@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.
package/scripts/sync.js CHANGED
@@ -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
@@ -503,6 +503,14 @@ var ATTACHED_FORWARD_DROPS_FILENAME = "attached-forward-drops.json";
503
503
  import { chmodSync as chmodSync2, lstatSync as lstatSync2, readFileSync, rmSync as rmSync3, statSync } from "fs";
504
504
  import { join as join2 } from "path";
505
505
 
506
+ // ../../packages/schema/src/drizzle/deferred-migrations.ts
507
+ var DEFERRED_MIGRATION_TAGS = [
508
+ "0031_audit_capture_by_time_index",
509
+ "0032_audit_capture_by_id_index",
510
+ "0033_audit_capture_location_index",
511
+ "0034_findings_read_indexes"
512
+ ];
513
+
506
514
  // ../../packages/schema/src/drizzle/sqlite-ddl.ts
507
515
  var SQLITE_MIGRATIONS = [
508
516
  {
@@ -620,6 +628,30 @@ var SQLITE_MIGRATIONS = [
620
628
  {
621
629
  tag: "0028_activity_session_probe_indexes",
622
630
  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"
631
+ },
632
+ {
633
+ tag: "0029_audit_capture_rollup_index",
634
+ 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');"
635
+ },
636
+ {
637
+ tag: "0030_audit_content_expiry",
638
+ 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;"
639
+ },
640
+ {
641
+ tag: "0031_audit_capture_by_time_index",
642
+ 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');"
643
+ },
644
+ {
645
+ tag: "0032_audit_capture_by_id_index",
646
+ 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');"
647
+ },
648
+ {
649
+ tag: "0033_audit_capture_location_index",
650
+ 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');"
651
+ },
652
+ {
653
+ tag: "0034_findings_read_indexes",
654
+ 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`);"
623
655
  }
624
656
  ];
625
657
 
@@ -20667,6 +20699,15 @@ var FindingCategory = external_exports.enum([
20667
20699
  ]).meta({ id: "FindingCategory" });
20668
20700
  var FindingOrigin = external_exports.enum(["in-flight", "at-rest"]).meta({ id: "FindingOrigin" });
20669
20701
  var FindingStatus = external_exports.enum(["open", "handled", "resolved", "dismissed"]).meta({ id: "FindingStatus" });
20702
+ var SyncFailureReason = external_exports.enum(["deployment_refused", "payload_invalid", "detached_undelivered"]).meta({ id: "SyncFailureReason" });
20703
+ var FindingDeliveryState = external_exports.enum(["sent", "queued", "not_sent", "never_offered", "local_scan"]).meta({ id: "FindingDeliveryState" });
20704
+ var FindingDelivery = external_exports.object({
20705
+ state: FindingDeliveryState,
20706
+ // The delivery time for `sent`; the failure time for `not_sent` when recorded.
20707
+ at: external_exports.iso.datetime().optional(),
20708
+ // Only on `not_sent`, and only when a known reason was recorded.
20709
+ reason: SyncFailureReason.optional()
20710
+ }).meta({ id: "FindingDelivery" });
20670
20711
  var ResolutionMethod = external_exports.enum([
20671
20712
  "enforced-in-flight",
20672
20713
  "fixed-at-source",
@@ -20723,7 +20764,10 @@ var FindingInstance = external_exports.object({
20723
20764
  // The session that event belongs to, when it has one — the seam a
20724
20765
  // per-instance "view session" link needs. Absent for events captured
20725
20766
  // outside a session.
20726
- sessionId: external_exports.string().optional()
20767
+ sessionId: external_exports.string().optional(),
20768
+ // The delivery state of the event above (see FindingDelivery). Optional so
20769
+ // readers that do not project it stay valid.
20770
+ delivery: FindingDelivery.optional()
20727
20771
  }).meta({ id: "FindingInstance" });
20728
20772
  var FindingGroup = external_exports.object({
20729
20773
  id: external_exports.string(),
@@ -20775,7 +20819,10 @@ var FindingFacets = external_exports.object({
20775
20819
  // Host tool (attributes.tool_name). Present only on the instance-level
20776
20820
  // reads, which can filter by it; the type-level read omits the dimension
20777
20821
  // because a group spans tools.
20778
- tool: external_exports.array(FindingFacetItem).optional()
20822
+ tool: external_exports.array(FindingFacetItem).optional(),
20823
+ // Delivery states (FindingDeliveryState). Present only on the
20824
+ // instance-level reads, like `tool`.
20825
+ deployment: external_exports.array(FindingFacetItem).optional()
20779
20826
  }).meta({ id: "FindingFacets" });
20780
20827
  var FindingTypeSummary = FindingGroup.omit({ instances: true, match: true }).meta({
20781
20828
  id: "FindingTypeSummary"
@@ -20886,6 +20933,8 @@ var ListFindingInstancesQuery = external_exports.object({
20886
20933
  // Exact host-tool names (attributes.tool_name, e.g. 'Bash'). A real filter,
20887
20934
  // where the free-text `q` can only match the rendered "via Bash" label.
20888
20935
  tool: external_exports.array(external_exports.string()).optional(),
20936
+ // The delivery state of each finding's event (see FindingDelivery).
20937
+ deployment: external_exports.array(FindingDeliveryState).optional(),
20889
20938
  // Exact repository / file-path matches, for the drill-down out of the
20890
20939
  // locations view. A row whose event carries no repo/file matches neither.
20891
20940
  repo: external_exports.string().optional(),
@@ -20906,6 +20955,10 @@ var ListFindingInstancesResponse = external_exports.object({
20906
20955
  items: external_exports.array(FindingInstanceDetail),
20907
20956
  nextCursor: external_exports.string().nullable()
20908
20957
  }).meta({ id: "ListFindingInstancesResponse" });
20958
+ var ListFindingInstancesPage = external_exports.object({
20959
+ items: external_exports.array(FindingInstanceDetail),
20960
+ nextCursor: external_exports.string().nullable()
20961
+ }).meta({ id: "ListFindingInstancesPage" });
20909
20962
  var FindingLocationSummary = external_exports.object({
20910
20963
  // Opaque, stable, minted from the pair by encodeLocationId. It exists
20911
20964
  // because a location's identity is two values and a URL param carries one:
@@ -20948,6 +21001,8 @@ var ListFindingLocationsQuery = external_exports.object({
20948
21001
  // instances that match, and folds its status from those.
20949
21002
  status: external_exports.array(FindingStatus).optional(),
20950
21003
  tool: external_exports.array(external_exports.string()).optional(),
21004
+ // The delivery state of each finding's event (see FindingDelivery).
21005
+ deployment: external_exports.array(FindingDeliveryState).optional(),
20951
21006
  q: external_exports.string().optional(),
20952
21007
  sessionId: external_exports.string().optional(),
20953
21008
  from: external_exports.iso.datetime().optional(),
@@ -21150,6 +21205,10 @@ var CaptureAttributes = external_exports.object({
21150
21205
  // to 'allow' — the enforcement audit trail's link back to the grant that
21151
21206
  // authorized the bypass.
21152
21207
  exception_ids: external_exports.array(external_exports.guid()).optional(),
21208
+ // The persisted spellings of EventMetadata's messageId/conversationId — the
21209
+ // join back to the `llm_call` leaf for the same assistant turn.
21210
+ message_id: external_exports.string().optional(),
21211
+ conversation_id: external_exports.string().optional(),
21153
21212
  // Whole milliseconds this capture's inspection blocked its caller — the
21154
21213
  // plugin's own added latency (see EventMetadata.inspectionMs, whose value
21155
21214
  // this is). Promoted to the `inspection_ms` generated column so the facet is
@@ -21158,7 +21217,19 @@ var CaptureAttributes = external_exports.object({
21158
21217
  // inline json_extract and is not itself an optimization.
21159
21218
  // ABSENT on replayed captures (backfill / worktree scan) and on rows written
21160
21219
  // before the measurement shipped — never present as a placeholder 0.
21161
- inspection_ms: external_exports.number().int().nonnegative().optional()
21220
+ inspection_ms: external_exports.number().int().nonnegative().optional(),
21221
+ // What a `redact` this capture could not carry out became instead (see
21222
+ // EventMetadata.redactDegradedTo, whose value this is). Present only when a
21223
+ // degrade actually happened, so absence is the ordinary case rather than a
21224
+ // reader having to distinguish it from a zero.
21225
+ //
21226
+ // PER CAPTURE, while `inspection_findings.action_taken` is per finding —
21227
+ // so on a multi-finding row this does not say which finding degraded, and
21228
+ // its presence does not mean the fallback decided the capture's action. A
21229
+ // capture denied by another finding's own Block policy carries `block`
21230
+ // here too. The full statement is on EventMetadata.redactDegradedTo; it is
21231
+ // repeated rather than referenced because a store reader opens this file.
21232
+ redact_degraded_to: ActionTaken.optional()
21162
21233
  }).catchall(external_exports.unknown());
21163
21234
  var ToolCallInspection = external_exports.object({
21164
21235
  ruleId: external_exports.string().min(1),
@@ -21357,7 +21428,17 @@ var AuditEvent = external_exports.object({
21357
21428
  /** `share` to a first-party/internal destination. */
21358
21429
  internal: external_exports.boolean(),
21359
21430
  /** Event needs review (e.g. unverified egress). */
21360
- flagged: external_exports.boolean()
21431
+ flagged: external_exports.boolean(),
21432
+ /**
21433
+ * The body this event's `title` is drawn from was cleared by local body
21434
+ * expiry, so an EMPTY title here means "gone", not "never had one".
21435
+ *
21436
+ * A separate flag rather than a sentinel written into `title`: the title is
21437
+ * rendered text, and a store-layer module that invented display copy for it
21438
+ * would be choosing words the view is supposed to choose. Additive and
21439
+ * defaulted, so an older producer still validates.
21440
+ */
21441
+ bodyExpired: external_exports.boolean().default(false)
21361
21442
  }).meta({ id: "ActivityAuditEvent" });
21362
21443
  var ActivitySessionSummary = external_exports.object({
21363
21444
  id: external_exports.string(),
@@ -22698,6 +22779,12 @@ var EventMetadata = external_exports.object({
22698
22779
  // to 'allow' — the enforcement audit trail's link back to the grant that
22699
22780
  // authorized the bypass. Absent on captures where no exception applied.
22700
22781
  exceptionIds: external_exports.array(external_exports.guid()).optional(),
22782
+ // The assistant message this capture belongs to, and the conversation it sits
22783
+ // in — set by the browser extension's network capture so a stored `response`
22784
+ // row can be joined to the `llm_call` leaf describing the same turn. Absent
22785
+ // on every other capture path, which has no such id.
22786
+ messageId: external_exports.string().optional(),
22787
+ conversationId: external_exports.string().optional(),
22701
22788
  // How long THIS capture's inspection blocked its caller, in whole
22702
22789
  // milliseconds — the plugin's own added latency, NOT the LLM call it sat in
22703
22790
  // front of. Measured inside `capture()` (@akasecurity/plugin-sdk) across
@@ -22710,7 +22797,37 @@ var EventMetadata = external_exports.object({
22710
22797
  // Absent is also what every pre-measurement client writes, and what a
22711
22798
  // clock failure degrades to — a reader must treat absence as "not measured"
22712
22799
  // and never as a zero, which would read as "inspection is free".
22713
- inspectionMs: external_exports.number().int().nonnegative().optional()
22800
+ inspectionMs: external_exports.number().int().nonnegative().optional(),
22801
+ // What a `redact` this capture COULD NOT CARRY OUT became instead — the
22802
+ // workspace's `redactFallback`, applied because the field could not be
22803
+ // masked in place (a shell command, a URL, or any argument on a host whose
22804
+ // hook contract offers no rewrite channel).
22805
+ //
22806
+ // It exists because the action alone cannot say why. A finding recorded as
22807
+ // `warn` reads identically whether its detection was ASSIGNED Warn or was
22808
+ // assigned Redact on a field that could not take one — and those are
22809
+ // different facts about the same row: the first is a policy the user chose,
22810
+ // the second is a masking the host could not perform. Absent means no
22811
+ // degrade happened, which is every ordinary capture.
22812
+ //
22813
+ // TWO LIMITS a reader of a stored row has to know, because the grain here
22814
+ // is the CAPTURE while `actionTaken` is per FINDING:
22815
+ //
22816
+ // - It does not say WHICH finding degraded. A capture carrying a degraded
22817
+ // `redact` alongside a finding ASSIGNED the same action stores both
22818
+ // identically and one reason for the pair; attributing it to both
22819
+ // describes the assigned one wrongly, and to neither loses the degrade.
22820
+ // - PRESENCE IS NOT CAUSATION. The value is the action the lost redact
22821
+ // became, not the reason the capture ended as it did — a capture denied
22822
+ // by some other finding's own Block policy still carries `block` here,
22823
+ // and clearing the workspace's fallback would not have let it through.
22824
+ // Gate on the value against what a fallback can produce; never read the
22825
+ // field's presence as "this was the fallback's doing".
22826
+ //
22827
+ // Both are pinned as behaviour in @akasecurity/plugin-sdk's runtime suite.
22828
+ // Closing either means moving the reason onto the finding row, which
22829
+ // already carries its own action.
22830
+ redactDegradedTo: ActionTaken.optional()
22714
22831
  }).meta({ id: "EventMetadata" });
22715
22832
  var Event = external_exports.object({
22716
22833
  id: external_exports.guid(),
@@ -22820,7 +22937,32 @@ var RotateKeyInput = external_exports.object({
22820
22937
  confirmation: external_exports.string()
22821
22938
  });
22822
22939
 
22940
+ // ../../packages/schema/src/zod/finding-delivery.ts
22941
+ var KNOWN_REASONS = SyncFailureReason.options;
22942
+ function knownReason(value) {
22943
+ return value !== null && KNOWN_REASONS.includes(value) ? value : void 0;
22944
+ }
22945
+ function deriveFindingDelivery(row) {
22946
+ if (row.kind === "code_change") return { state: "local_scan" };
22947
+ if (row.syncedAt !== null && row.syncedAt > 0) {
22948
+ return { state: "sent", at: epochMillisToIso(row.syncedAt) };
22949
+ }
22950
+ if (row.syncedAt !== null) {
22951
+ const reason = knownReason(row.syncFailure);
22952
+ return {
22953
+ state: "not_sent",
22954
+ ...row.syncFailedAt === null ? {} : { at: epochMillisToIso(row.syncFailedAt) },
22955
+ ...reason === void 0 ? {} : { reason }
22956
+ };
22957
+ }
22958
+ if (row.outboxOwed === 1 || row.syncClaimedAt !== null) return { state: "queued" };
22959
+ return { state: "never_offered" };
22960
+ }
22961
+
22823
22962
  // ../../packages/schema/src/zod/findings-group-build.ts
22963
+ function lookupOwn(map2, key) {
22964
+ return Object.hasOwn(map2, key) ? map2[key] : void 0;
22965
+ }
22824
22966
  function toApiAction(dbVal) {
22825
22967
  const map2 = {
22826
22968
  log: "monitored",
@@ -22829,7 +22971,7 @@ function toApiAction(dbVal) {
22829
22971
  warn: "warned",
22830
22972
  allow: "allowed"
22831
22973
  };
22832
- return map2[dbVal] ?? "allowed";
22974
+ return lookupOwn(map2, dbVal) ?? "allowed";
22833
22975
  }
22834
22976
  function toApiCategory(dbVal) {
22835
22977
  if (dbVal === "code_context") return "source_code";
@@ -22837,13 +22979,18 @@ function toApiCategory(dbVal) {
22837
22979
  return parsed2.success ? parsed2.data : "custom";
22838
22980
  }
22839
22981
  function toApiProvider(sourceTool) {
22840
- return TOOL_TO_HARNESS[sourceTool] ?? HARNESS.Api;
22982
+ return lookupOwn(TOOL_TO_HARNESS, sourceTool) ?? HARNESS.Api;
22841
22983
  }
22842
- var STATUS_PRECEDENCE = ["open", "handled", "dismissed", "resolved"];
22984
+ var FINDING_STATUS_PRECEDENCE = [
22985
+ "open",
22986
+ "handled",
22987
+ "dismissed",
22988
+ "resolved"
22989
+ ];
22843
22990
  function foldGroupStatus(instanceStatuses) {
22844
22991
  const statuses = new Set(instanceStatuses.filter((s) => s !== void 0));
22845
22992
  if (statuses.size === 0) return void 0;
22846
- for (const candidate of STATUS_PRECEDENCE) {
22993
+ for (const candidate of FINDING_STATUS_PRECEDENCE) {
22847
22994
  if (statuses.has(candidate)) return candidate;
22848
22995
  }
22849
22996
  return void 0;
@@ -22950,11 +23097,16 @@ function applyFindingFilters(types, opts) {
22950
23097
  }
22951
23098
  return filtered;
22952
23099
  }
22953
- var SEVERITY_ORDER = { critical: 0, high: 1, medium: 2, low: 3 };
22954
- var SEVERITY_RANK = SEVERITY_ORDER;
23100
+ function rankByOrder(members2) {
23101
+ return Object.fromEntries(members2.map((member, index) => [member, index]));
23102
+ }
23103
+ var SEVERITY_RANK = rankByOrder(Severity.options);
23104
+ function severityRank(severity) {
23105
+ return lookupOwn(SEVERITY_RANK, severity);
23106
+ }
22955
23107
  function compareFindingGroupOrder(a, b) {
22956
- const rankA = SEVERITY_RANK[a.severity] ?? -1;
22957
- const rankB = SEVERITY_RANK[b.severity] ?? -1;
23108
+ const rankA = severityRank(a.severity) ?? -1;
23109
+ const rankB = severityRank(b.severity) ?? -1;
22958
23110
  const severityDiff = rankA - rankB;
22959
23111
  if (severityDiff !== 0) return severityDiff;
22960
23112
  const recencyDiff = b.latestDetectedAt.localeCompare(a.latestDetectedAt);
@@ -23029,6 +23181,20 @@ function computeFindingFacets(allTypes, opts) {
23029
23181
  }
23030
23182
 
23031
23183
  // ../../packages/schema/src/zod/findings-flat-build.ts
23184
+ function compareCodePoints(a, b) {
23185
+ const aIter = a[Symbol.iterator]();
23186
+ const bIter = b[Symbol.iterator]();
23187
+ for (; ; ) {
23188
+ const aNext = aIter.next();
23189
+ const bNext = bIter.next();
23190
+ if (aNext.done && bNext.done) return 0;
23191
+ if (aNext.done) return -1;
23192
+ if (bNext.done) return 1;
23193
+ const aPoint = aNext.value.codePointAt(0) ?? 0;
23194
+ const bPoint = bNext.value.codePointAt(0) ?? 0;
23195
+ if (aPoint !== bPoint) return aPoint - bPoint;
23196
+ }
23197
+ }
23032
23198
  function rowHaystack(row) {
23033
23199
  return [
23034
23200
  row.ruleId,
@@ -23053,6 +23219,8 @@ function matchesDimension(row, opts, dimension) {
23053
23219
  return !opts.actions?.length || opts.actions.includes(toApiAction(row.actionTaken));
23054
23220
  case "statuses":
23055
23221
  return !opts.statuses?.length || row.status !== void 0 && opts.statuses.includes(row.status);
23222
+ case "deliveries":
23223
+ return !opts.deliveries?.length || row.delivery !== void 0 && opts.deliveries.includes(row.delivery.state);
23056
23224
  case "tools":
23057
23225
  return !opts.tools?.length || row.toolName !== void 0 && opts.tools.includes(row.toolName);
23058
23226
  // An EMPTY value is a real filter here, not an absent one. The location
@@ -23079,6 +23247,7 @@ var DIMENSIONS = [
23079
23247
  "providers",
23080
23248
  "actions",
23081
23249
  "statuses",
23250
+ "deliveries",
23082
23251
  "tools",
23083
23252
  "repo",
23084
23253
  "file",
@@ -23092,10 +23261,19 @@ function matchesInstanceFilters(row, opts, except) {
23092
23261
  return true;
23093
23262
  }
23094
23263
  function toItems(counts) {
23095
- return [...counts.entries()].map(([value, count]) => ({ value, count })).sort((a, b) => b.count - a.count || a.value.localeCompare(b.value));
23264
+ return [...counts.entries()].map(([value, count]) => ({ value, count })).sort(
23265
+ (a, b) => b.count - a.count || a.value.localeCompare(b.value) || // localeCompare reports canonically-equivalent strings (an NFC and an
23266
+ // NFD spelling of the same text) as equal, so a count tie between
23267
+ // them would otherwise be ordered by whichever the Map iteration
23268
+ // produced. compareCodePoints breaks that tie deterministically, which
23269
+ // makes this a TOTAL order — not one that agrees with SQL collation,
23270
+ // which it need not: foldFacetTuples runs this same sort over grouped
23271
+ // tuples, so both paths order facets identically by construction.
23272
+ compareCodePoints(a.value, b.value)
23273
+ );
23096
23274
  }
23097
- function bump(counts, value) {
23098
- counts.set(value, (counts.get(value) ?? 0) + 1);
23275
+ function bump(counts, value, by = 1) {
23276
+ counts.set(value, (counts.get(value) ?? 0) + by);
23099
23277
  }
23100
23278
  function createInstanceFacetAccumulator(opts) {
23101
23279
  const severity = /* @__PURE__ */ new Map();
@@ -23104,6 +23282,7 @@ function createInstanceFacetAccumulator(opts) {
23104
23282
  const action = /* @__PURE__ */ new Map();
23105
23283
  const status = /* @__PURE__ */ new Map();
23106
23284
  const tool = /* @__PURE__ */ new Map();
23285
+ const deployment = /* @__PURE__ */ new Map();
23107
23286
  return {
23108
23287
  add(row) {
23109
23288
  if (matchesInstanceFilters(row, opts, "severity")) bump(severity, row.severity);
@@ -23118,6 +23297,9 @@ function createInstanceFacetAccumulator(opts) {
23118
23297
  if (row.toolName !== void 0 && matchesInstanceFilters(row, opts, "tools")) {
23119
23298
  bump(tool, row.toolName);
23120
23299
  }
23300
+ if (row.delivery !== void 0 && matchesInstanceFilters(row, opts, "deliveries")) {
23301
+ bump(deployment, row.delivery.state);
23302
+ }
23121
23303
  },
23122
23304
  facets: () => ({
23123
23305
  severity: toItems(severity),
@@ -23125,7 +23307,8 @@ function createInstanceFacetAccumulator(opts) {
23125
23307
  provider: toItems(provider),
23126
23308
  action: toItems(action),
23127
23309
  status: toItems(status),
23128
- tool: toItems(tool)
23310
+ tool: toItems(tool),
23311
+ deployment: toItems(deployment)
23129
23312
  })
23130
23313
  };
23131
23314
  }
@@ -23139,6 +23322,7 @@ function toInstanceDetail(row) {
23139
23322
  ...row.toolName === void 0 ? {} : { toolName: row.toolName },
23140
23323
  eventId: row.eventId,
23141
23324
  ...row.sessionId === void 0 ? {} : { sessionId: row.sessionId },
23325
+ ...row.delivery === void 0 ? {} : { delivery: row.delivery },
23142
23326
  ...row.user === void 0 ? {} : { user: row.user },
23143
23327
  action: toApiAction(row.actionTaken),
23144
23328
  detectedAt: row.occurredAt,
@@ -23153,12 +23337,6 @@ function toInstanceDetail(row) {
23153
23337
  policy: { id: `category:${category}`, name: category }
23154
23338
  };
23155
23339
  }
23156
- var SEVERITY_ORDER2 = {
23157
- critical: 0,
23158
- high: 1,
23159
- medium: 2,
23160
- low: 3
23161
- };
23162
23340
  function newLocationAccumulator() {
23163
23341
  return {
23164
23342
  instanceCount: 0,
@@ -23173,7 +23351,7 @@ function newLocationAccumulator() {
23173
23351
  }
23174
23352
  function addToLocation(acc, row) {
23175
23353
  acc.instanceCount += 1;
23176
- const rank = SEVERITY_ORDER2[row.severity] ?? Number.MAX_SAFE_INTEGER - 1;
23354
+ const rank = severityRank(row.severity) ?? Number.MAX_SAFE_INTEGER - 1;
23177
23355
  if (rank < acc.maxSeverityRank) {
23178
23356
  acc.maxSeverityRank = rank;
23179
23357
  acc.maxSeverity = row.severity;
@@ -23183,15 +23361,15 @@ function addToLocation(acc, row) {
23183
23361
  acc.ruleIds.add(row.ruleId);
23184
23362
  }
23185
23363
  function compareLocationOrder(a, b) {
23186
- const rankA = SEVERITY_ORDER2[a.maxSeverity] ?? -1;
23187
- const rankB = SEVERITY_ORDER2[b.maxSeverity] ?? -1;
23364
+ const rankA = severityRank(a.maxSeverity) ?? -1;
23365
+ const rankB = severityRank(b.maxSeverity) ?? -1;
23188
23366
  if (rankA !== rankB) return rankA - rankB;
23189
23367
  if (a.latestDetectedAt !== b.latestDetectedAt) {
23190
23368
  return a.latestDetectedAt < b.latestDetectedAt ? 1 : -1;
23191
23369
  }
23192
- if (a.repo !== b.repo) return a.repo < b.repo ? -1 : 1;
23193
- if (a.file !== b.file) return a.file < b.file ? -1 : 1;
23194
- return 0;
23370
+ const repoDiff = compareCodePoints(a.repo, b.repo);
23371
+ if (repoDiff !== 0) return repoDiff;
23372
+ return compareCodePoints(a.file, b.file);
23195
23373
  }
23196
23374
  function encodeLocationId(repo, file2) {
23197
23375
  return `${encodePart(repo)}/${encodePart(file2)}`;
@@ -23266,6 +23444,11 @@ var Policy = external_exports.object({
23266
23444
  // test `prohibitedModels` passes and `reversibleRuleIds` fails.
23267
23445
  provenance: PolicyProvenance.optional()
23268
23446
  }).meta({ id: "Policy" });
23447
+ var KNOWN_BUILTIN_IDS = ["monitor", "warn", "redact", "vault", "block"];
23448
+ var BuiltinPolicyId = external_exports.enum(KNOWN_BUILTIN_IDS).meta({ id: "BuiltinPolicyId" });
23449
+ var RedactFallback = BuiltinPolicyId.extract(["monitor", "warn", "block"]).meta({
23450
+ id: "RedactFallback"
23451
+ });
23269
23452
  var PolicyBundle = external_exports.object({
23270
23453
  version: external_exports.string(),
23271
23454
  policies: external_exports.array(Policy),
@@ -23313,6 +23496,16 @@ var PolicyBundle = external_exports.object({
23313
23496
  // control plane), so no name resolution stands between the decision and the
23314
23497
  // comparison.
23315
23498
  prohibitedModels: external_exports.array(external_exports.string()).optional(),
23499
+ // What a resolved `redact` becomes on a field the host cannot rewrite, as
23500
+ // the ORGANIZATION would have it. Merged raise-only against the device's own
23501
+ // `WorkspaceSettings.redactFallback` (see strongerRedactFallback below), so
23502
+ // a control plane can tighten a machine and never loosen one — the same
23503
+ // direction `mergeRaiseOnly` enforces for policies.
23504
+ //
23505
+ // Optional so an older backend, and an older on-disk cache, still parses;
23506
+ // absent leaves the device's own setting in force, which is the behaviour
23507
+ // that predates the field and the safe direction to default.
23508
+ redactFallback: RedactFallback.optional(),
23316
23509
  customKeywords: external_exports.array(external_exports.string()),
23317
23510
  fetchedAt: external_exports.iso.datetime()
23318
23511
  }).meta({ id: "PolicyBundle" });
@@ -23342,11 +23535,6 @@ function severityFloorPolicy(category) {
23342
23535
  const peak = CATEGORY_PEAK_SEVERITY[category];
23343
23536
  return peak === "critical" || peak === "high" ? "warn" : "monitor";
23344
23537
  }
23345
- var KNOWN_BUILTIN_IDS = ["monitor", "warn", "redact", "vault", "block"];
23346
- var BuiltinPolicyId = external_exports.enum(KNOWN_BUILTIN_IDS).meta({ id: "BuiltinPolicyId" });
23347
- var RedactFallback = BuiltinPolicyId.extract(["monitor", "warn", "block"]).meta({
23348
- id: "RedactFallback"
23349
- });
23350
23538
  var BUILTIN_ORDER = KNOWN_BUILTIN_IDS;
23351
23539
  var BUILTIN_POLICY_SPECS = {
23352
23540
  monitor: {
@@ -23402,6 +23590,11 @@ function isActionAtLeast(action, floor) {
23402
23590
  function strongerAction(a, b) {
23403
23591
  return actionRank(a) >= actionRank(b) ? a : b;
23404
23592
  }
23593
+ function strongerRedactFallback(local, remote) {
23594
+ if (remote === void 0) return local;
23595
+ const localAction = builtinPolicyToAction(local);
23596
+ return localAction === strongerAction(localAction, builtinPolicyToAction(remote)) ? local : remote;
23597
+ }
23405
23598
  function weakestBuiltinAtLeast(floor) {
23406
23599
  return KNOWN_BUILTIN_IDS.find((id) => isActionAtLeast(builtinPolicyToAction(id), floor)) ?? "block";
23407
23600
  }
@@ -23642,7 +23835,7 @@ var VaultConsent = external_exports.object({
23642
23835
  });
23643
23836
 
23644
23837
  // ../../packages/schema/src/zod/local.ts
23645
- var WORKSPACE_SETTINGS_SPEC_VERSION = 7;
23838
+ var WORKSPACE_SETTINGS_SPEC_VERSION = 8;
23646
23839
  var MODEL_JUDGE_PAYLOAD_VERSION = 1;
23647
23840
  var RunMode = external_exports.enum(["standalone", "attached"]);
23648
23841
  var ControlPlaneConnection = external_exports.object({
@@ -23662,6 +23855,15 @@ var HistorySyncConsent = external_exports.object({
23662
23855
  payloadVersion: external_exports.number().int().positive(),
23663
23856
  endpoint: external_exports.string()
23664
23857
  });
23858
+ var BODY_RETENTION_DEFAULT_DAYS = 30;
23859
+ var BodyRetention = external_exports.object({
23860
+ enabled: external_exports.boolean().default(false),
23861
+ // Never 0, and the ceiling is a fat-finger guard rather than a policy
23862
+ // limit — `enabled` is the real gate. A low value cannot reach a row the
23863
+ // sync ledger still owes: the sweep's age filter only ever NARROWS a
23864
+ // candidate set that is already bounded by "delivered, or never owed".
23865
+ retainDays: external_exports.number().int().min(1).max(3650).default(BODY_RETENTION_DEFAULT_DAYS)
23866
+ }).meta({ id: "BodyRetention" });
23665
23867
  var WorkspaceSettings = external_exports.object({
23666
23868
  specVersion: external_exports.number().int().positive().default(WORKSPACE_SETTINGS_SPEC_VERSION),
23667
23869
  runMode: RunMode.default("standalone"),
@@ -23710,7 +23912,13 @@ var WorkspaceSettings = external_exports.object({
23710
23912
  // carry prompt/reply/tool-output text in `content`; the key name predates
23711
23913
  // both widenings. Absent until granted, and a grant for a different endpoint
23712
23914
  // or an older payload no longer counts.
23713
- historySyncConsent: HistorySyncConsent.optional()
23915
+ historySyncConsent: HistorySyncConsent.optional(),
23916
+ // Local body expiry (see BodyRetention). Off until switched on; expiring a
23917
+ // body never removes the row or its findings.
23918
+ bodyRetention: BodyRetention.default({
23919
+ enabled: false,
23920
+ retainDays: BODY_RETENTION_DEFAULT_DAYS
23921
+ })
23714
23922
  });
23715
23923
  function defaultWorkspaceSettings() {
23716
23924
  return WorkspaceSettings.parse({});
@@ -23805,12 +24013,15 @@ function toCaptureAttributes(event) {
23805
24013
  ...metadata?.traceId !== void 0 ? { trace_id: metadata.traceId } : {},
23806
24014
  ...metadata?.exceptionIds !== void 0 ? { exception_ids: metadata.exceptionIds } : {},
23807
24015
  ...metadata?.inspectionMs !== void 0 ? { inspection_ms: metadata.inspectionMs } : {},
24016
+ ...metadata?.redactDegradedTo !== void 0 ? { redact_degraded_to: metadata.redactDegradedTo } : {},
23808
24017
  // `model`/`turnIndex` have no dedicated CaptureAttributes field (no writer
23809
24018
  // has ever populated either), but every legacy metadata key still rides
23810
24019
  // the bag rather than being silently dropped — CaptureAttributes'
23811
24020
  // `.catchall(z.unknown())` carries the long tail.
23812
24021
  ...metadata?.model !== void 0 ? { model: metadata.model } : {},
23813
- ...metadata?.turnIndex !== void 0 ? { turn_index: metadata.turnIndex } : {}
24022
+ ...metadata?.turnIndex !== void 0 ? { turn_index: metadata.turnIndex } : {},
24023
+ ...metadata?.messageId !== void 0 ? { message_id: metadata.messageId } : {},
24024
+ ...metadata?.conversationId !== void 0 ? { conversation_id: metadata.conversationId } : {}
23814
24025
  };
23815
24026
  }
23816
24027
  function captureDefinitionVersion(finding) {
@@ -23838,13 +24049,22 @@ var ManagedSettingKey = external_exports.enum([
23838
24049
  "vaultInlineReveal",
23839
24050
  "modelJudgeConsent",
23840
24051
  "dataSharesInPlace",
23841
- "redactFallback"
24052
+ "redactFallback",
24053
+ // Pins the toggle and the day count together — see BodyRetention on why the
24054
+ // two are one unit. An administrator mandating a window wants the count
24055
+ // enforced with it, not one a user can widen while the toggle stays on.
24056
+ "bodyRetention"
23842
24057
  ]).meta({ id: "ManagedSettingKey" });
23843
24058
  function isManagedSettingKey(value) {
23844
24059
  return ManagedSettingKey.safeParse(value).success;
23845
24060
  }
23846
24061
  var ManagedSettingsValues = external_exports.object({
23847
24062
  runMode: external_exports.enum(["standalone", "attached"]).optional(),
24063
+ // `controlPlane` and `bodyRetention` are the two nested values, and both are
24064
+ // plain, non-strict objects: a key under either that this build does not know
24065
+ // is stripped and nothing reports it. The unknown-value split in
24066
+ // ManagedSettings below classifies top-level names only, so it stops at
24067
+ // these boundaries.
23848
24068
  controlPlane: external_exports.object({
23849
24069
  endpoint: external_exports.string().min(1),
23850
24070
  label: external_exports.string().min(1).optional()
@@ -23855,7 +24075,8 @@ var ManagedSettingsValues = external_exports.object({
23855
24075
  vaultInlineReveal: external_exports.enum(["masked", "full", "off"]).optional(),
23856
24076
  modelJudgeConsent: external_exports.boolean().optional(),
23857
24077
  dataSharesInPlace: external_exports.boolean().optional(),
23858
- redactFallback: RedactFallback.optional()
24078
+ redactFallback: RedactFallback.optional(),
24079
+ bodyRetention: BodyRetention.optional()
23859
24080
  }).meta({ id: "ManagedSettingsValues" });
23860
24081
  var ManagedSettings = external_exports.object({
23861
24082
  specVersion: external_exports.number().int().positive().default(MANAGED_SETTINGS_SPEC_VERSION),
@@ -23863,7 +24084,21 @@ var ManagedSettings = external_exports.object({
23863
24084
  // decision from a bug. Absent renders as a generic "your organization".
23864
24085
  organization: external_exports.string().min(1).optional(),
23865
24086
  // What the administrator pinned.
23866
- values: ManagedSettingsValues.default({}),
24087
+ //
24088
+ // Parsed as a RECORD rather than as the nested schema, and split below for
24089
+ // the same reason `lockedFields` is parsed as names: a plain `z.object`
24090
+ // drops an unrecognised key and succeeds, so a pin this build does not know
24091
+ // vanished and nothing anywhere said so. A pin with no lock is a supported
24092
+ // shape — it is a DEFAULT the user may still change — so that silence hit
24093
+ // exactly the file an administrator is most likely to write while a fleet
24094
+ // is mid-upgrade.
24095
+ //
24096
+ // Splitting here rather than calling `.strict()`: strict would REFUSE the
24097
+ // file, which is the outcome the lock half already rejected — an older
24098
+ // build then runs entirely unmanaged, every pin and lock gone. A bad KNOWN
24099
+ // value still fails, because the nested schema is re-run over the known
24100
+ // subset and its issues are re-raised on this parse.
24101
+ values: external_exports.record(external_exports.string(), external_exports.unknown()).default({}),
23867
24102
  // Which of those the user may not change. A key here with no matching value
23868
24103
  // freezes whatever the user last chose; a value with no lock is a DEFAULT
23869
24104
  // the user may still override. The two are separable on purpose.
@@ -23876,17 +24111,31 @@ var ManagedSettings = external_exports.object({
23876
24111
  // the fleets most likely to carry a version skew. A name outside the enum
23877
24112
  // is still never HONOURED: the lockable set stays explicit above.
23878
24113
  lockedFields: external_exports.array(external_exports.string()).default([])
23879
- }).transform(({ lockedFields, ...rest }) => {
24114
+ }).transform(({ lockedFields, values, ...rest }, ctx) => {
23880
24115
  const known = [];
23881
24116
  const unknown2 = [];
23882
24117
  for (const name of lockedFields) {
23883
24118
  if (isManagedSettingKey(name)) known.push(name);
23884
24119
  else unknown2.push(name);
23885
24120
  }
24121
+ const knownValues = /* @__PURE__ */ Object.create(null);
24122
+ const unknownValues = [];
24123
+ for (const [name, value] of Object.entries(values)) {
24124
+ if (Object.hasOwn(ManagedSettingsValues.shape, name)) knownValues[name] = value;
24125
+ else unknownValues.push(name);
24126
+ }
24127
+ const pinned = ManagedSettingsValues.safeParse(knownValues);
24128
+ if (!pinned.success) {
24129
+ for (const issue2 of pinned.error.issues)
24130
+ ctx.addIssue({ ...issue2, path: ["values", ...issue2.path] });
24131
+ return external_exports.NEVER;
24132
+ }
23886
24133
  return {
23887
24134
  ...rest,
24135
+ values: pinned.data,
23888
24136
  lockedFields: known,
23889
- ...unknown2.length > 0 ? { unknownLockedFields: unknown2 } : {}
24137
+ ...unknown2.length > 0 ? { unknownLockedFields: unknown2 } : {},
24138
+ ...unknownValues.length > 0 ? { unknownValueFields: unknownValues } : {}
23890
24139
  };
23891
24140
  }).meta({ id: "ManagedSettings" });
23892
24141
 
@@ -24150,7 +24399,23 @@ var SaveSettingsInput = external_exports.object({
24150
24399
  modelJudgeConsent: ModelJudgeConsentChoice,
24151
24400
  historySyncConsent: HistorySyncConsentChoice,
24152
24401
  vaultConsent: external_exports.string(),
24153
- vaultInlineReveal: external_exports.string()
24402
+ vaultInlineReveal: external_exports.string(),
24403
+ // Widened to `string` like its neighbours rather than typed as
24404
+ // `RedactFallback`, on this module's own layering rule: shape here, VALUE at
24405
+ // the call site, so the domain check receives the type it was written for.
24406
+ //
24407
+ // NOT because a narrower schema would reject differently. `parseActionInput`
24408
+ // is a `safeParse` wrapper and throws for no field schema, so either spelling
24409
+ // reaches a recoverable `{ ok: false }` and there is no rejected promise to
24410
+ // trade against. The real cost runs the other way and is the part worth
24411
+ // knowing: a value this schema admits and the domain enum then rejects lands
24412
+ // on the action's shared refusal, which names NO field, where a shape
24413
+ // rejection reaches `malformedInput` and names the schema key.
24414
+ redactFallback: external_exports.string(),
24415
+ // Shape only, the way the enum fields above are strings only: the RANGE is
24416
+ // `BodyRetention`'s and the action checks it there, so there is one place
24417
+ // that decides what a legal horizon is rather than two that can drift.
24418
+ bodyRetention: external_exports.object({ enabled: external_exports.boolean(), retainDays: external_exports.number() })
24154
24419
  });
24155
24420
  var AttachInput = external_exports.object({
24156
24421
  endpoint: external_exports.string(),
@@ -24322,6 +24587,52 @@ function reviewSeverityRank(reasons) {
24322
24587
  return Math.min(...reasons.map((r) => REVIEW_SEVERITY_RANK[r]));
24323
24588
  }
24324
24589
 
24590
+ // ../../packages/schema/src/zod/web-capture.ts
24591
+ var WebUsageSource = external_exports.enum(["site", "estimated", "none"]);
24592
+ var WebUsage = external_exports.object({
24593
+ inputTokens: external_exports.number().int().nonnegative().optional(),
24594
+ outputTokens: external_exports.number().int().nonnegative().optional(),
24595
+ cacheReadInputTokens: external_exports.number().int().nonnegative().optional(),
24596
+ cacheCreationInputTokens: external_exports.number().int().nonnegative().optional()
24597
+ });
24598
+ var WebToolCall = external_exports.object({
24599
+ toolUseId: external_exports.string().min(1),
24600
+ toolName: external_exports.string().min(1),
24601
+ target: external_exports.string().optional(),
24602
+ isError: external_exports.boolean().optional(),
24603
+ inputSize: external_exports.number().int().nonnegative().optional(),
24604
+ outputSize: external_exports.number().int().nonnegative().optional()
24605
+ });
24606
+ var WebExchange = external_exports.object({
24607
+ messageId: external_exports.string().min(1),
24608
+ startedAt: external_exports.iso.datetime(),
24609
+ model: external_exports.string().optional(),
24610
+ usage: WebUsage.optional(),
24611
+ usageSource: WebUsageSource,
24612
+ stopReason: external_exports.string().optional(),
24613
+ conversationId: external_exports.string().optional(),
24614
+ turnIndex: external_exports.number().int().nonnegative().optional(),
24615
+ toolCalls: external_exports.array(WebToolCall).default([]),
24616
+ // Absent when the adapter recovered no text. Capped by the caller at
24617
+ // RESPONSE_TEXT_MAX_BYTES; `truncated` records that the cap was reached, so a
24618
+ // short capture is never mistaken for a short reply.
24619
+ responseText: external_exports.string().optional(),
24620
+ truncated: external_exports.boolean().default(false)
24621
+ });
24622
+ var RESPONSE_TEXT_MAX_BYTES = 2 * 1024 * 1024;
24623
+ var WebCaptureStatus = external_exports.object({
24624
+ patched: external_exports.boolean(),
24625
+ live: external_exports.boolean(),
24626
+ blind: external_exports.boolean(),
24627
+ sendsSeenDom: external_exports.number().int().nonnegative(),
24628
+ exchangesSeenNet: external_exports.number().int().nonnegative(),
24629
+ parseFailures: external_exports.number().int().nonnegative(),
24630
+ unparsedBodies: external_exports.number().int().nonnegative(),
24631
+ // The adapter-declared JSON key paths that were absent from a real payload —
24632
+ // the earliest signal that a site's contract moved.
24633
+ shapeMisses: external_exports.array(external_exports.string()).default([])
24634
+ });
24635
+
24325
24636
  // ../../packages/persistence/src/paths.ts
24326
24637
  import {
24327
24638
  chmodSync,
@@ -24682,6 +24993,22 @@ function discardStore(file2, backup) {
24682
24993
  }
24683
24994
  }
24684
24995
 
24996
+ // ../../packages/persistence/src/internal/sql-functions.ts
24997
+ var utf8 = new TextDecoder();
24998
+ function akaLower(value) {
24999
+ if (value === null) return null;
25000
+ if (typeof value === "string") return value.toLowerCase();
25001
+ if (typeof value === "number" || typeof value === "bigint") return String(value).toLowerCase();
25002
+ return utf8.decode(value).toLowerCase();
25003
+ }
25004
+ function registerSqlFunctions(db) {
25005
+ db.function(
25006
+ "aka_lower",
25007
+ { deterministic: true, directOnly: true, useBigIntArguments: true },
25008
+ akaLower
25009
+ );
25010
+ }
25011
+
24685
25012
  // ../../packages/persistence/src/internal/sql-text.ts
24686
25013
  function escapeLikePattern(s) {
24687
25014
  return s.replace(/\\/g, "\\\\").replace(/%/g, "\\%").replace(/_/g, "\\_");
@@ -24766,6 +25093,11 @@ function schemaObjectExists(db, kind, name) {
24766
25093
  function indexExists(db, name) {
24767
25094
  return schemaObjectExists(db, "index", name);
24768
25095
  }
25096
+ function indexColumns(db, name) {
25097
+ if (!indexExists(db, name)) return [];
25098
+ const columns = db.prepare(`PRAGMA index_info(${name})`).all();
25099
+ return columns.map((c) => c.name).filter((c) => c !== null);
25100
+ }
24769
25101
  function columnNames(db, table, opts) {
24770
25102
  const pragma = opts?.includeGenerated ? "table_xinfo" : "table_info";
24771
25103
  const columns = db.prepare(`PRAGMA ${pragma}(${table})`).all();
@@ -24827,177 +25159,819 @@ function mapRowsTolerant(rows, map2) {
24827
25159
  return out;
24828
25160
  }
24829
25161
 
24830
- // ../../packages/persistence/src/migrations.ts
24831
- function describeObject(object2) {
24832
- return object2.kind === "column" ? `column ${object2.table}.${object2.name}` : `table ${object2.name}`;
24833
- }
24834
- function splitStatements(sql) {
24835
- return sql.split(/-->\s*statement-breakpoint/).map((s) => s.trim()).filter((s) => s.length > 0);
24836
- }
24837
- function createdIndexName(statement) {
24838
- const body = statement.replace(/^(?:\s*--[^\n]*\n?)+/, "").trimStart();
24839
- return /^CREATE (?:UNIQUE )?INDEX (?:IF NOT EXISTS )?`([^`]+)`/.exec(body)?.[1];
25162
+ // ../../packages/persistence/src/internal/outbox-lane.ts
25163
+ var OUTBOX_CAPTURE_EVENT_TYPES = ["prompt", "response", "tool_use"];
25164
+ var OUTBOX_CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25165
+
25166
+ // ../../packages/persistence/src/sync-failure.ts
25167
+ var SYNC_FAILURE_REASONS = SyncFailureReason.options;
25168
+ function syncFailureRejectCondition(column = "sync_failure") {
25169
+ const members2 = SYNC_FAILURE_REASONS.map((r) => `'${r}'`).join(", ");
25170
+ return `NEW.${column} IS NOT NULL AND NEW.${column} NOT IN (${members2})`;
24840
25171
  }
24841
- var LEGACY_DROP_MIGRATION_TAG = "0014_drop_legacy_events_findings";
24842
- function applyMigrations(db, file2) {
24843
- const legacyCount = db.prepare("PRAGMA user_version").get().user_version;
24844
- db.exec(
24845
- "CREATE TABLE IF NOT EXISTS migration_ledger (tag TEXT PRIMARY KEY, applied_at INTEGER NOT NULL)"
24846
- );
24847
- const applied = new Set(
24848
- db.prepare("SELECT tag FROM migration_ledger").all().map((r) => r.tag)
24849
- );
24850
- const preLedgerStore = applied.size === 0 && legacyCount > 0;
24851
- const record2 = db.prepare(
24852
- "INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)"
24853
- );
24854
- for (const [index, migration] of SQLITE_MIGRATIONS.entries()) {
24855
- if (applied.has(migration.tag)) continue;
24856
- if (migration.tag === LEGACY_DROP_MIGRATION_TAG) continue;
24857
- const evidence = evidenceObjects(migration.sql);
24858
- const present = evidence.filter((o) => evidenceExists(db, o));
24859
- if (present.length > 0 && present.length < evidence.length) {
24860
- const missing = evidence.filter((o) => !present.includes(o));
24861
- 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.`;
24862
- akaWarn(message);
24863
- throw new Error(`[aka] ${message}`);
24864
- }
24865
- const alreadyApplied = evidence.length > 0 ? present.length === evidence.length : preLedgerStore && index < legacyCount;
24866
- const wantsFkOff = /PRAGMA foreign_keys\s*=\s*OFF/i.test(migration.sql);
24867
- const statements = splitStatements(migration.sql);
24868
- if (wantsFkOff) db.exec("PRAGMA foreign_keys = OFF");
24869
- try {
24870
- withTransaction(
24871
- db,
24872
- () => {
24873
- for (const statement of statements) {
24874
- const indexName = createdIndexName(statement);
24875
- if (indexName === void 0) {
24876
- if (alreadyApplied) continue;
24877
- } else if (indexExists(db, indexName)) {
24878
- continue;
24879
- }
24880
- db.exec(statement);
24881
- }
24882
- if (wantsFkOff && !alreadyApplied) {
24883
- const violations = db.prepare("PRAGMA foreign_key_check").all();
24884
- if (violations.length > 0) {
24885
- throw new Error(
24886
- `[aka] sqlite migration ${migration.tag} left ${String(violations.length)} foreign-key violation(s); rolling back.`
24887
- );
24888
- }
24889
- }
24890
- record2.run(migration.tag, Date.now());
24891
- },
24892
- "IMMEDIATE"
24893
- );
24894
- } finally {
24895
- if (wantsFkOff) db.exec("PRAGMA foreign_keys = ON");
24896
- }
25172
+
25173
+ // ../../packages/persistence/src/repositories/history-sync.ts
25174
+ var STRUCTURAL_EVENT_TYPES = ["session", "llm_call", "tool_call"];
25175
+ var TYPE_LIST = STRUCTURAL_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25176
+ var CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_TYPE_LIST;
25177
+ var COUNTED_EVENT_TYPES = [
25178
+ ...STRUCTURAL_EVENT_TYPES,
25179
+ ...OUTBOX_CAPTURE_EVENT_TYPES
25180
+ ];
25181
+ var COUNTED_TYPE_LIST = COUNTED_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25182
+ var PARTITION_BUCKETS = `
25183
+ SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NULL THEN 1 ELSE 0 END) AS queued,
25184
+ SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NOT NULL THEN 1 ELSE 0 END) AS inProgress,
25185
+ SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS synced,
25186
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25187
+ AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
25188
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25189
+ AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached,
25190
+ -- Spelled as what it INCLUDES rather than what it excludes, so a reason
25191
+ -- added later lands in no bucket and fails the sum assertion, instead
25192
+ -- of silently joining this one.
25193
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25194
+ AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
25195
+ THEN 1 ELSE 0 END) AS failed,
25196
+ COUNT(*) AS total`;
25197
+ var COUNTED_SCOPE = `
25198
+ WHERE event_type IN (${COUNTED_TYPE_LIST})
25199
+ AND (
25200
+ event_type IN (${TYPE_LIST})
25201
+ OR synced_at IS NOT NULL
25202
+ OR outbox_owed = 1
25203
+ )`;
25204
+ var SKIPPED = -1;
25205
+ var ROW_COLUMNS = `id,
25206
+ parent_id AS parentId,
25207
+ root_session_id AS rootSessionId,
25208
+ event_type AS eventType,
25209
+ host_id AS hostId,
25210
+ harness_id AS harnessId,
25211
+ source_project_id AS sourceProjectId,
25212
+ started_at AS startedAt,
25213
+ ended_at AS endedAt,
25214
+ severity,
25215
+ priority,
25216
+ content,
25217
+ content_hash AS contentHash,
25218
+ attributes`;
25219
+ var SqliteHistorySyncRepository = class {
25220
+ constructor(db) {
25221
+ this.db = db;
25222
+ this.ensureRowStmt = db.prepare(`INSERT OR IGNORE INTO history_sync (id) VALUES (1)`);
25223
+ this.sessionsStmt = db.prepare(
25224
+ `SELECT COALESCE(root_session_id, id) AS sessionId, MIN(started_at) AS earliest
25225
+ FROM audit_events
25226
+ WHERE synced_at IS NULL
25227
+ AND event_type IN (${TYPE_LIST})
25228
+ AND started_at < :before
25229
+ GROUP BY sessionId
25230
+ ORDER BY earliest
25231
+ LIMIT :limit`
25232
+ );
25233
+ this.rowsStmt = db.prepare(
25234
+ `SELECT ${ROW_COLUMNS}
25235
+ FROM audit_events
25236
+ WHERE synced_at IS NULL
25237
+ AND event_type IN (${TYPE_LIST})
25238
+ AND started_at < :before
25239
+ AND COALESCE(root_session_id, id) = :sessionId
25240
+ ORDER BY (event_type = 'session') DESC, started_at
25241
+ LIMIT :limit`
25242
+ );
25243
+ this.captureRowsStmt = db.prepare(
25244
+ `SELECT ${ROW_COLUMNS}
25245
+ FROM audit_events
25246
+ WHERE synced_at IS NULL
25247
+ AND sync_claimed_at IS NULL
25248
+ AND outbox_owed = 1
25249
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25250
+ AND started_at < :before
25251
+ ORDER BY started_at
25252
+ LIMIT :limit`
25253
+ );
25254
+ this.markOwedStmt = db.prepare(
25255
+ `UPDATE audit_events SET outbox_owed = 1 WHERE id = :id AND synced_at IS NULL`
25256
+ );
25257
+ this.markCaptureBacklogOwedStmt = db.prepare(
25258
+ `UPDATE audit_events SET outbox_owed = 1
25259
+ WHERE synced_at IS NULL
25260
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25261
+ AND started_at < :before`
25262
+ );
25263
+ this.stampStmt = db.prepare(
25264
+ `UPDATE audit_events
25265
+ SET synced_at = :at,
25266
+ sync_claimed_at = NULL,
25267
+ sync_failed_at = :failedAt,
25268
+ sync_failure = :failure
25269
+ WHERE id = :id`
25270
+ );
25271
+ this.claimRowStmt = db.prepare(
25272
+ `UPDATE audit_events SET sync_claimed_at = :at WHERE id = :id AND synced_at IS NULL`
25273
+ );
25274
+ this.releaseRowStmt = db.prepare(
25275
+ `UPDATE audit_events SET sync_claimed_at = NULL WHERE id = :id`
25276
+ );
25277
+ this.releaseStaleClaimsStmt = db.prepare(
25278
+ `UPDATE audit_events SET sync_claimed_at = NULL
25279
+ WHERE sync_claimed_at IS NOT NULL AND sync_claimed_at < :staleBefore`
25280
+ );
25281
+ this.partitionStmt = db.prepare(`SELECT${PARTITION_BUCKETS}
25282
+ FROM audit_events${COUNTED_SCOPE}`);
25283
+ this.partitionByKindStmt = db.prepare(
25284
+ `SELECT event_type AS kind,${PARTITION_BUCKETS}
25285
+ FROM audit_events INDEXED BY idx_audit_events_sync${COUNTED_SCOPE}
25286
+ GROUP BY event_type`
25287
+ );
25288
+ this.countsStmt = db.prepare(
25289
+ `SELECT
25290
+ SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
25291
+ SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
25292
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25293
+ AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
25294
+ THEN 1 ELSE 0 END) AS skipped,
25295
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25296
+ AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
25297
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25298
+ AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached
25299
+ FROM audit_events
25300
+ WHERE event_type IN (${TYPE_LIST})`
25301
+ );
25302
+ this.captureSkipCountStmt = db.prepare(
25303
+ // EVERY sentinel capture, whatever the reason — deliberately NOT split the
25304
+ // way the structural totals are. The split exists because a refusal is
25305
+ // terminal only against the deployment that gave it, and the structural
25306
+ // re-arm frees it on a change of deployment. The capture lane has no such
25307
+ // escape: re-arming a capture would offer one deployment's undelivered
25308
+ // prompts, with their text, to a deployment that never saw them, which is
25309
+ // exactly what disownCapturesStmt exists to prevent. So on this lane both
25310
+ // reasons mean the same thing — this row will not be sent — and splitting
25311
+ // them would put refused captures in a bucket nothing reads and nothing
25312
+ // frees.
25313
+ `SELECT COUNT(*) AS skipped
25314
+ FROM audit_events
25315
+ WHERE synced_at = ${String(SKIPPED)}
25316
+ AND event_type IN (${CAPTURE_TYPE_LIST})`
25317
+ );
25318
+ this.fingerprintStmt = db.prepare(
25319
+ `SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
25320
+ FROM history_sync WHERE id = 1`
25321
+ );
25322
+ this.setFingerprintStmt = db.prepare(
25323
+ `UPDATE history_sync
25324
+ SET endpoint_fingerprint = :fingerprint, backlog_before = :backlogBefore
25325
+ WHERE id = 1`
25326
+ );
25327
+ this.disownCapturesStmt = db.prepare(
25328
+ `UPDATE audit_events SET outbox_owed = NULL
25329
+ WHERE outbox_owed IS NOT NULL
25330
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25331
+ AND started_at < :attachedAt`
25332
+ );
25333
+ this.rearmStmt = db.prepare(
25334
+ `UPDATE audit_events
25335
+ SET synced_at = NULL, sync_failed_at = NULL, sync_failure = NULL
25336
+ WHERE (synced_at > 0
25337
+ OR sync_failure IN ('deployment_refused', 'detached_undelivered'))
25338
+ AND event_type IN (${TYPE_LIST})`
25339
+ );
25340
+ this.claimStmt = db.prepare(
25341
+ `UPDATE history_sync
25342
+ SET owner_pid = :pid, owner_host = :host, acquired_at = :now, heartbeat_at = :now
25343
+ WHERE id = 1
25344
+ AND (owner_pid IS NULL
25345
+ OR heartbeat_at IS NULL
25346
+ OR heartbeat_at < :staleBefore
25347
+ OR heartbeat_at > :now)`
25348
+ );
25349
+ this.heartbeatStmt = db.prepare(
25350
+ `UPDATE history_sync SET heartbeat_at = :now WHERE id = 1 AND owner_pid = :pid`
25351
+ );
25352
+ this.releaseStmt = db.prepare(
25353
+ `UPDATE history_sync
25354
+ SET owner_pid = NULL, owner_host = NULL, acquired_at = NULL, heartbeat_at = NULL
25355
+ WHERE id = 1 AND owner_pid = :pid`
25356
+ );
25357
+ this.closeWindowStmt = db.prepare(
25358
+ `UPDATE audit_events
25359
+ SET synced_at = ${String(SKIPPED)},
25360
+ sync_failed_at = :at,
25361
+ sync_failure = 'detached_undelivered'
25362
+ WHERE synced_at IS NULL
25363
+ AND event_type IN (${TYPE_LIST})
25364
+ AND started_at >= :attachedAt`
25365
+ );
25366
+ this.releaseBoundaryStmt = db.prepare(
25367
+ `UPDATE history_sync SET backlog_before = NULL WHERE id = 1`
25368
+ );
25369
+ this.freezeBoundaryStmt = db.prepare(
25370
+ `UPDATE history_sync SET backlog_before = :backlogBefore WHERE id = 1`
25371
+ );
25372
+ this.leaseStmt = db.prepare(
25373
+ `SELECT owner_pid AS ownerPid, owner_host AS ownerHost,
25374
+ acquired_at AS acquiredAt, heartbeat_at AS heartbeatAt
25375
+ FROM history_sync WHERE id = 1`
25376
+ );
25377
+ this.inspectionsStmt = db.prepare(
25378
+ `SELECT d.rule_id AS ruleId,
25379
+ d.name AS ruleName,
25380
+ d.version AS ruleVersion,
25381
+ d.category AS category,
25382
+ d.severity AS severity,
25383
+ f.span_start AS spanStart,
25384
+ f.span_end AS spanEnd,
25385
+ f.masked_match AS maskedMatch,
25386
+ f.action_taken AS actionTaken,
25387
+ f.confidence AS confidence
25388
+ FROM inspection_findings f
25389
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
25390
+ WHERE f.audit_event_id = :auditEventId
25391
+ ORDER BY f.span_start, f.id`
25392
+ );
24897
25393
  }
24898
- if (legacyCount < SQLITE_MIGRATIONS.length) {
24899
- db.exec(`PRAGMA user_version = ${String(SQLITE_MIGRATIONS.length)}`);
25394
+ db;
25395
+ ensureRowStmt;
25396
+ sessionsStmt;
25397
+ rowsStmt;
25398
+ stampStmt;
25399
+ countsStmt;
25400
+ fingerprintStmt;
25401
+ setFingerprintStmt;
25402
+ rearmStmt;
25403
+ claimStmt;
25404
+ heartbeatStmt;
25405
+ releaseStmt;
25406
+ leaseStmt;
25407
+ inspectionsStmt;
25408
+ closeWindowStmt;
25409
+ releaseBoundaryStmt;
25410
+ freezeBoundaryStmt;
25411
+ captureRowsStmt;
25412
+ markOwedStmt;
25413
+ markCaptureBacklogOwedStmt;
25414
+ captureSkipCountStmt;
25415
+ disownCapturesStmt;
25416
+ partitionStmt;
25417
+ partitionByKindStmt;
25418
+ claimRowStmt;
25419
+ releaseRowStmt;
25420
+ releaseStaleClaimsStmt;
25421
+ /**
25422
+ * The masked detections recorded against one tool call.
25423
+ *
25424
+ * These travel with the event because a tool call's target is not
25425
+ * re-inspectable from the event alone — unlike a capture, where the text
25426
+ * itself is re-scannable. What crosses is the masked match and the rule that
25427
+ * produced it, never the value.
25428
+ */
25429
+ inspectionsFor(auditEventId) {
25430
+ return allRows(this.inspectionsStmt, { auditEventId });
24900
25431
  }
24901
- ensureSyncedAtColumn(db, "audit_events");
24902
- ensureScanLedgerTable(db);
24903
- ensureHistorySyncTable(db);
24904
- ensureBlockedDetectionsTable(db);
24905
- ensureRuleProbeCacheTable(db);
24906
- ensureWriteGateTrigger(db);
24907
- ensureTokenUsageColumns(db);
24908
- reconcileSourceProjectIds(db);
24909
- if (!applied.has(LEGACY_DROP_MIGRATION_TAG)) {
24910
- const drained = runLegacyHistoryBackfill(db);
24911
- if (drained) applyLegacyDropMigration(db, file2);
25432
+ /**
25433
+ * Sessions with structural rows still to send, oldest first.
25434
+ *
25435
+ * BOUNDED BY THE BACKLOG BOUNDARY, which is the whole correctness of this
25436
+ * read. Anything recorded after the machine attached is the live forward
25437
+ * path's to deliver; this drain exists for what was recorded before it, and a
25438
+ * row both paths send is at best a duplicate request and at worst — for a
25439
+ * session root — an overwrite of the inventory ids the live path resolved.
25440
+ */
25441
+ pendingSessions(limit, before) {
25442
+ return allRows(this.sessionsStmt, { limit, before }).map(
25443
+ (r) => r.sessionId
25444
+ );
24912
25445
  }
24913
- }
24914
- function readLegacyTables(db) {
24915
- let holdsRows = false;
24916
- const marks = [];
24917
- for (const table of ["events", "findings"]) {
24918
- try {
24919
- const row = db.prepare(`SELECT count(*) AS n, ifnull(max(rowid), -1) AS hi FROM ${table}`).get();
24920
- if (row === void 0) {
24921
- holdsRows = true;
24922
- marks.push(`${table}:unreadable`);
24923
- continue;
24924
- }
24925
- if (row.n > 0) holdsRows = true;
24926
- marks.push(`${table}:${String(row.n)}:${String(row.hi)}`);
24927
- } catch {
24928
- holdsRows = true;
24929
- marks.push(`${table}:unreadable`);
24930
- }
25446
+ /** One session's undelivered structural rows within the backlog, root first. */
25447
+ pendingRows(sessionId, limit, before) {
25448
+ return allRows(this.rowsStmt, { sessionId, limit, before });
24931
25449
  }
24932
- return { holdsRows, mark: marks.join("|") };
24933
- }
24934
- function applyLegacyDropMigration(db, file2) {
24935
- const migration = SQLITE_MIGRATIONS.find((m) => m.tag === LEGACY_DROP_MIGRATION_TAG);
24936
- if (!migration) return;
24937
- const before = file2 === void 0 ? void 0 : readLegacyTables(db);
24938
- if (file2 !== void 0 && before?.holdsRows === true) {
24939
- try {
24940
- backupBeforeLegacyDrop(db, file2);
24941
- } catch (error61) {
24942
- akaWarn(`legacy events/findings backup failed; deferring the drop: ${String(error61)}`);
24943
- return;
24944
- }
25450
+ /**
25451
+ * Captures this machine still owes the deployment, oldest first.
25452
+ *
25453
+ * Selected by the `outbox_owed` marker the attached forward path writes, not
25454
+ * by a time window — see captureRowsStmt for why a window could not express
25455
+ * this. `before` is the grace window that leaves a just-recorded capture to
25456
+ * the live path.
25457
+ */
25458
+ pendingCaptureRows(limit, before) {
25459
+ return allRows(this.captureRowsStmt, { limit, before });
24945
25460
  }
24946
- try {
25461
+ /**
25462
+ * Record that a capture is OWED to the deployment.
25463
+ *
25464
+ * Written by the attached forward path when a live send did not confirm
25465
+ * delivery, and read by the drain as the whole of its eligibility test. It is
25466
+ * a fact rather than an inference: the machine was attached, the send did not
25467
+ * land, so the row is owed — which no time window can state, because the same
25468
+ * window that holds the rows a past attachment left owed also holds every
25469
+ * capture recorded while the machine was DETACHED, and those were never
25470
+ * offered to anyone.
25471
+ *
25472
+ * Idempotent, and never un-set: `markSynced` settling the row is what takes it
25473
+ * out of the drain's read.
25474
+ */
25475
+ markCaptureOwed(id) {
25476
+ this.markOwedStmt.run({ id });
25477
+ }
25478
+ /**
25479
+ * Mark every capture already on disk as owed, as of `before`.
25480
+ *
25481
+ * The consent-time backfill, called once from `aka attach` when a human
25482
+ * grants existing-history consent — never from an ongoing drain pass, and
25483
+ * never inferred from a boundary that could later move. `before` is the
25484
+ * caller's own "now" at the moment consent was granted, so what this marks
25485
+ * is exactly the backlog the consent prompt already counted, not whatever a
25486
+ * later re-attach or key rotation might widen it to.
25487
+ *
25488
+ * Returns how many rows matched, for the caller to log or test against. Not a
25489
+ * count of NEWLY marked rows — a row still unsynced from an earlier call
25490
+ * matches again and is counted again, the same as `UPDATE`'s own `changes`.
25491
+ */
25492
+ markCaptureBacklogOwed(before) {
25493
+ return Number(this.markCaptureBacklogOwedStmt.run({ before }).changes);
25494
+ }
25495
+ /**
25496
+ * Record delivery. Called only AFTER the far side has accepted the rows.
25497
+ *
25498
+ * CLEARS any failure reason in the same statement. A row that failed against
25499
+ * one deployment and then landed is delivered, and leaving the reason behind
25500
+ * would leave the store holding two contradictory answers about one row —
25501
+ * with the surface free to render either.
25502
+ */
25503
+ markSynced(ids, atMs) {
25504
+ this.stampAll(ids, atMs, null);
25505
+ }
25506
+ /**
25507
+ * Record that THIS MACHINE cannot express the row on the wire.
25508
+ *
25509
+ * Reserved for a local defect — a row that cannot be rebuilt into a valid
25510
+ * payload, or a body the client itself refused to send. It fails identically
25511
+ * against every deployment, so it is terminal everywhere and the re-arm leaves
25512
+ * it alone. A row that merely failed to REACH the deployment stays NULL, so it
25513
+ * is retried; marking those would turn one outage into permanent data loss.
25514
+ */
25515
+ markSkipped(ids, atMs) {
25516
+ this.stampAll(ids, SKIPPED, "payload_invalid", atMs);
25517
+ }
25518
+ /**
25519
+ * Record that THIS DEPLOYMENT refused the row.
25520
+ *
25521
+ * The same sentinel as `markSkipped`, and deliberately so: both stop the row
25522
+ * being re-offered on this lane, and `synced_at` goes on answering whether a
25523
+ * row is outstanding rather than why. What separates them is the reason, and
25524
+ * what the reason buys is the re-arm — a refusal is one deployment's verdict
25525
+ * on one body, so it is terminal only for as long as this machine points at
25526
+ * that deployment, and `rearmFor` clears it when the deployment changes.
25527
+ *
25528
+ * Leaving such a row NULL instead would be worse than the loss it replaces:
25529
+ * these reads carry no cursor, so an unstamped row the deployment refuses is
25530
+ * the head of every subsequent page, and the lane stalls behind it for ever.
25531
+ */
25532
+ markRefused(ids, atMs) {
25533
+ this.stampAll(ids, SKIPPED, "deployment_refused", atMs);
25534
+ }
25535
+ eachInTransaction(ids, run) {
25536
+ if (ids.length === 0) return;
24947
25537
  withTransaction(
24948
- db,
25538
+ this.db,
24949
25539
  () => {
24950
- const alreadyDropped = db.prepare("SELECT 1 FROM migration_ledger WHERE tag = ?").get(migration.tag);
24951
- if (alreadyDropped) return;
24952
- if (before !== void 0 && readLegacyTables(db).mark !== before.mark) {
24953
- akaWarn(
24954
- "legacy events/findings rows changed after the pre-drop snapshot decision; deferring the drop so the next open can copy them first."
24955
- );
24956
- return;
24957
- }
24958
- for (const statement of splitStatements(migration.sql)) {
24959
- db.exec(statement);
24960
- }
24961
- db.prepare("INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)").run(
24962
- migration.tag,
24963
- Date.now()
24964
- );
25540
+ for (const id of ids) run(id);
24965
25541
  },
24966
25542
  "IMMEDIATE"
24967
25543
  );
24968
- } catch (error61) {
24969
- akaWarn(`legacy events/findings drop failed; deferring: ${String(error61)}`);
24970
25544
  }
24971
- }
24972
- function backupBeforeLegacyDrop(db, file2) {
24973
- reapStalePartials(file2);
24974
- const backup = backupPath(file2, "pre-drop");
24975
- snapshotStore(db, backup);
24976
- return backup;
24977
- }
24978
- var TOKEN_USAGE_COLUMNS = [
24979
- {
24980
- name: "input_tokens",
24981
- ddl: "ALTER TABLE audit_events ADD COLUMN input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.input_tokens')) VIRTUAL"
24982
- },
24983
- {
24984
- name: "output_tokens",
24985
- ddl: "ALTER TABLE audit_events ADD COLUMN output_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.output_tokens')) VIRTUAL"
24986
- },
24987
- {
24988
- name: "cache_creation_input_tokens",
24989
- ddl: "ALTER TABLE audit_events ADD COLUMN cache_creation_input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.cache_creation_input_tokens')) VIRTUAL"
24990
- },
24991
- {
24992
- name: "cache_read_input_tokens",
24993
- ddl: "ALTER TABLE audit_events ADD COLUMN cache_read_input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.cache_read_input_tokens')) VIRTUAL"
24994
- },
24995
- {
24996
- name: "model",
24997
- ddl: "ALTER TABLE audit_events ADD COLUMN model text GENERATED ALWAYS AS (json_extract(attributes, '$.model')) VIRTUAL"
24998
- },
24999
- {
25000
- name: "provider",
25545
+ stampAll(ids, value, failure, failedAtMs) {
25546
+ if (ids.length === 0) return;
25547
+ const failedAt = failure === null ? null : failedAtMs ?? null;
25548
+ withTransaction(
25549
+ this.db,
25550
+ () => {
25551
+ for (const id of ids) this.stampStmt.run({ at: value, failedAt, failure, id });
25552
+ },
25553
+ "IMMEDIATE"
25554
+ );
25555
+ }
25556
+ /**
25557
+ * Claim rows as in-flight.
25558
+ *
25559
+ * Advisory in exactly the sense the lease is: it records that a send is in
25560
+ * progress so a surface can say so, and a lost claim costs a row showing as
25561
+ * queued while it is actually being sent. It is not exclusion — the far side
25562
+ * settles a duplicate on the row id.
25563
+ */
25564
+ claimRows(ids, atMs) {
25565
+ this.eachInTransaction(ids, (id) => this.claimRowStmt.run({ at: atMs, id }));
25566
+ }
25567
+ /** Give back a claim without settling — the send failed, the row is queued again. */
25568
+ releaseRows(ids) {
25569
+ this.eachInTransaction(ids, (id) => this.releaseRowStmt.run({ id }));
25570
+ }
25571
+ /**
25572
+ * Clear claims older than `staleBefore`, and report how many were cleared.
25573
+ *
25574
+ * A process killed between claiming and settling leaves rows claimed with
25575
+ * nothing left to settle them. Without this they read as "sending" for ever.
25576
+ */
25577
+ releaseStaleClaims(staleBefore) {
25578
+ return Number(this.releaseStaleClaimsStmt.run({ staleBefore }).changes);
25579
+ }
25580
+ /**
25581
+ * Every tracked row in exactly one delivery state.
25582
+ *
25583
+ * Takes no boundary on purpose. The boundary answers "what should the drain
25584
+ * pick up now", which is a different question from "what state is this row
25585
+ * in" — and a machine that has never attached has no boundary to pass, so
25586
+ * requiring one would force a caller to invent one and report the whole store
25587
+ * as queued.
25588
+ */
25589
+ /**
25590
+ * The same partition, one row per kind that a lane carries.
25591
+ *
25592
+ * A kind with nothing to report is ABSENT rather than a row of zeros: the
25593
+ * scope decides which rows exist at all, so a kind that has never been
25594
+ * recorded — or whose captures nobody ever owed — produces no group. A caller
25595
+ * rendering a fixed list of kinds must therefore treat a missing one as "no
25596
+ * rows", never as "zero sent"; the two look identical in a bar and mean
25597
+ * different things.
25598
+ */
25599
+ partitionByKind() {
25600
+ return allRows(
25601
+ this.partitionByKindStmt,
25602
+ {}
25603
+ ).map((row) => ({
25604
+ kind: row.kind,
25605
+ queued: row.queued ?? 0,
25606
+ inProgress: row.inProgress ?? 0,
25607
+ synced: row.synced ?? 0,
25608
+ failed: row.failed ?? 0,
25609
+ refused: row.refused ?? 0,
25610
+ detached: row.detached ?? 0,
25611
+ total: row.total ?? 0
25612
+ }));
25613
+ }
25614
+ partition() {
25615
+ const row = getRow(this.partitionStmt, {});
25616
+ return {
25617
+ queued: row?.queued ?? 0,
25618
+ inProgress: row?.inProgress ?? 0,
25619
+ synced: row?.synced ?? 0,
25620
+ failed: row?.failed ?? 0,
25621
+ refused: row?.refused ?? 0,
25622
+ detached: row?.detached ?? 0,
25623
+ total: row?.total ?? 0
25624
+ };
25625
+ }
25626
+ /** `pending` counts only what is inside the backlog; sent and skipped are totals. */
25627
+ counts(before) {
25628
+ const row = getRow(this.countsStmt, { before });
25629
+ const captures = getRow(this.captureSkipCountStmt);
25630
+ return {
25631
+ pending: row?.pending ?? 0,
25632
+ sent: row?.sent ?? 0,
25633
+ skipped: row?.skipped ?? 0,
25634
+ refused: row?.refused ?? 0,
25635
+ detached: row?.detached ?? 0,
25636
+ capturesSkipped: captures?.skipped ?? 0
25637
+ };
25638
+ }
25639
+ /**
25640
+ * The deployment the current stamps were made against, and where its backlog
25641
+ * ends.
25642
+ *
25643
+ * READ-ONLY. An absent row reads as an absent deployment, which is what a
25644
+ * machine that has never drained is — and every writer below seeds the row
25645
+ * before it needs one, so nothing depends on this creating it. Keeping the
25646
+ * write off the gate path matters because the gate runs on every pass while a
25647
+ * write has to take the database's write lock.
25648
+ */
25649
+ deployment() {
25650
+ const row = getRow(
25651
+ this.fingerprintStmt
25652
+ );
25653
+ return {
25654
+ fingerprint: row?.fingerprint ?? void 0,
25655
+ backlogBefore: row?.backlogBefore ?? void 0
25656
+ };
25657
+ }
25658
+ /**
25659
+ * Point the ledger at a different deployment, discarding what it recorded
25660
+ * about the previous one.
25661
+ *
25662
+ * Delivery is a fact about ONE recipient: rows sent to the deployment a
25663
+ * machine has just left are undelivered as far as the new one is concerned.
25664
+ * All four in one transaction, so a crash between them cannot leave stamps
25665
+ * attributed to the wrong deployment, a boundary that belongs to another, or
25666
+ * a disown with no re-mark to follow it.
25667
+ *
25668
+ * The boundary is written HERE and only here, which is what freezes it: a
25669
+ * re-attach to the SAME deployment (a key rotation) leaves the fingerprint
25670
+ * unchanged, so this never runs and the backlog does not widen back over rows
25671
+ * the live path has since delivered.
25672
+ *
25673
+ * `backfillCapturesBefore` is the caller's OWN "now" at the instant a human
25674
+ * granted existing-history consent for the deployment this call is arming —
25675
+ * a DIFFERENT instant from `backlogBefore`: the re-mark boundary is the GRANT
25676
+ * instant, `backlogBefore` is the ATTACH instant, and the two can be far
25677
+ * apart. Passed only when that grant is valid, since this method has no way
25678
+ * to check consent itself and must not mark a row owed for a machine that
25679
+ * never agreed to it. Applied AFTER the disown above, in the SAME
25680
+ * transaction: what the disown clears is every marker below `backlogBefore`,
25681
+ * which includes this deployment's OWN pre-attach rows — `aka attach` calls
25682
+ * `seedCaptureBacklogOwed` at the attach instant, so every row it marks sits
25683
+ * on the cleared side of that bound — and the re-mark in the same
25684
+ * transaction is what puts those rows back. A crash between the two cannot
25685
+ * strand the ledger disowned with nothing re-marked — the transaction either
25686
+ * lands whole or not at all, and a fingerprint mismatch that has not yet
25687
+ * committed re-enters this method on the very next pass. Omit it (the
25688
+ * structural-only tests do) to exercise the disown in isolation.
25689
+ *
25690
+ * The disown is bounded by `backlogBefore`, which is what keeps it from
25691
+ * touching a marker the NEW deployment's OWN live path has already set: B's
25692
+ * live path can mark a capture owed from the moment `aka attach` writes the
25693
+ * descriptor, before the drain's first pass ever reaches this method, and
25694
+ * such a row sits at or after the bound rather than below it. What keeps the
25695
+ * disown from eating THIS SAME CALL's own re-mark is the order, not the
25696
+ * bound — disown runs first, re-mark second, both inside the one
25697
+ * transaction above.
25698
+ */
25699
+ rearmFor(fingerprint, backlogBefore, backfillCapturesBefore) {
25700
+ this.ensureRowStmt.run();
25701
+ withTransaction(
25702
+ this.db,
25703
+ () => {
25704
+ const previous = getRow(this.fingerprintStmt)?.fingerprint;
25705
+ this.rearmStmt.run();
25706
+ if (previous !== null && previous !== void 0 && previous !== fingerprint) {
25707
+ this.disownCapturesStmt.run({ attachedAt: backlogBefore });
25708
+ }
25709
+ if (backfillCapturesBefore !== void 0) {
25710
+ this.markCaptureBacklogOwedStmt.run({ before: backfillCapturesBefore });
25711
+ }
25712
+ this.setFingerprintStmt.run({ fingerprint, backlogBefore });
25713
+ },
25714
+ "IMMEDIATE"
25715
+ );
25716
+ }
25717
+ /**
25718
+ * End the attached period: hand its rows to the live path, and release the
25719
+ * boundary so the next attachment can freeze a new one.
25720
+ *
25721
+ * WITHOUT THIS, a detach and a re-attach to the same deployment leave a window
25722
+ * nothing delivers. The fingerprint is unchanged, so the boundary is never
25723
+ * re-frozen and stays at the FIRST attachment — while nothing forwards at all
25724
+ * during the detached period, because the machine is not attached. Rows
25725
+ * recorded in that window sit after the boundary and before the re-attach, so
25726
+ * neither path takes them, and the pending count reports none outstanding.
25727
+ *
25728
+ * WHAT IT RECORDS, and what it deliberately does not. These rows were the
25729
+ * closing attachment's to deliver and are no longer outstanding — that is what
25730
+ * lets the boundary move. It is NOT a claim that any of them arrived, and the
25731
+ * distinction is not academic: this used to write a delivery TIME, which every
25732
+ * read treats as delivery, so one detach turned a window of undelivered rows
25733
+ * into a window of delivered ones and no surface could tell. It writes the
25734
+ * skip sentinel and a reason of its own instead, so "no longer owed" and
25735
+ * "received" stop being the same fact.
25736
+ *
25737
+ * A change of deployment still frees them (see the re-arm), because the next
25738
+ * deployment has seen none of this machine's history — so the rows reach it
25739
+ * exactly as they did when this wrote a delivery time.
25740
+ *
25741
+ * ONE TRANSACTION, so a crash cannot release the boundary while leaving the
25742
+ * window unstamped — that half-state would re-send the whole attached period
25743
+ * on the next attach, which is the failure the boundary exists to prevent.
25744
+ */
25745
+ closeAttachedWindow(attachedAtMs, atMs) {
25746
+ this.ensureRowStmt.run();
25747
+ withTransaction(
25748
+ this.db,
25749
+ () => {
25750
+ const row = getRow(this.fingerprintStmt);
25751
+ const from = row?.backlogBefore ?? attachedAtMs;
25752
+ this.closeWindowStmt.run({ at: atMs, attachedAt: from });
25753
+ this.releaseBoundaryStmt.run();
25754
+ },
25755
+ "IMMEDIATE"
25756
+ );
25757
+ }
25758
+ /**
25759
+ * Freeze a boundary for the deployment already on file, KEEPING the stamps.
25760
+ *
25761
+ * The re-attach half of the above. Distinct from `rearmFor`, which is for a
25762
+ * different deployment and therefore discards what was delivered to the old
25763
+ * one: here the recipient is the same, so everything already sent to it stays
25764
+ * sent.
25765
+ */
25766
+ freezeBoundary(backlogBefore) {
25767
+ this.ensureRowStmt.run();
25768
+ this.freezeBoundaryStmt.run({ backlogBefore });
25769
+ }
25770
+ /** Take the claim, or report that someone live already holds it. */
25771
+ claim(pid, host, nowMs, staleAfterMs) {
25772
+ this.ensureRowStmt.run();
25773
+ let taken = false;
25774
+ withTransaction(
25775
+ this.db,
25776
+ () => {
25777
+ const result = this.claimStmt.run({
25778
+ pid,
25779
+ host,
25780
+ now: nowMs,
25781
+ staleBefore: nowMs - staleAfterMs
25782
+ });
25783
+ taken = result.changes === 1;
25784
+ },
25785
+ "IMMEDIATE"
25786
+ );
25787
+ return taken;
25788
+ }
25789
+ /** Say the holder is still alive. A no-op once the claim has moved on. */
25790
+ heartbeat(pid, nowMs) {
25791
+ this.heartbeatStmt.run({ now: nowMs, pid });
25792
+ }
25793
+ /** Give the claim up. Scoped to this holder, so a taken-over claim is left be. */
25794
+ release(pid) {
25795
+ this.releaseStmt.run({ pid });
25796
+ }
25797
+ /** Who holds the claim, if anyone. Read-only, for the same reason as above. */
25798
+ lease() {
25799
+ return getRow(this.leaseStmt);
25800
+ }
25801
+ };
25802
+
25803
+ // ../../packages/persistence/src/migrations.ts
25804
+ function describeObject(object2) {
25805
+ return object2.kind === "column" ? `column ${object2.table}.${object2.name}` : `table ${object2.name}`;
25806
+ }
25807
+ function splitStatements(sql) {
25808
+ return sql.split(/-->\s*statement-breakpoint/).map((s) => s.trim()).filter((s) => s.length > 0);
25809
+ }
25810
+ function createdIndexName(statement) {
25811
+ const body = statement.replace(/^(?:\s*--[^\n]*\n?)+/, "").trimStart();
25812
+ return /^CREATE (?:UNIQUE )?INDEX (?:IF NOT EXISTS )?`([^`]+)`/.exec(body)?.[1];
25813
+ }
25814
+ var LEGACY_DROP_MIGRATION_TAG = "0014_drop_legacy_events_findings";
25815
+ function applyMigrations(db, file2, options = {}) {
25816
+ const legacyCount = db.prepare("PRAGMA user_version").get().user_version;
25817
+ db.exec(
25818
+ "CREATE TABLE IF NOT EXISTS migration_ledger (tag TEXT PRIMARY KEY, applied_at INTEGER NOT NULL)"
25819
+ );
25820
+ const applied = new Set(
25821
+ db.prepare("SELECT tag FROM migration_ledger").all().map((r) => r.tag)
25822
+ );
25823
+ const preLedgerStore = applied.size === 0 && legacyCount > 0;
25824
+ const record2 = db.prepare(
25825
+ "INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)"
25826
+ );
25827
+ for (const [index, migration] of SQLITE_MIGRATIONS.entries()) {
25828
+ if (applied.has(migration.tag)) continue;
25829
+ if (options.skipTags?.has(migration.tag) === true) continue;
25830
+ if (migration.tag === LEGACY_DROP_MIGRATION_TAG) continue;
25831
+ const evidence = evidenceObjects(migration.sql);
25832
+ const present = evidence.filter((o) => evidenceExists(db, o));
25833
+ if (present.length > 0 && present.length < evidence.length) {
25834
+ const missing = evidence.filter((o) => !present.includes(o));
25835
+ 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.`;
25836
+ akaWarn(message);
25837
+ throw new Error(`[aka] ${message}`);
25838
+ }
25839
+ const alreadyApplied = evidence.length > 0 ? present.length === evidence.length : preLedgerStore && index < legacyCount;
25840
+ const wantsFkOff = /PRAGMA foreign_keys\s*=\s*OFF/i.test(migration.sql);
25841
+ const statements = splitStatements(migration.sql);
25842
+ if (wantsFkOff) db.exec("PRAGMA foreign_keys = OFF");
25843
+ try {
25844
+ withTransaction(
25845
+ db,
25846
+ () => {
25847
+ for (const statement of statements) {
25848
+ const indexName = createdIndexName(statement);
25849
+ if (indexName === void 0) {
25850
+ if (alreadyApplied) continue;
25851
+ } else if (indexExists(db, indexName)) {
25852
+ continue;
25853
+ }
25854
+ db.exec(statement);
25855
+ }
25856
+ if (wantsFkOff && !alreadyApplied) {
25857
+ const violations = db.prepare("PRAGMA foreign_key_check").all();
25858
+ if (violations.length > 0) {
25859
+ throw new Error(
25860
+ `[aka] sqlite migration ${migration.tag} left ${String(violations.length)} foreign-key violation(s); rolling back.`
25861
+ );
25862
+ }
25863
+ }
25864
+ record2.run(migration.tag, Date.now());
25865
+ },
25866
+ "IMMEDIATE"
25867
+ );
25868
+ } finally {
25869
+ if (wantsFkOff) db.exec("PRAGMA foreign_keys = ON");
25870
+ }
25871
+ }
25872
+ if (legacyCount < SQLITE_MIGRATIONS.length) {
25873
+ db.exec(`PRAGMA user_version = ${String(SQLITE_MIGRATIONS.length)}`);
25874
+ }
25875
+ ensureSyncedAtColumn(db, "audit_events");
25876
+ ensureScanLedgerTable(db);
25877
+ ensureHistorySyncTable(db);
25878
+ ensureBlockedDetectionsTable(db);
25879
+ ensureRuleProbeCacheTable(db);
25880
+ ensureWriteGateTrigger(db);
25881
+ ensureTokenUsageColumns(db);
25882
+ reconcileSourceProjectIds(db);
25883
+ if (!applied.has(LEGACY_DROP_MIGRATION_TAG)) {
25884
+ const drained = runLegacyHistoryBackfill(db);
25885
+ if (drained) applyLegacyDropMigration(db, file2);
25886
+ }
25887
+ }
25888
+ function readLegacyTables(db) {
25889
+ let holdsRows = false;
25890
+ const marks = [];
25891
+ for (const table of ["events", "findings"]) {
25892
+ try {
25893
+ const row = db.prepare(`SELECT count(*) AS n, ifnull(max(rowid), -1) AS hi FROM ${table}`).get();
25894
+ if (row === void 0) {
25895
+ holdsRows = true;
25896
+ marks.push(`${table}:unreadable`);
25897
+ continue;
25898
+ }
25899
+ if (row.n > 0) holdsRows = true;
25900
+ marks.push(`${table}:${String(row.n)}:${String(row.hi)}`);
25901
+ } catch {
25902
+ holdsRows = true;
25903
+ marks.push(`${table}:unreadable`);
25904
+ }
25905
+ }
25906
+ return { holdsRows, mark: marks.join("|") };
25907
+ }
25908
+ function applyLegacyDropMigration(db, file2) {
25909
+ const migration = SQLITE_MIGRATIONS.find((m) => m.tag === LEGACY_DROP_MIGRATION_TAG);
25910
+ if (!migration) return;
25911
+ const before = file2 === void 0 ? void 0 : readLegacyTables(db);
25912
+ if (file2 !== void 0 && before?.holdsRows === true) {
25913
+ try {
25914
+ backupBeforeLegacyDrop(db, file2);
25915
+ } catch (error61) {
25916
+ akaWarn(`legacy events/findings backup failed; deferring the drop: ${String(error61)}`);
25917
+ return;
25918
+ }
25919
+ }
25920
+ try {
25921
+ withTransaction(
25922
+ db,
25923
+ () => {
25924
+ const alreadyDropped = db.prepare("SELECT 1 FROM migration_ledger WHERE tag = ?").get(migration.tag);
25925
+ if (alreadyDropped) return;
25926
+ if (before !== void 0 && readLegacyTables(db).mark !== before.mark) {
25927
+ akaWarn(
25928
+ "legacy events/findings rows changed after the pre-drop snapshot decision; deferring the drop so the next open can copy them first."
25929
+ );
25930
+ return;
25931
+ }
25932
+ for (const statement of splitStatements(migration.sql)) {
25933
+ db.exec(statement);
25934
+ }
25935
+ db.prepare("INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)").run(
25936
+ migration.tag,
25937
+ Date.now()
25938
+ );
25939
+ },
25940
+ "IMMEDIATE"
25941
+ );
25942
+ } catch (error61) {
25943
+ akaWarn(`legacy events/findings drop failed; deferring: ${String(error61)}`);
25944
+ }
25945
+ }
25946
+ function backupBeforeLegacyDrop(db, file2) {
25947
+ reapStalePartials(file2);
25948
+ const backup = backupPath(file2, "pre-drop");
25949
+ snapshotStore(db, backup);
25950
+ return backup;
25951
+ }
25952
+ var TOKEN_USAGE_COLUMNS = [
25953
+ {
25954
+ name: "input_tokens",
25955
+ ddl: "ALTER TABLE audit_events ADD COLUMN input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.input_tokens')) VIRTUAL"
25956
+ },
25957
+ {
25958
+ name: "output_tokens",
25959
+ ddl: "ALTER TABLE audit_events ADD COLUMN output_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.output_tokens')) VIRTUAL"
25960
+ },
25961
+ {
25962
+ name: "cache_creation_input_tokens",
25963
+ ddl: "ALTER TABLE audit_events ADD COLUMN cache_creation_input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.cache_creation_input_tokens')) VIRTUAL"
25964
+ },
25965
+ {
25966
+ name: "cache_read_input_tokens",
25967
+ ddl: "ALTER TABLE audit_events ADD COLUMN cache_read_input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.cache_read_input_tokens')) VIRTUAL"
25968
+ },
25969
+ {
25970
+ name: "model",
25971
+ ddl: "ALTER TABLE audit_events ADD COLUMN model text GENERATED ALWAYS AS (json_extract(attributes, '$.model')) VIRTUAL"
25972
+ },
25973
+ {
25974
+ name: "provider",
25001
25975
  ddl: "ALTER TABLE audit_events ADD COLUMN provider text GENERATED ALWAYS AS (json_extract(attributes, '$.provider')) VIRTUAL"
25002
25976
  }
25003
25977
  ];
@@ -25259,10 +26233,62 @@ function ensureSyncedAtColumn(db, table) {
25259
26233
  if (!columns.includes("outbox_owed")) {
25260
26234
  db.exec(`ALTER TABLE ${table} ADD COLUMN outbox_owed integer`);
25261
26235
  }
26236
+ if (!columns.includes("sync_failed_at")) {
26237
+ db.exec(`ALTER TABLE ${table} ADD COLUMN sync_failed_at integer`);
26238
+ }
26239
+ if (!columns.includes("sync_failure")) {
26240
+ withTransaction(
26241
+ db,
26242
+ () => {
26243
+ db.exec(`ALTER TABLE ${table} ADD COLUMN sync_failure text`);
26244
+ db.exec(
26245
+ `UPDATE ${table} SET synced_at = NULL
26246
+ WHERE synced_at = -1
26247
+ AND event_type IN (${COUNTED_EVENT_TYPES.map((t) => `'${t}'`).join(", ")})`
26248
+ );
26249
+ },
26250
+ "IMMEDIATE"
26251
+ );
26252
+ }
25262
26253
  db.exec(
25263
- `CREATE INDEX IF NOT EXISTS idx_audit_events_sync
25264
- ON audit_events (event_type, synced_at, sync_claimed_at, started_at)`
26254
+ `CREATE TRIGGER IF NOT EXISTS aka_sync_failure_guard
26255
+ BEFORE UPDATE OF sync_failure ON ${table}
26256
+ WHEN ${syncFailureRejectCondition()}
26257
+ BEGIN SELECT RAISE(ABORT, 'sync_failure is not one of the recorded reasons'); END`
25265
26258
  );
26259
+ const syncIndexColumns = [
26260
+ "event_type",
26261
+ "synced_at",
26262
+ "sync_claimed_at",
26263
+ "started_at",
26264
+ // Appended LAST on purpose. The delivery-state read now projects it, so it
26265
+ // has to be in the index for the read to stay covered — but putting it
26266
+ // ahead of `started_at` would reorder the prefix the structural drain's
26267
+ // reads match on.
26268
+ "sync_failure"
26269
+ // `outbox_owed` is DELIBERATELY ABSENT, and it was measured both ways.
26270
+ //
26271
+ // The delivery-state read tests it — a capture's state depends on whether a
26272
+ // live forward marked it owed — so carrying it here makes that read covering
26273
+ // rather than a row fetch per row: 16 ms against 40 ms on a real 6 GB store.
26274
+ // But a sixth column changes what the planner charges for this index, and
26275
+ // with no ANALYZE statistics it plans from schema shape alone: measured, it
26276
+ // then stops choosing the per-session index for the token rollup and walks
26277
+ // every `llm_call` in the store through the event-type index instead. That
26278
+ // read grows with the store; this one does not.
26279
+ //
26280
+ // 40 ms on the largest store measured, once per render, is a cost worth
26281
+ // paying to leave every other read's plan where it was.
26282
+ ];
26283
+ const currentSyncIndex = indexColumns(db, "idx_audit_events_sync");
26284
+ const syncIndexMatches = currentSyncIndex.length === syncIndexColumns.length && currentSyncIndex.every((column, i) => column === syncIndexColumns[i]);
26285
+ if (!syncIndexMatches) {
26286
+ db.exec("DROP INDEX IF EXISTS idx_audit_events_sync");
26287
+ db.exec(
26288
+ `CREATE INDEX idx_audit_events_sync
26289
+ ON audit_events (${syncIndexColumns.join(", ")})`
26290
+ );
26291
+ }
25266
26292
  db.exec(
25267
26293
  `CREATE INDEX IF NOT EXISTS idx_audit_outbox_owed
25268
26294
  ON audit_events (event_type, synced_at, sync_claimed_at, started_at) WHERE outbox_owed = 1`
@@ -25484,7 +26510,11 @@ function buildAuditEvent(row) {
25484
26510
  link: linkParsed?.success ? linkParsed.data : null,
25485
26511
  targetId: row.target_id,
25486
26512
  internal: intToBool(row.internal),
25487
- flagged: intToBool(row.flagged)
26513
+ flagged: intToBool(row.flagged),
26514
+ // Only meaningful when the title came out empty — a row whose body was
26515
+ // expired but whose title fell back to `tool_name` still has something to
26516
+ // render, and flagging it would make the view apologise for nothing.
26517
+ bodyExpired: row.content_expired_at !== null && (row.title ?? "") === ""
25488
26518
  };
25489
26519
  }
25490
26520
  var TIMELINE_COLUMNS = `
@@ -25492,6 +26522,7 @@ var TIMELINE_COLUMNS = `
25492
26522
  event_type,
25493
26523
  started_at,
25494
26524
  coalesce(content, json_extract(attributes, '$.tool_name')) AS title,
26525
+ content_expired_at,
25495
26526
  coalesce(json_extract(attributes, '$.detail'), json_extract(attributes, '$.target')) AS detail,
25496
26527
  coalesce(json_extract(attributes, '$.tool_name'), json_extract(attributes, '$.tool')) AS tool,
25497
26528
  json_extract(attributes, '$.severity') AS severity,
@@ -26157,6 +27188,88 @@ var SqliteAuditEventsRepository = class {
26157
27188
  }
26158
27189
  };
26159
27190
 
27191
+ // ../../packages/persistence/src/repositories/body-retention.ts
27192
+ var DEFAULT_BATCH_SIZE = 500;
27193
+ var DEFAULT_MAX_ROWS = 5e4;
27194
+ var SYNC_LANE_TYPES_SQL = OUTBOX_CAPTURE_TYPE_LIST;
27195
+ var SqliteBodyRetentionRepository = class {
27196
+ constructor(db) {
27197
+ this.db = db;
27198
+ const select = (laneClause) => `
27199
+ SELECT id, LENGTH(CAST(content AS BLOB)) AS bytes
27200
+ FROM audit_events
27201
+ WHERE content IS NOT NULL
27202
+ AND started_at < :cutoff
27203
+ AND event_type IN (${CAPTURE_EVENT_TYPES_SQL})
27204
+ ${laneClause}
27205
+ ORDER BY started_at
27206
+ LIMIT :limit`;
27207
+ this.candidatesStmt = this.db.prepare(select(""));
27208
+ this.candidatesSyncSafeStmt = this.db.prepare(
27209
+ select(`AND (event_type NOT IN (${SYNC_LANE_TYPES_SQL}) OR synced_at IS NOT NULL)`)
27210
+ );
27211
+ this.heldBySyncStmt = this.db.prepare(`
27212
+ SELECT COUNT(*) AS n
27213
+ FROM audit_events
27214
+ WHERE content IS NOT NULL
27215
+ AND started_at < :cutoff
27216
+ AND event_type IN (${SYNC_LANE_TYPES_SQL})
27217
+ AND synced_at IS NULL`);
27218
+ this.expireStmt = this.db.prepare(
27219
+ `UPDATE audit_events SET content = NULL, content_expired_at = :now WHERE id = :id`
27220
+ );
27221
+ }
27222
+ db;
27223
+ candidatesStmt;
27224
+ candidatesSyncSafeStmt;
27225
+ heldBySyncStmt;
27226
+ expireStmt;
27227
+ /** How many bytes a pass with these options would free, changing nothing. */
27228
+ preview(opts) {
27229
+ const limit = opts.maxRows ?? DEFAULT_MAX_ROWS;
27230
+ const stmt = opts.sweepSyncLane ? this.candidatesStmt : this.candidatesSyncSafeStmt;
27231
+ const rows = stmt.all({ cutoff: opts.cutoff, limit });
27232
+ return {
27233
+ rowsExpired: rows.length,
27234
+ bytesFreed: rows.reduce((sum, r) => sum + r.bytes, 0),
27235
+ rowsHeldBySync: this.countHeldBySync(opts)
27236
+ };
27237
+ }
27238
+ /** Clear eligible bodies, in bounded batches. */
27239
+ expire(opts) {
27240
+ const batchSize = opts.batchSize ?? DEFAULT_BATCH_SIZE;
27241
+ const maxRows = opts.maxRows ?? DEFAULT_MAX_ROWS;
27242
+ const stmt = opts.sweepSyncLane ? this.candidatesStmt : this.candidatesSyncSafeStmt;
27243
+ let rowsExpired = 0;
27244
+ let bytesFreed = 0;
27245
+ let done = true;
27246
+ while (rowsExpired < maxRows) {
27247
+ const remaining = Math.min(batchSize, maxRows - rowsExpired);
27248
+ const batch = stmt.all({ cutoff: opts.cutoff, limit: remaining });
27249
+ if (batch.length === 0) break;
27250
+ withTransaction(
27251
+ this.db,
27252
+ () => {
27253
+ for (const row of batch) this.expireStmt.run({ id: row.id, now: opts.now });
27254
+ },
27255
+ "IMMEDIATE"
27256
+ );
27257
+ rowsExpired += batch.length;
27258
+ bytesFreed += batch.reduce((sum, r) => sum + r.bytes, 0);
27259
+ if (batch.length < remaining) break;
27260
+ if (rowsExpired >= maxRows) {
27261
+ done = stmt.all({ cutoff: opts.cutoff, limit: 1 }).length === 0;
27262
+ }
27263
+ }
27264
+ return { rowsExpired, bytesFreed, rowsHeldBySync: this.countHeldBySync(opts), done };
27265
+ }
27266
+ countHeldBySync(opts) {
27267
+ if (opts.sweepSyncLane) return 0;
27268
+ const row = this.heldBySyncStmt.get({ cutoff: opts.cutoff });
27269
+ return row.n;
27270
+ }
27271
+ };
27272
+
26160
27273
  // ../../packages/persistence/src/repositories/classified-data.ts
26161
27274
  var SqliteClassifiedDataRepository = class {
26162
27275
  constructor(db) {
@@ -26985,7 +28098,15 @@ function toFlatFindingRow(r) {
26985
28098
  ...r.tool_name === null ? {} : { toolName: r.tool_name },
26986
28099
  eventId: r.event_id,
26987
28100
  ...r.session_id === null ? {} : { sessionId: r.session_id },
26988
- status: deriveInstanceStatus(r)
28101
+ status: deriveInstanceStatus(r),
28102
+ delivery: deriveFindingDelivery({
28103
+ kind: r.kind,
28104
+ syncedAt: r.synced_at,
28105
+ syncClaimedAt: r.sync_claimed_at,
28106
+ syncFailedAt: r.sync_failed_at,
28107
+ syncFailure: r.sync_failure,
28108
+ outboxOwed: r.outbox_owed
28109
+ })
26989
28110
  };
26990
28111
  }
26991
28112
  function encodeGroupCursor(group) {
@@ -27049,7 +28170,10 @@ var FINDING_ROW_COLUMNS_SQL = `f.id AS id, d.rule_id AS rule_id, d.category AS c
27049
28170
  e.tool_name AS tool_name,
27050
28171
  f.audit_event_id AS event_id, e.root_session_id AS session_id,
27051
28172
  e.event_type AS kind, f.finding_key AS finding_key,
27052
- ${latestResolutionStatusSql("f")} AS latest_status`;
28173
+ ${latestResolutionStatusSql("f")} AS latest_status,
28174
+ e.synced_at AS synced_at, e.sync_claimed_at AS sync_claimed_at,
28175
+ e.sync_failed_at AS sync_failed_at, e.sync_failure AS sync_failure,
28176
+ e.outbox_owed AS outbox_owed`;
27053
28177
  var DAY_MS3 = 864e5;
27054
28178
  var SqliteFindingsRepository = class {
27055
28179
  constructor(db) {
@@ -27294,6 +28418,7 @@ var SqliteFindingsRepository = class {
27294
28418
  providers: query.provider,
27295
28419
  actions: query.action,
27296
28420
  statuses: query.status,
28421
+ deliveries: query.deployment,
27297
28422
  tools: query.tool,
27298
28423
  repo: query.repo,
27299
28424
  file: query.file,
@@ -27361,6 +28486,7 @@ var SqliteFindingsRepository = class {
27361
28486
  providers: query.provider,
27362
28487
  actions: query.action,
27363
28488
  statuses: query.status,
28489
+ deliveries: query.deployment,
27364
28490
  tools: query.tool,
27365
28491
  q: query.q
27366
28492
  };
@@ -27624,7 +28750,9 @@ var SqliteFindingsRepository = class {
27624
28750
  )
27625
28751
  );
27626
28752
  for (const row of grouped) {
27627
- if (row.action_taken in byAction) byAction[row.action_taken] = row.c;
28753
+ if (Object.hasOwn(byAction, row.action_taken)) {
28754
+ byAction[row.action_taken] = row.c;
28755
+ }
27628
28756
  }
27629
28757
  const bySeverity = { critical: 0, high: 0, medium: 0, low: 0 };
27630
28758
  const sevRows = allRows(
@@ -27641,7 +28769,9 @@ var SqliteFindingsRepository = class {
27641
28769
  )
27642
28770
  );
27643
28771
  for (const row of sevRows) {
27644
- if (row.severity in bySeverity) bySeverity[row.severity] = row.c;
28772
+ if (Object.hasOwn(bySeverity, row.severity)) {
28773
+ bySeverity[row.severity] = row.c;
28774
+ }
27645
28775
  }
27646
28776
  const categories = ENFORCEABLE_CATEGORIES;
27647
28777
  const enabledRows = allRows(
@@ -27690,525 +28820,6 @@ function isoDay(ms) {
27690
28820
  return new Date(ms).toISOString().slice(0, 10);
27691
28821
  }
27692
28822
 
27693
- // ../../packages/persistence/src/repositories/history-sync.ts
27694
- var STRUCTURAL_EVENT_TYPES = ["session", "llm_call", "tool_call"];
27695
- var TYPE_LIST = STRUCTURAL_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
27696
- var OUTBOX_CAPTURE_EVENT_TYPES = ["prompt", "response", "tool_use"];
27697
- var CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
27698
- var SKIPPED = -1;
27699
- var ROW_COLUMNS = `id,
27700
- parent_id AS parentId,
27701
- root_session_id AS rootSessionId,
27702
- event_type AS eventType,
27703
- host_id AS hostId,
27704
- harness_id AS harnessId,
27705
- source_project_id AS sourceProjectId,
27706
- started_at AS startedAt,
27707
- ended_at AS endedAt,
27708
- severity,
27709
- priority,
27710
- content,
27711
- content_hash AS contentHash,
27712
- attributes`;
27713
- var SqliteHistorySyncRepository = class {
27714
- constructor(db) {
27715
- this.db = db;
27716
- this.ensureRowStmt = db.prepare(`INSERT OR IGNORE INTO history_sync (id) VALUES (1)`);
27717
- this.sessionsStmt = db.prepare(
27718
- `SELECT COALESCE(root_session_id, id) AS sessionId, MIN(started_at) AS earliest
27719
- FROM audit_events
27720
- WHERE synced_at IS NULL
27721
- AND event_type IN (${TYPE_LIST})
27722
- AND started_at < :before
27723
- GROUP BY sessionId
27724
- ORDER BY earliest
27725
- LIMIT :limit`
27726
- );
27727
- this.rowsStmt = db.prepare(
27728
- `SELECT ${ROW_COLUMNS}
27729
- FROM audit_events
27730
- WHERE synced_at IS NULL
27731
- AND event_type IN (${TYPE_LIST})
27732
- AND started_at < :before
27733
- AND COALESCE(root_session_id, id) = :sessionId
27734
- ORDER BY (event_type = 'session') DESC, started_at
27735
- LIMIT :limit`
27736
- );
27737
- this.captureRowsStmt = db.prepare(
27738
- `SELECT ${ROW_COLUMNS}
27739
- FROM audit_events
27740
- WHERE synced_at IS NULL
27741
- AND sync_claimed_at IS NULL
27742
- AND outbox_owed = 1
27743
- AND event_type IN (${CAPTURE_TYPE_LIST})
27744
- AND started_at < :before
27745
- ORDER BY started_at
27746
- LIMIT :limit`
27747
- );
27748
- this.markOwedStmt = db.prepare(
27749
- `UPDATE audit_events SET outbox_owed = 1 WHERE id = :id AND synced_at IS NULL`
27750
- );
27751
- this.markCaptureBacklogOwedStmt = db.prepare(
27752
- `UPDATE audit_events SET outbox_owed = 1
27753
- WHERE synced_at IS NULL
27754
- AND event_type IN (${CAPTURE_TYPE_LIST})
27755
- AND started_at < :before`
27756
- );
27757
- this.stampStmt = db.prepare(
27758
- `UPDATE audit_events SET synced_at = :at, sync_claimed_at = NULL WHERE id = :id`
27759
- );
27760
- this.claimRowStmt = db.prepare(
27761
- `UPDATE audit_events SET sync_claimed_at = :at WHERE id = :id AND synced_at IS NULL`
27762
- );
27763
- this.releaseRowStmt = db.prepare(
27764
- `UPDATE audit_events SET sync_claimed_at = NULL WHERE id = :id`
27765
- );
27766
- this.releaseStaleClaimsStmt = db.prepare(
27767
- `UPDATE audit_events SET sync_claimed_at = NULL
27768
- WHERE sync_claimed_at IS NOT NULL AND sync_claimed_at < :staleBefore`
27769
- );
27770
- this.partitionStmt = db.prepare(
27771
- `SELECT
27772
- SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NULL THEN 1 ELSE 0 END) AS queued,
27773
- SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NOT NULL THEN 1 ELSE 0 END) AS inProgress,
27774
- SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS synced,
27775
- SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0 THEN 1 ELSE 0 END) AS failed,
27776
- COUNT(*) AS total
27777
- FROM audit_events
27778
- WHERE event_type IN (${TYPE_LIST})`
27779
- );
27780
- this.countsStmt = db.prepare(
27781
- `SELECT
27782
- SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
27783
- SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
27784
- SUM(CASE WHEN synced_at = ${String(SKIPPED)} THEN 1 ELSE 0 END) AS skipped
27785
- FROM audit_events
27786
- WHERE event_type IN (${TYPE_LIST})`
27787
- );
27788
- this.captureSkipCountStmt = db.prepare(
27789
- `SELECT COUNT(*) AS skipped
27790
- FROM audit_events
27791
- WHERE synced_at = ${String(SKIPPED)}
27792
- AND event_type IN (${CAPTURE_TYPE_LIST})`
27793
- );
27794
- this.fingerprintStmt = db.prepare(
27795
- `SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
27796
- FROM history_sync WHERE id = 1`
27797
- );
27798
- this.setFingerprintStmt = db.prepare(
27799
- `UPDATE history_sync
27800
- SET endpoint_fingerprint = :fingerprint, backlog_before = :backlogBefore
27801
- WHERE id = 1`
27802
- );
27803
- this.disownCapturesStmt = db.prepare(
27804
- `UPDATE audit_events SET outbox_owed = NULL
27805
- WHERE outbox_owed IS NOT NULL
27806
- AND event_type IN (${CAPTURE_TYPE_LIST})
27807
- AND started_at < :attachedAt`
27808
- );
27809
- this.rearmStmt = db.prepare(
27810
- `UPDATE audit_events SET synced_at = NULL
27811
- WHERE synced_at > 0 AND event_type IN (${TYPE_LIST})`
27812
- );
27813
- this.claimStmt = db.prepare(
27814
- `UPDATE history_sync
27815
- SET owner_pid = :pid, owner_host = :host, acquired_at = :now, heartbeat_at = :now
27816
- WHERE id = 1
27817
- AND (owner_pid IS NULL
27818
- OR heartbeat_at IS NULL
27819
- OR heartbeat_at < :staleBefore
27820
- OR heartbeat_at > :now)`
27821
- );
27822
- this.heartbeatStmt = db.prepare(
27823
- `UPDATE history_sync SET heartbeat_at = :now WHERE id = 1 AND owner_pid = :pid`
27824
- );
27825
- this.releaseStmt = db.prepare(
27826
- `UPDATE history_sync
27827
- SET owner_pid = NULL, owner_host = NULL, acquired_at = NULL, heartbeat_at = NULL
27828
- WHERE id = 1 AND owner_pid = :pid`
27829
- );
27830
- this.closeWindowStmt = db.prepare(
27831
- `UPDATE audit_events SET synced_at = :at
27832
- WHERE synced_at IS NULL
27833
- AND event_type IN (${TYPE_LIST})
27834
- AND started_at >= :attachedAt`
27835
- );
27836
- this.releaseBoundaryStmt = db.prepare(
27837
- `UPDATE history_sync SET backlog_before = NULL WHERE id = 1`
27838
- );
27839
- this.freezeBoundaryStmt = db.prepare(
27840
- `UPDATE history_sync SET backlog_before = :backlogBefore WHERE id = 1`
27841
- );
27842
- this.leaseStmt = db.prepare(
27843
- `SELECT owner_pid AS ownerPid, owner_host AS ownerHost,
27844
- acquired_at AS acquiredAt, heartbeat_at AS heartbeatAt
27845
- FROM history_sync WHERE id = 1`
27846
- );
27847
- this.inspectionsStmt = db.prepare(
27848
- `SELECT d.rule_id AS ruleId,
27849
- d.name AS ruleName,
27850
- d.version AS ruleVersion,
27851
- d.category AS category,
27852
- d.severity AS severity,
27853
- f.span_start AS spanStart,
27854
- f.span_end AS spanEnd,
27855
- f.masked_match AS maskedMatch,
27856
- f.action_taken AS actionTaken,
27857
- f.confidence AS confidence
27858
- FROM inspection_findings f
27859
- JOIN inspection_definitions d ON d.id = f.inspection_definition_id
27860
- WHERE f.audit_event_id = :auditEventId
27861
- ORDER BY f.span_start, f.id`
27862
- );
27863
- }
27864
- db;
27865
- ensureRowStmt;
27866
- sessionsStmt;
27867
- rowsStmt;
27868
- stampStmt;
27869
- countsStmt;
27870
- fingerprintStmt;
27871
- setFingerprintStmt;
27872
- rearmStmt;
27873
- claimStmt;
27874
- heartbeatStmt;
27875
- releaseStmt;
27876
- leaseStmt;
27877
- inspectionsStmt;
27878
- closeWindowStmt;
27879
- releaseBoundaryStmt;
27880
- freezeBoundaryStmt;
27881
- captureRowsStmt;
27882
- markOwedStmt;
27883
- markCaptureBacklogOwedStmt;
27884
- captureSkipCountStmt;
27885
- disownCapturesStmt;
27886
- partitionStmt;
27887
- claimRowStmt;
27888
- releaseRowStmt;
27889
- releaseStaleClaimsStmt;
27890
- /**
27891
- * The masked detections recorded against one tool call.
27892
- *
27893
- * These travel with the event because a tool call's target is not
27894
- * re-inspectable from the event alone — unlike a capture, where the text
27895
- * itself is re-scannable. What crosses is the masked match and the rule that
27896
- * produced it, never the value.
27897
- */
27898
- inspectionsFor(auditEventId) {
27899
- return allRows(this.inspectionsStmt, { auditEventId });
27900
- }
27901
- /**
27902
- * Sessions with structural rows still to send, oldest first.
27903
- *
27904
- * BOUNDED BY THE BACKLOG BOUNDARY, which is the whole correctness of this
27905
- * read. Anything recorded after the machine attached is the live forward
27906
- * path's to deliver; this drain exists for what was recorded before it, and a
27907
- * row both paths send is at best a duplicate request and at worst — for a
27908
- * session root — an overwrite of the inventory ids the live path resolved.
27909
- */
27910
- pendingSessions(limit, before) {
27911
- return allRows(this.sessionsStmt, { limit, before }).map(
27912
- (r) => r.sessionId
27913
- );
27914
- }
27915
- /** One session's undelivered structural rows within the backlog, root first. */
27916
- pendingRows(sessionId, limit, before) {
27917
- return allRows(this.rowsStmt, { sessionId, limit, before });
27918
- }
27919
- /**
27920
- * Captures this machine still owes the deployment, oldest first.
27921
- *
27922
- * Selected by the `outbox_owed` marker the attached forward path writes, not
27923
- * by a time window — see captureRowsStmt for why a window could not express
27924
- * this. `before` is the grace window that leaves a just-recorded capture to
27925
- * the live path.
27926
- */
27927
- pendingCaptureRows(limit, before) {
27928
- return allRows(this.captureRowsStmt, { limit, before });
27929
- }
27930
- /**
27931
- * Record that a capture is OWED to the deployment.
27932
- *
27933
- * Written by the attached forward path when a live send did not confirm
27934
- * delivery, and read by the drain as the whole of its eligibility test. It is
27935
- * a fact rather than an inference: the machine was attached, the send did not
27936
- * land, so the row is owed — which no time window can state, because the same
27937
- * window that holds the rows a past attachment left owed also holds every
27938
- * capture recorded while the machine was DETACHED, and those were never
27939
- * offered to anyone.
27940
- *
27941
- * Idempotent, and never un-set: `markSynced` settling the row is what takes it
27942
- * out of the drain's read.
27943
- */
27944
- markCaptureOwed(id) {
27945
- this.markOwedStmt.run({ id });
27946
- }
27947
- /**
27948
- * Mark every capture already on disk as owed, as of `before`.
27949
- *
27950
- * The consent-time backfill, called once from `aka attach` when a human
27951
- * grants existing-history consent — never from an ongoing drain pass, and
27952
- * never inferred from a boundary that could later move. `before` is the
27953
- * caller's own "now" at the moment consent was granted, so what this marks
27954
- * is exactly the backlog the consent prompt already counted, not whatever a
27955
- * later re-attach or key rotation might widen it to.
27956
- *
27957
- * Returns how many rows matched, for the caller to log or test against. Not a
27958
- * count of NEWLY marked rows — a row still unsynced from an earlier call
27959
- * matches again and is counted again, the same as `UPDATE`'s own `changes`.
27960
- */
27961
- markCaptureBacklogOwed(before) {
27962
- return Number(this.markCaptureBacklogOwedStmt.run({ before }).changes);
27963
- }
27964
- /** Record delivery. Called only AFTER the far side has accepted the rows. */
27965
- markSynced(ids, atMs) {
27966
- this.stampAll(ids, atMs);
27967
- }
27968
- /**
27969
- * Record that a row will never be sent.
27970
- *
27971
- * Reserved for a local defect — a row that cannot be rebuilt into a valid
27972
- * payload. A row that merely failed to reach the deployment stays NULL, so it
27973
- * is retried; marking those would turn one outage into permanent data loss.
27974
- */
27975
- markSkipped(ids) {
27976
- this.stampAll(ids, SKIPPED);
27977
- }
27978
- eachInTransaction(ids, run) {
27979
- if (ids.length === 0) return;
27980
- withTransaction(
27981
- this.db,
27982
- () => {
27983
- for (const id of ids) run(id);
27984
- },
27985
- "IMMEDIATE"
27986
- );
27987
- }
27988
- stampAll(ids, value) {
27989
- if (ids.length === 0) return;
27990
- withTransaction(
27991
- this.db,
27992
- () => {
27993
- for (const id of ids) this.stampStmt.run({ at: value, id });
27994
- },
27995
- "IMMEDIATE"
27996
- );
27997
- }
27998
- /**
27999
- * Claim rows as in-flight.
28000
- *
28001
- * Advisory in exactly the sense the lease is: it records that a send is in
28002
- * progress so a surface can say so, and a lost claim costs a row showing as
28003
- * queued while it is actually being sent. It is not exclusion — the far side
28004
- * settles a duplicate on the row id.
28005
- */
28006
- claimRows(ids, atMs) {
28007
- this.eachInTransaction(ids, (id) => this.claimRowStmt.run({ at: atMs, id }));
28008
- }
28009
- /** Give back a claim without settling — the send failed, the row is queued again. */
28010
- releaseRows(ids) {
28011
- this.eachInTransaction(ids, (id) => this.releaseRowStmt.run({ id }));
28012
- }
28013
- /**
28014
- * Clear claims older than `staleBefore`, and report how many were cleared.
28015
- *
28016
- * A process killed between claiming and settling leaves rows claimed with
28017
- * nothing left to settle them. Without this they read as "sending" for ever.
28018
- */
28019
- releaseStaleClaims(staleBefore) {
28020
- return Number(this.releaseStaleClaimsStmt.run({ staleBefore }).changes);
28021
- }
28022
- /**
28023
- * Every tracked row in exactly one delivery state.
28024
- *
28025
- * Takes no boundary on purpose. The boundary answers "what should the drain
28026
- * pick up now", which is a different question from "what state is this row
28027
- * in" — and a machine that has never attached has no boundary to pass, so
28028
- * requiring one would force a caller to invent one and report the whole store
28029
- * as queued.
28030
- */
28031
- partition() {
28032
- const row = getRow(this.partitionStmt, {});
28033
- return {
28034
- queued: row?.queued ?? 0,
28035
- inProgress: row?.inProgress ?? 0,
28036
- synced: row?.synced ?? 0,
28037
- failed: row?.failed ?? 0,
28038
- total: row?.total ?? 0
28039
- };
28040
- }
28041
- /** `pending` counts only what is inside the backlog; sent and skipped are totals. */
28042
- counts(before) {
28043
- const row = getRow(
28044
- this.countsStmt,
28045
- { before }
28046
- );
28047
- const captures = getRow(this.captureSkipCountStmt);
28048
- return {
28049
- pending: row?.pending ?? 0,
28050
- sent: row?.sent ?? 0,
28051
- skipped: row?.skipped ?? 0,
28052
- capturesSkipped: captures?.skipped ?? 0
28053
- };
28054
- }
28055
- /**
28056
- * The deployment the current stamps were made against, and where its backlog
28057
- * ends.
28058
- *
28059
- * READ-ONLY. An absent row reads as an absent deployment, which is what a
28060
- * machine that has never drained is — and every writer below seeds the row
28061
- * before it needs one, so nothing depends on this creating it. Keeping the
28062
- * write off the gate path matters because the gate runs on every pass while a
28063
- * write has to take the database's write lock.
28064
- */
28065
- deployment() {
28066
- const row = getRow(
28067
- this.fingerprintStmt
28068
- );
28069
- return {
28070
- fingerprint: row?.fingerprint ?? void 0,
28071
- backlogBefore: row?.backlogBefore ?? void 0
28072
- };
28073
- }
28074
- /**
28075
- * Point the ledger at a different deployment, discarding what it recorded
28076
- * about the previous one.
28077
- *
28078
- * Delivery is a fact about ONE recipient: rows sent to the deployment a
28079
- * machine has just left are undelivered as far as the new one is concerned.
28080
- * All four in one transaction, so a crash between them cannot leave stamps
28081
- * attributed to the wrong deployment, a boundary that belongs to another, or
28082
- * a disown with no re-mark to follow it.
28083
- *
28084
- * The boundary is written HERE and only here, which is what freezes it: a
28085
- * re-attach to the SAME deployment (a key rotation) leaves the fingerprint
28086
- * unchanged, so this never runs and the backlog does not widen back over rows
28087
- * the live path has since delivered.
28088
- *
28089
- * `backfillCapturesBefore` is the caller's OWN "now" at the instant a human
28090
- * granted existing-history consent for the deployment this call is arming —
28091
- * a DIFFERENT instant from `backlogBefore`: the re-mark boundary is the GRANT
28092
- * instant, `backlogBefore` is the ATTACH instant, and the two can be far
28093
- * apart. Passed only when that grant is valid, since this method has no way
28094
- * to check consent itself and must not mark a row owed for a machine that
28095
- * never agreed to it. Applied AFTER the disown above, in the SAME
28096
- * transaction: what the disown clears is every marker below `backlogBefore`,
28097
- * which includes this deployment's OWN pre-attach rows — `aka attach` calls
28098
- * `seedCaptureBacklogOwed` at the attach instant, so every row it marks sits
28099
- * on the cleared side of that bound — and the re-mark in the same
28100
- * transaction is what puts those rows back. A crash between the two cannot
28101
- * strand the ledger disowned with nothing re-marked — the transaction either
28102
- * lands whole or not at all, and a fingerprint mismatch that has not yet
28103
- * committed re-enters this method on the very next pass. Omit it (the
28104
- * structural-only tests do) to exercise the disown in isolation.
28105
- *
28106
- * The disown is bounded by `backlogBefore`, which is what keeps it from
28107
- * touching a marker the NEW deployment's OWN live path has already set: B's
28108
- * live path can mark a capture owed from the moment `aka attach` writes the
28109
- * descriptor, before the drain's first pass ever reaches this method, and
28110
- * such a row sits at or after the bound rather than below it. What keeps the
28111
- * disown from eating THIS SAME CALL's own re-mark is the order, not the
28112
- * bound — disown runs first, re-mark second, both inside the one
28113
- * transaction above.
28114
- */
28115
- rearmFor(fingerprint, backlogBefore, backfillCapturesBefore) {
28116
- this.ensureRowStmt.run();
28117
- withTransaction(
28118
- this.db,
28119
- () => {
28120
- const previous = getRow(this.fingerprintStmt)?.fingerprint;
28121
- this.rearmStmt.run();
28122
- if (previous !== null && previous !== void 0 && previous !== fingerprint) {
28123
- this.disownCapturesStmt.run({ attachedAt: backlogBefore });
28124
- }
28125
- if (backfillCapturesBefore !== void 0) {
28126
- this.markCaptureBacklogOwedStmt.run({ before: backfillCapturesBefore });
28127
- }
28128
- this.setFingerprintStmt.run({ fingerprint, backlogBefore });
28129
- },
28130
- "IMMEDIATE"
28131
- );
28132
- }
28133
- /**
28134
- * End the attached period: hand its rows to the live path, and release the
28135
- * boundary so the next attachment can freeze a new one.
28136
- *
28137
- * WITHOUT THIS, a detach and a re-attach to the same deployment leave a window
28138
- * nothing delivers. The fingerprint is unchanged, so the boundary is never
28139
- * re-frozen and stays at the FIRST attachment — while nothing forwards at all
28140
- * during the detached period, because the machine is not attached. Rows
28141
- * recorded in that window sit after the boundary and before the re-attach, so
28142
- * neither path takes them, and the pending count reports none outstanding.
28143
- *
28144
- * Stamping the attached window is not a claim that every one of those rows
28145
- * reached the deployment — the live path drops on failure and says so
28146
- * elsewhere. It records that they were ITS to deliver, which is exactly the
28147
- * status quo: they sit outside the frozen boundary today and are equally never
28148
- * re-sent. Making it explicit is what lets the boundary move.
28149
- *
28150
- * ONE TRANSACTION, so a crash cannot release the boundary while leaving the
28151
- * window unstamped — that half-state would re-send the whole attached period
28152
- * on the next attach, which is the failure the boundary exists to prevent.
28153
- */
28154
- closeAttachedWindow(attachedAtMs, atMs) {
28155
- this.ensureRowStmt.run();
28156
- withTransaction(
28157
- this.db,
28158
- () => {
28159
- const row = getRow(this.fingerprintStmt);
28160
- const from = row?.backlogBefore ?? attachedAtMs;
28161
- this.closeWindowStmt.run({ at: atMs, attachedAt: from });
28162
- this.releaseBoundaryStmt.run();
28163
- },
28164
- "IMMEDIATE"
28165
- );
28166
- }
28167
- /**
28168
- * Freeze a boundary for the deployment already on file, KEEPING the stamps.
28169
- *
28170
- * The re-attach half of the above. Distinct from `rearmFor`, which is for a
28171
- * different deployment and therefore discards what was delivered to the old
28172
- * one: here the recipient is the same, so everything already sent to it stays
28173
- * sent.
28174
- */
28175
- freezeBoundary(backlogBefore) {
28176
- this.ensureRowStmt.run();
28177
- this.freezeBoundaryStmt.run({ backlogBefore });
28178
- }
28179
- /** Take the claim, or report that someone live already holds it. */
28180
- claim(pid, host, nowMs, staleAfterMs) {
28181
- this.ensureRowStmt.run();
28182
- let taken = false;
28183
- withTransaction(
28184
- this.db,
28185
- () => {
28186
- const result = this.claimStmt.run({
28187
- pid,
28188
- host,
28189
- now: nowMs,
28190
- staleBefore: nowMs - staleAfterMs
28191
- });
28192
- taken = result.changes === 1;
28193
- },
28194
- "IMMEDIATE"
28195
- );
28196
- return taken;
28197
- }
28198
- /** Say the holder is still alive. A no-op once the claim has moved on. */
28199
- heartbeat(pid, nowMs) {
28200
- this.heartbeatStmt.run({ now: nowMs, pid });
28201
- }
28202
- /** Give the claim up. Scoped to this holder, so a taken-over claim is left be. */
28203
- release(pid) {
28204
- this.releaseStmt.run({ pid });
28205
- }
28206
- /** Who holds the claim, if anyone. Read-only, for the same reason as above. */
28207
- lease() {
28208
- return getRow(this.leaseStmt);
28209
- }
28210
- };
28211
-
28212
28823
  // ../../packages/persistence/src/repositories/inspection-definitions.ts
28213
28824
  var SqliteInspectionDefinitionsRepository = class {
28214
28825
  constructor(db) {
@@ -28436,6 +29047,7 @@ function overlayManagedSettings(settings, managed, now = () => /* @__PURE__ */ n
28436
29047
  if (values.vaultInlineReveal !== void 0) merged.vaultInlineReveal = values.vaultInlineReveal;
28437
29048
  if (values.dataSharesInPlace !== void 0) merged.dataSharesInPlace = values.dataSharesInPlace;
28438
29049
  if (values.redactFallback !== void 0) merged.redactFallback = values.redactFallback;
29050
+ if (values.bodyRetention !== void 0) merged.bodyRetention = values.bodyRetention;
28439
29051
  if (values.vaultConsent !== void 0) {
28440
29052
  merged.vaultConsent = values.vaultConsent ? (
28441
29053
  // Keep an existing valid grant so its acknowledgedAt survives; mint one
@@ -30943,7 +31555,7 @@ var SqliteSecurityRepository = class {
30943
31555
  ELSE 0
30944
31556
  END) AS open_at_rest
30945
31557
  FROM inspection_findings f
30946
- JOIN audit_events e ON e.id = f.audit_event_id
31558
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
30947
31559
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
30948
31560
  LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
30949
31561
  ON latest.finding_key = f.finding_key
@@ -31169,7 +31781,7 @@ var SqliteSecurityRepository = class {
31169
31781
  this.db.prepare(
31170
31782
  `SELECT e.repo AS repo, count(*) AS c
31171
31783
  FROM inspection_findings f
31172
- JOIN audit_events e ON e.id = f.audit_event_id
31784
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31173
31785
  WHERE e.started_at >= :from AND e.started_at < :to
31174
31786
  AND e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
31175
31787
  AND e.repo IS NOT NULL
@@ -31293,7 +31905,7 @@ var SqliteSecurityRepository = class {
31293
31905
  d.severity AS severity,
31294
31906
  COUNT(*) AS count
31295
31907
  FROM inspection_findings f
31296
- JOIN audit_events e ON e.id = f.audit_event_id
31908
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31297
31909
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
31298
31910
  LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
31299
31911
  ON latest.finding_key = f.finding_key
@@ -31328,7 +31940,7 @@ var SqliteSecurityRepository = class {
31328
31940
  `SELECT e.started_at AS occurred_at, d.severity AS severity, f.action_taken AS action_taken,
31329
31941
  d.rule_id AS rule_id, d.category AS category
31330
31942
  FROM inspection_findings f
31331
- JOIN audit_events e ON e.id = f.audit_event_id
31943
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31332
31944
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
31333
31945
  WHERE e.started_at >= :from AND e.started_at < :to
31334
31946
  AND e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
@@ -32169,6 +32781,7 @@ function openWithPragmas(file2) {
32169
32781
  db.exec("PRAGMA journal_mode = WAL");
32170
32782
  db.exec("PRAGMA busy_timeout = 2000");
32171
32783
  db.exec("PRAGMA foreign_keys = ON");
32784
+ registerSqlFunctions(db);
32172
32785
  } catch (err) {
32173
32786
  closeQuietly(db);
32174
32787
  throw err;
@@ -32198,7 +32811,7 @@ function backupLegacyStore(db, file2) {
32198
32811
  discardStore(file2, backup);
32199
32812
  return backup;
32200
32813
  }
32201
- function openAndInitialize(file2, base) {
32814
+ function openAndInitialize(file2, base, skipTags) {
32202
32815
  let db = openWithPragmas(file2);
32203
32816
  try {
32204
32817
  if (isForeignSqliteLineage(db)) {
@@ -32208,7 +32821,7 @@ function openAndInitialize(file2, base) {
32208
32821
  `Detected an older, incompatible (tenant-bearing) ${DB_FILENAME}; backed it up to ${backup} and created a fresh store.`
32209
32822
  );
32210
32823
  }
32211
- applyMigrations(db, file2);
32824
+ applyMigrations(db, file2, { skipTags });
32212
32825
  tightenPerms(file2);
32213
32826
  const policies = new SqlitePoliciesRepository(db);
32214
32827
  const installedPacks = new SqliteInstalledPacksRepository(db, base);
@@ -32223,6 +32836,7 @@ function openAndInitialize(file2, base) {
32223
32836
  exceptions: new SqliteExceptionsRepository(db),
32224
32837
  resolutions: new SqliteResolutionsRepository(db),
32225
32838
  ruleProbeCache: new SqliteRuleProbeCacheRepository(db),
32839
+ bodyRetention: new SqliteBodyRetentionRepository(db),
32226
32840
  security: new SqliteSecurityRepository(db),
32227
32841
  detections: new SqliteDetectionsRepository(db),
32228
32842
  shares: new SqliteSharesRepository(db),
@@ -32245,7 +32859,8 @@ function openAndInitialize(file2, base) {
32245
32859
  throw err;
32246
32860
  }
32247
32861
  }
32248
- function openLocalDatabase(dir) {
32862
+ var DEFERRED_TAGS = new Set(DEFERRED_MIGRATION_TAGS);
32863
+ function openLocalDatabase(dir, options = {}) {
32249
32864
  ensureDataDirSync(dir);
32250
32865
  const file2 = join7(dir, DB_FILENAME);
32251
32866
  reapStalePartials(file2);
@@ -32257,6 +32872,7 @@ function openLocalDatabase(dir) {
32257
32872
  installedPacks,
32258
32873
  scanLedger,
32259
32874
  historySync,
32875
+ bodyRetention,
32260
32876
  secretVault,
32261
32877
  exceptions,
32262
32878
  resolutions,
@@ -32280,7 +32896,8 @@ function openLocalDatabase(dir) {
32280
32896
  // `dir` is always `<base>/data` — every caller resolves it through
32281
32897
  // `dataDir()` — so its parent is the `~/.aka` base the layout splits into
32282
32898
  // settings/ and data/, and the pack-policy floor needs both halves.
32283
- dirname2(dir)
32899
+ dirname2(dir),
32900
+ options.applyDeferredMigrations === true ? void 0 : DEFERRED_TAGS
32284
32901
  );
32285
32902
  function captureRowId(event) {
32286
32903
  return captureId(
@@ -32473,6 +33090,7 @@ function openLocalDatabase(dir) {
32473
33090
  installedPacks,
32474
33091
  scanLedger,
32475
33092
  historySync,
33093
+ bodyRetention,
32476
33094
  secretVault,
32477
33095
  exceptions,
32478
33096
  resolutions,
@@ -32513,8 +33131,35 @@ function openLocalDatabase(dir) {
32513
33131
 
32514
33132
  // ../../packages/persistence/src/egress-wire.ts
32515
33133
  import { createHash as createHash3 } from "crypto";
33134
+ var PROJECT_KEY_DIGEST_VERSION = "v2";
33135
+ var SCP_FORM = /^(?:[^@/]+@)?([^/:]+):(.+)$/;
33136
+ var DOS_DRIVE = /^[A-Za-z]:[\\/]/;
33137
+ var FILE_URL = /^file:\/\//i;
33138
+ var SCHEME_FORM = /^[a-z][a-z0-9+.-]*:\/\/(?:[^@/]+@)?([^/:]+)(?::\d+)?(\/.*)?$/i;
33139
+ var SLASH = "/".charCodeAt(0);
33140
+ var GIT_SUFFIX = ".git";
33141
+ function trimSlashes(path) {
33142
+ let start = 0;
33143
+ let end = path.length;
33144
+ while (start < end && path.charCodeAt(start) === SLASH) start += 1;
33145
+ while (end > start && path.charCodeAt(end - 1) === SLASH) end -= 1;
33146
+ return path.slice(start, end);
33147
+ }
33148
+ function canonicalGitUrl(url2) {
33149
+ const trimmed = url2.trim();
33150
+ if (DOS_DRIVE.test(trimmed) || FILE_URL.test(trimmed)) return trimmed;
33151
+ const scheme = SCHEME_FORM.exec(trimmed);
33152
+ const scp = scheme === null ? SCP_FORM.exec(trimmed) : null;
33153
+ const host = (scheme?.[1] ?? scp?.[1])?.toLowerCase();
33154
+ if (host === void 0) return trimmed;
33155
+ const path = (scheme === null ? scp?.[2] : scheme[2]) ?? "";
33156
+ const bare = trimSlashes(path);
33157
+ const cleaned = bare.endsWith(GIT_SUFFIX) ? bare.slice(0, -GIT_SUFFIX.length) : bare;
33158
+ return cleaned === "" ? host : `${host}/${cleaned}`;
33159
+ }
32516
33160
  function hashProjectKey(projectKey) {
32517
- return createHash3("sha256").update(projectKey, "utf8").digest("hex");
33161
+ const canonical = projectKey.startsWith("git:") ? `git:${canonicalGitUrl(projectKey.slice("git:".length))}` : projectKey;
33162
+ return createHash3("sha256").update(`${PROJECT_KEY_DIGEST_VERSION}:${canonical}`, "utf8").digest("hex");
32518
33163
  }
32519
33164
  function toIngestHit(hit) {
32520
33165
  return {
@@ -32681,18 +33326,50 @@ function fingerprintValue(key, raw) {
32681
33326
  return createHmac("sha256", key.material).update(raw, "utf8").digest("hex");
32682
33327
  }
32683
33328
 
33329
+ // ../../packages/persistence/src/forward-health.ts
33330
+ import { readFileSync as readFileSync7 } from "fs";
33331
+ import { join as join9 } from "path";
33332
+ var FAILURES = /* @__PURE__ */ new Set([
33333
+ "unauthorized",
33334
+ "forbidden",
33335
+ "unreachable"
33336
+ ]);
33337
+ var BREAKER_COOLDOWN_MS = 3e4;
33338
+ function parseForwardHealth(raw, nowMs) {
33339
+ try {
33340
+ const parsed2 = JSON.parse(raw);
33341
+ if (typeof parsed2 !== "object" || parsed2 === null) return null;
33342
+ const record2 = parsed2;
33343
+ const failures = typeof record2.consecutiveFailures === "number" && record2.consecutiveFailures >= 0 ? record2.consecutiveFailures : 0;
33344
+ const openedAtMs = typeof record2.openedAtMs === "number" && Number.isFinite(record2.openedAtMs) && record2.openedAtMs <= nowMs ? record2.openedAtMs : null;
33345
+ const lastFailure = typeof record2.lastFailure === "string" && FAILURES.has(record2.lastFailure) ? record2.lastFailure : null;
33346
+ return { consecutiveFailures: failures, openedAtMs, lastFailure };
33347
+ } catch {
33348
+ return null;
33349
+ }
33350
+ }
33351
+ function isForwardPaused(health, nowMs) {
33352
+ const openedAtMs = health?.openedAtMs ?? null;
33353
+ if (openedAtMs === null) return false;
33354
+ return nowMs - openedAtMs < BREAKER_COOLDOWN_MS;
33355
+ }
33356
+
32684
33357
  // ../../packages/persistence/src/history-backfill.ts
32685
33358
  import { existsSync as existsSync4 } from "fs";
32686
- import { join as join9 } from "path";
33359
+ import { join as join10 } from "path";
32687
33360
 
32688
33361
  // ../../packages/persistence/src/history-preview.ts
32689
33362
  import { existsSync as existsSync5 } from "fs";
32690
- import { join as join10 } from "path";
33363
+ import { join as join11 } from "path";
32691
33364
  import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
32692
33365
 
33366
+ // ../../packages/persistence/src/history-sync-state.ts
33367
+ import { readFileSync as readFileSync8 } from "fs";
33368
+ import { join as join12 } from "path";
33369
+
32693
33370
  // ../../packages/persistence/src/store-symlinks.ts
32694
33371
  import { existsSync as existsSync6, lstatSync as lstatSync3, readlinkSync, realpathSync, statSync as statSync4 } from "fs";
32695
- import { dirname as dirname3, join as join11, resolve } from "path";
33372
+ import { dirname as dirname3, join as join13, resolve } from "path";
32696
33373
 
32697
33374
  // ../../packages/persistence/src/vault/crypto.ts
32698
33375
  import {
@@ -32706,19 +33383,19 @@ import {
32706
33383
  // ../../packages/persistence/src/vault/key-provider.ts
32707
33384
  import { execFileSync } from "child_process";
32708
33385
  import { randomBytes as randomBytes2 } from "crypto";
32709
- import { chmodSync as chmodSync3, readFileSync as readFileSync7, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
32710
- import { join as join12 } from "path";
33386
+ import { chmodSync as chmodSync3, readFileSync as readFileSync9, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
33387
+ import { join as join14 } from "path";
32711
33388
 
32712
33389
  // ../../packages/persistence/src/vault/vault.ts
32713
33390
  import { randomBytes as randomBytes3, randomUUID as randomUUID12 } from "crypto";
32714
33391
 
32715
33392
  // ../../packages/persistence/src/warn-era-cap.ts
32716
33393
  import { existsSync as existsSync7, writeFileSync as writeFileSync4 } from "fs";
32717
- import { join as join13 } from "path";
33394
+ import { join as join15 } from "path";
32718
33395
  var MARKER = "warn-era-capped";
32719
33396
  function capWarnEraEnforcementOnce(db, policyMode, dataDir2) {
32720
33397
  if (policyMode !== "warn") return { capped: 0, skipped: "not-warn" };
32721
- const marker = join13(dataDir2, MARKER);
33398
+ const marker = join15(dataDir2, MARKER);
32722
33399
  if (existsSync7(marker)) return { capped: 0, skipped: "already-run" };
32723
33400
  const capped = db.policies.capCategoryActions();
32724
33401
  writeFileSync4(marker, `${new Date(Date.now()).toISOString()}
@@ -32909,10 +33586,10 @@ function parsed(schema, body, route) {
32909
33586
  }
32910
33587
  function withoutTrailingSlashes(endpoint) {
32911
33588
  let end = endpoint.length;
32912
- while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH) end -= 1;
33589
+ while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH2) end -= 1;
32913
33590
  return endpoint.slice(0, end);
32914
33591
  }
32915
- var SLASH = "/".charCodeAt(0);
33592
+ var SLASH2 = "/".charCodeAt(0);
32916
33593
  function createRemoteClient(options) {
32917
33594
  const base = withoutTrailingSlashes(options.endpoint);
32918
33595
  const url2 = (route) => `${base}${route}`;
@@ -33163,11 +33840,11 @@ function commandScanFor(config2, scanWorktree2, sourceTool) {
33163
33840
  }
33164
33841
 
33165
33842
  // ../../packages/plugin-runtime/src/attached/forward-drops.ts
33166
- import { readFileSync as readFileSync8 } from "fs";
33167
- import { join as join14 } from "path";
33843
+ import { readFileSync as readFileSync10 } from "fs";
33844
+ import { join as join16 } from "path";
33168
33845
  var FORWARD_DROPS_FILENAME = ATTACHED_FORWARD_DROPS_FILENAME;
33169
33846
  function forwardDropsPath(dataDir2) {
33170
- return join14(dataDir2, FORWARD_DROPS_FILENAME);
33847
+ return join16(dataDir2, FORWARD_DROPS_FILENAME);
33171
33848
  }
33172
33849
  function recordForwardDrops(dataDir2, count, nowMs) {
33173
33850
  if (count <= 0) return;
@@ -33185,7 +33862,7 @@ function recordForwardDrops(dataDir2, count, nowMs) {
33185
33862
  }
33186
33863
  function readForwardDrops(dataDir2) {
33187
33864
  try {
33188
- const parsed2 = JSON.parse(readFileSync8(forwardDropsPath(dataDir2), "utf8"));
33865
+ const parsed2 = JSON.parse(readFileSync10(forwardDropsPath(dataDir2), "utf8"));
33189
33866
  if (typeof parsed2 !== "object" || parsed2 === null) return null;
33190
33867
  const record2 = parsed2;
33191
33868
  if (typeof record2.droppedForwards !== "number" || !Number.isFinite(record2.droppedForwards)) {
@@ -33203,13 +33880,12 @@ function readForwardDrops(dataDir2) {
33203
33880
 
33204
33881
  // ../../packages/plugin-runtime/src/attached/forward-policy.ts
33205
33882
  import { randomUUID as randomUUID15 } from "crypto";
33206
- import { readFileSync as readFileSync15 } from "fs";
33207
33883
  import { readFile, rename, writeFile } from "fs/promises";
33208
- import { join as join24 } from "path";
33884
+ import { join as join26 } from "path";
33209
33885
 
33210
33886
  // ../../packages/plugin-sdk/src/config.ts
33211
33887
  import { existsSync as existsSync8 } from "fs";
33212
- import { join as join15 } from "path";
33888
+ import { join as join17 } from "path";
33213
33889
 
33214
33890
  // ../../packages/plugin-sdk/src/provider-env.ts
33215
33891
  var DEFAULT_ANTHROPIC_HOST = "api.anthropic.com";
@@ -33263,7 +33939,7 @@ function resolveProvider() {
33263
33939
  function loadConfig(base = defaultDataDir(), resolveProviderFn = resolveProvider) {
33264
33940
  try {
33265
33941
  ensureLayoutDirSync(base);
33266
- const settingsFile = join15(settingsDir(base), "settings.json");
33942
+ const settingsFile = join17(settingsDir(base), "settings.json");
33267
33943
  if (existsSync8(settingsFile)) tightenFile(settingsFile);
33268
33944
  } catch {
33269
33945
  }
@@ -33287,9 +33963,9 @@ function resolveProviderSafe(resolveProviderFn) {
33287
33963
  }
33288
33964
 
33289
33965
  // ../../packages/plugin-sdk/src/config-inventory.ts
33290
- import { readdirSync as readdirSync2, readFileSync as readFileSync10, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
33966
+ import { readdirSync as readdirSync2, readFileSync as readFileSync12, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
33291
33967
  import { homedir as homedir2 } from "os";
33292
- import { basename as basename3, join as join17 } from "path";
33968
+ import { basename as basename3, join as join19 } from "path";
33293
33969
 
33294
33970
  // ../../packages/detections/src/egress/registry.ts
33295
33971
  var EXTRACTOR_VERSION = "1";
@@ -33982,12 +34658,18 @@ var EGRESS_CODE_EXTENSIONS = /* @__PURE__ */ new Set([
33982
34658
  ".rs"
33983
34659
  ]);
33984
34660
  var SNIPPET_MAX = 200;
34661
+ var WHITESPACE = /\s/;
33985
34662
  var MASK = "\u2022\u2022\u2022\u2022";
33986
34663
  var URL_CANDIDATE = /(https?|wss?|sftp|grpcs?|smtp):\/\/(?:[^\s'"`<>()[\]{},;]|\$\{[^}\s]{1,64}\}|\{[A-Za-z_]\w{0,63}\}|%[sd])+/gi;
33987
34664
  var PLACEHOLDER = /\$\{[^}\s]{1,64}\}|\{[A-Za-z_]\w{0,63}\}|%[sd]/g;
33988
34665
  var VAR_TOKEN = "${var}";
33989
34666
  var VAR_SENTINEL = "akaegressvar0";
33990
- var TRAILING_PUNCTUATION = /[.,;:'"]+$/;
34667
+ var TRAILING_PUNCTUATION = `.,;:'"`;
34668
+ function stripTrailingPunctuation(value) {
34669
+ let end = value.length;
34670
+ while (end > 0 && TRAILING_PUNCTUATION.includes(value.charAt(end - 1))) end -= 1;
34671
+ return end === value.length ? value : value.slice(0, end);
34672
+ }
33991
34673
  var TRANSPORT_BY_SCHEME = {
33992
34674
  http: "http",
33993
34675
  https: "https",
@@ -34052,35 +34734,100 @@ var VENDORED_PATH = /(^|\/)(vendor|third_party|external)\//;
34052
34734
  function isVendoredPath(file2) {
34053
34735
  return VENDORED_PATH.test(file2);
34054
34736
  }
34055
- function redactLine(line) {
34056
- return line.trim().replace(USERINFO, "://").replace(WEBHOOK_URL, `$1${MASK}`).replace(SECRET_VALUE, `$1${MASK}`).replace(AUTH_SCHEME_VALUE, `$1$2 ${MASK}`).replace(BEARER_TOKEN, `Bearer ${MASK}`);
34737
+ var REDACTION_PASSES = [
34738
+ { pattern: USERINFO, replace: () => "://" },
34739
+ { pattern: WEBHOOK_URL, replace: (m) => `${m[1] ?? ""}${MASK}` },
34740
+ { pattern: SECRET_VALUE, replace: (m) => `${m[1] ?? ""}${MASK}` },
34741
+ { pattern: AUTH_SCHEME_VALUE, replace: (m) => `${m[1] ?? ""}${m[2] ?? ""} ${MASK}` },
34742
+ { pattern: BEARER_TOKEN, replace: () => `Bearer ${MASK}` }
34743
+ ];
34744
+ function runPass(input2, pass) {
34745
+ const at = [];
34746
+ const end = [];
34747
+ const before = [];
34748
+ const after = [];
34749
+ let output2 = "";
34750
+ let copied = 0;
34751
+ let shift = 0;
34752
+ for (const match of input2.matchAll(pass.pattern)) {
34753
+ const start = match.index;
34754
+ const matched = match[0];
34755
+ const replacement = pass.replace(match);
34756
+ output2 += input2.slice(copied, start) + replacement;
34757
+ at.push(start);
34758
+ end.push(start + matched.length);
34759
+ before.push(shift);
34760
+ shift += replacement.length - matched.length;
34761
+ after.push(shift);
34762
+ copied = start + matched.length;
34763
+ }
34764
+ if (at.length === 0) return { output: input2, edits: { at, end, before, after } };
34765
+ return { output: output2 + input2.slice(copied), edits: { at, end, before, after } };
34766
+ }
34767
+ function throughPass(edits, offset) {
34768
+ let low = 0;
34769
+ let high = edits.at.length - 1;
34770
+ let found = -1;
34771
+ while (low <= high) {
34772
+ const mid = low + high >> 1;
34773
+ if ((edits.at[mid] ?? 0) <= offset) {
34774
+ found = mid;
34775
+ low = mid + 1;
34776
+ } else {
34777
+ high = mid - 1;
34778
+ }
34779
+ }
34780
+ if (found === -1) return offset;
34781
+ if (offset < (edits.end[found] ?? 0)) return (edits.at[found] ?? 0) + (edits.before[found] ?? 0);
34782
+ return offset + (edits.after[found] ?? 0);
34057
34783
  }
34058
- function redactSnippet(line, anchor2 = 0) {
34059
- const redacted = redactLine(line);
34060
- if (redacted.length <= SNIPPET_MAX) return redacted;
34061
- const lead = line.length - line.trimStart().length;
34784
+ function redactedLineOf(line) {
34062
34785
  const trimmed = line.trim();
34063
- const mapped = redacted.length === trimmed.length ? anchor2 - lead : redactLine(trimmed.slice(0, Math.max(0, anchor2 - lead))).length;
34786
+ const edits = [];
34787
+ let text = trimmed;
34788
+ for (const pass of REDACTION_PASSES) {
34789
+ const result = runPass(text, pass);
34790
+ text = result.output;
34791
+ edits.push(result.edits);
34792
+ }
34793
+ if (text.length <= SNIPPET_MAX) return { redacted: text };
34794
+ return {
34795
+ redacted: text,
34796
+ window: { trimmed, edits, lead: line.length - line.trimStart().length }
34797
+ };
34798
+ }
34799
+ function snippetWindow({ redacted, window }, anchor2) {
34800
+ if (window === void 0) return redacted;
34801
+ const { trimmed, edits, lead } = window;
34802
+ let mapped = Math.max(0, anchor2 - lead);
34803
+ if (redacted.length !== trimmed.length) {
34804
+ while (mapped > 0 && WHITESPACE.test(trimmed.charAt(mapped - 1))) mapped -= 1;
34805
+ for (const pass of edits) mapped = throughPass(pass, mapped);
34806
+ }
34064
34807
  const start = Math.min(
34065
34808
  Math.max(0, mapped - Math.floor(SNIPPET_MAX / 2)),
34066
34809
  redacted.length - SNIPPET_MAX
34067
34810
  );
34068
34811
  return redacted.slice(start, start + SNIPPET_MAX);
34069
34812
  }
34813
+ function redactSnippet(line, anchor2 = 0) {
34814
+ return snippetWindow(redactedLineOf(line), anchor2);
34815
+ }
34070
34816
  function extractEgress(text) {
34071
34817
  const lineStarts = lineStartOffsets(text);
34072
34818
  const urlSpans = [];
34073
34819
  const hits = [];
34074
34820
  const lineTextOf = memoizeByLine((index) => lineTextAt(text, lineStarts, index));
34075
34821
  const ipContextOf = memoizeByLine((index) => ipLineContext(lineTextOf(index)));
34076
- const snippetAt = (index, offset) => redactSnippet(lineTextOf(index), offset - (lineStarts[index] ?? 0));
34822
+ const redactedOf = memoizeByLine((index) => redactedLineOf(lineTextOf(index)));
34823
+ const snippetAt = (index, offset) => snippetWindow(redactedOf(index), offset - (lineStarts[index] ?? 0));
34077
34824
  for (const match of text.matchAll(URL_CANDIDATE)) {
34078
34825
  const start = match.index;
34079
34826
  const matched = match[0];
34080
34827
  urlSpans.push([start, start + matched.length]);
34081
34828
  const scheme = match[1];
34082
34829
  if (scheme === void 0) continue;
34083
- const candidate = matched.replace(TRAILING_PUNCTUATION, "");
34830
+ const candidate = stripTrailingPunctuation(matched);
34084
34831
  if (candidate === "") continue;
34085
34832
  const parsed2 = parseCandidate(candidate, scheme);
34086
34833
  if (parsed2 === null) continue;
@@ -34314,33 +35061,37 @@ function extractManifestSdks(text, kind) {
34314
35061
  return [];
34315
35062
  }
34316
35063
  }
34317
- function makeHit(ecosystem, pkg, line, rawLine) {
34318
- return { ecosystem, pkg, line, snippet: redactSnippet(rawLine) };
35064
+ function makeHit(ecosystem, pkg, line, snippet) {
35065
+ return { ecosystem, pkg, line, snippet };
34319
35066
  }
34320
35067
  function extractPackageJson(text) {
34321
35068
  const parsed2 = parseJson(text);
34322
35069
  if (parsed2 === null) return [];
34323
35070
  const seen = /* @__PURE__ */ new Set();
34324
35071
  const hits = [];
35072
+ const lines = manifestLines(text);
35073
+ const tokens = quotedTokenOffsets(text);
35074
+ const dependenciesAt = sectionOffset(text, "dependencies");
35075
+ const optionalAt = sectionOffset(text, "optionalDependencies");
34325
35076
  for (const pkg of objectKeys(parsed2.dependencies)) {
34326
35077
  seen.add(pkg);
34327
- hits.push(hitAtQuotedKey("npm", pkg, text, "dependencies"));
35078
+ hits.push(hitAtQuotedKey("npm", pkg, text, dependenciesAt, lines, tokens));
34328
35079
  }
34329
35080
  for (const pkg of objectKeys(parsed2.optionalDependencies)) {
34330
35081
  if (seen.has(pkg)) continue;
34331
35082
  seen.add(pkg);
34332
- hits.push(hitAtQuotedKey("npm", pkg, text, "optionalDependencies"));
35083
+ hits.push(hitAtQuotedKey("npm", pkg, text, optionalAt, lines, tokens));
34333
35084
  }
34334
35085
  return hits;
34335
35086
  }
34336
35087
  var REQUIREMENTS_NAME = /^\s*([A-Za-z0-9][\w.-]*)/;
34337
35088
  function extractRequirementsTxt(text) {
34338
35089
  const hits = [];
34339
- eachLine(text, (rawLine, lineNumber) => {
35090
+ eachLine(text, (rawLine, lineNumber, snippet) => {
34340
35091
  const match = REQUIREMENTS_NAME.exec(rawLine);
34341
35092
  const name = match?.[1];
34342
35093
  if (name === void 0) return;
34343
- hits.push(makeHit("pypi", normalizePypi(name), lineNumber, rawLine));
35094
+ hits.push(makeHit("pypi", normalizePypi(name), lineNumber, snippet()));
34344
35095
  });
34345
35096
  return hits;
34346
35097
  }
@@ -34352,7 +35103,7 @@ function extractPyprojectToml(text) {
34352
35103
  const hits = [];
34353
35104
  let section = "";
34354
35105
  let inDependenciesArray = false;
34355
- eachLine(text, (rawLine, lineNumber) => {
35106
+ eachLine(text, (rawLine, lineNumber, snippet) => {
34356
35107
  const sectionMatch = TOML_SECTION.exec(rawLine);
34357
35108
  if (sectionMatch) {
34358
35109
  section = sectionMatch[1]?.trim() ?? "";
@@ -34366,7 +35117,7 @@ function extractPyprojectToml(text) {
34366
35117
  for (const spec of quotedStrings(rawLine)) {
34367
35118
  const name = PEP508_NAME.exec(spec)?.[1];
34368
35119
  if (name !== void 0)
34369
- hits.push(makeHit("pypi", normalizePypi(name), lineNumber, rawLine));
35120
+ hits.push(makeHit("pypi", normalizePypi(name), lineNumber, snippet()));
34370
35121
  }
34371
35122
  if (rawLine.includes("]")) inDependenciesArray = false;
34372
35123
  return;
@@ -34374,7 +35125,7 @@ function extractPyprojectToml(text) {
34374
35125
  if (section === "tool.poetry.dependencies") {
34375
35126
  const key = POETRY_KEY.exec(rawLine)?.[1];
34376
35127
  if (key !== void 0 && key !== "python") {
34377
- hits.push(makeHit("pypi", normalizePypi(key), lineNumber, rawLine));
35128
+ hits.push(makeHit("pypi", normalizePypi(key), lineNumber, snippet()));
34378
35129
  }
34379
35130
  }
34380
35131
  });
@@ -34390,7 +35141,7 @@ var GO_MODULE_VERSION_LINE = /^\s*([\w./-]+)\s+v\d/;
34390
35141
  function extractGoMod(text) {
34391
35142
  const hits = [];
34392
35143
  let blockKeyword = null;
34393
- eachLine(text, (rawLine, lineNumber) => {
35144
+ eachLine(text, (rawLine, lineNumber, snippet) => {
34394
35145
  if (blockKeyword === null) {
34395
35146
  const open3 = GO_BLOCK_OPEN.exec(rawLine)?.[1];
34396
35147
  if (open3 !== void 0) {
@@ -34398,7 +35149,7 @@ function extractGoMod(text) {
34398
35149
  return;
34399
35150
  }
34400
35151
  const path = GO_REQUIRE_SINGLE_LINE.exec(rawLine)?.[1];
34401
- if (path !== void 0) hits.push(makeHit("go", path, lineNumber, rawLine));
35152
+ if (path !== void 0) hits.push(makeHit("go", path, lineNumber, snippet()));
34402
35153
  return;
34403
35154
  }
34404
35155
  if (GO_BLOCK_CLOSE.test(rawLine)) {
@@ -34407,7 +35158,7 @@ function extractGoMod(text) {
34407
35158
  }
34408
35159
  if (blockKeyword === "require") {
34409
35160
  const path = GO_MODULE_VERSION_LINE.exec(rawLine)?.[1];
34410
- if (path !== void 0) hits.push(makeHit("go", path, lineNumber, rawLine));
35161
+ if (path !== void 0) hits.push(makeHit("go", path, lineNumber, snippet()));
34411
35162
  }
34412
35163
  });
34413
35164
  return hits;
@@ -34424,13 +35175,13 @@ var POM_CONTEXT_TAGS = /* @__PURE__ */ new Set([
34424
35175
  "exclusions",
34425
35176
  "exclusion"
34426
35177
  ]);
34427
- var XML_TAG = /<(\/?)([A-Za-z][\w.-]*)([^<>]*)>/g;
35178
+ var XML_TAG = /<(\/?)([A-Za-z][\w.-]*)((?:[^<>\w.-][^<>]*)?)>/g;
34428
35179
  var LEADING_TEXT = /^([^<]*)/;
34429
35180
  function extractPomXml(text) {
34430
35181
  const hits = [];
34431
35182
  const stack = [];
34432
35183
  let inComment = false;
34433
- eachLine(text, (rawLine, lineNumber) => {
35184
+ eachLine(text, (rawLine, lineNumber, snippet) => {
34434
35185
  const stripped = stripXmlComments(rawLine, inComment);
34435
35186
  inComment = stripped.inComment;
34436
35187
  const visible = stripped.visible;
@@ -34449,7 +35200,7 @@ function extractPomXml(text) {
34449
35200
  const after = visible.slice(match.index + match[0].length);
34450
35201
  const value = LEADING_TEXT.exec(after)?.[1]?.trim() ?? "";
34451
35202
  if (value !== "" && isProjectDependencyGroupId(stack)) {
34452
- hits.push(makeHit("maven", value, lineNumber, rawLine));
35203
+ hits.push(makeHit("maven", value, lineNumber, snippet()));
34453
35204
  }
34454
35205
  continue;
34455
35206
  }
@@ -34465,11 +35216,11 @@ var GRADLE_DEPENDENCY = /\b(?:implementation|api|compile)\b\s*[('"]*(?:platform\
34465
35216
  var LINE_COMMENT = /^\s*\/\//;
34466
35217
  function extractBuildGradle(text) {
34467
35218
  const hits = [];
34468
- eachLine(text, (rawLine, lineNumber) => {
35219
+ eachLine(text, (rawLine, lineNumber, snippet) => {
34469
35220
  if (LINE_COMMENT.test(rawLine)) return;
34470
35221
  for (const match of rawLine.matchAll(GRADLE_DEPENDENCY)) {
34471
35222
  const groupId = match[1];
34472
- if (groupId !== void 0) hits.push(makeHit("maven", groupId, lineNumber, rawLine));
35223
+ if (groupId !== void 0) hits.push(makeHit("maven", groupId, lineNumber, snippet()));
34473
35224
  }
34474
35225
  });
34475
35226
  return hits;
@@ -34477,9 +35228,9 @@ function extractBuildGradle(text) {
34477
35228
  var GEMFILE_DEPENDENCY = /^\s*gem\s+['"]([\w-]+)['"]/;
34478
35229
  function extractGemfile(text) {
34479
35230
  const hits = [];
34480
- eachLine(text, (rawLine, lineNumber) => {
35231
+ eachLine(text, (rawLine, lineNumber, snippet) => {
34481
35232
  const name = GEMFILE_DEPENDENCY.exec(rawLine)?.[1];
34482
- if (name !== void 0) hits.push(makeHit("rubygems", name, lineNumber, rawLine));
35233
+ if (name !== void 0) hits.push(makeHit("rubygems", name, lineNumber, snippet()));
34483
35234
  });
34484
35235
  return hits;
34485
35236
  }
@@ -34487,7 +35238,7 @@ var CARGO_KEY = /^([A-Za-z0-9_-]+)\s*=/;
34487
35238
  function extractCargoToml(text) {
34488
35239
  const hits = [];
34489
35240
  let mode = "none";
34490
- eachLine(text, (rawLine, lineNumber) => {
35241
+ eachLine(text, (rawLine, lineNumber, snippet) => {
34491
35242
  const sectionMatch = TOML_SECTION.exec(rawLine);
34492
35243
  if (sectionMatch) {
34493
35244
  const name = sectionMatch[1]?.trim() ?? "";
@@ -34496,7 +35247,7 @@ function extractCargoToml(text) {
34496
35247
  } else if (name.startsWith("dependencies.")) {
34497
35248
  mode = "dotted";
34498
35249
  const crate = name.slice("dependencies.".length);
34499
- if (crate !== "") hits.push(makeHit("cargo", crate, lineNumber, rawLine));
35250
+ if (crate !== "") hits.push(makeHit("cargo", crate, lineNumber, snippet()));
34500
35251
  } else {
34501
35252
  mode = "none";
34502
35253
  }
@@ -34504,7 +35255,7 @@ function extractCargoToml(text) {
34504
35255
  }
34505
35256
  if (mode === "plain") {
34506
35257
  const crate = CARGO_KEY.exec(rawLine)?.[1];
34507
- if (crate !== void 0) hits.push(makeHit("cargo", crate, lineNumber, rawLine));
35258
+ if (crate !== void 0) hits.push(makeHit("cargo", crate, lineNumber, snippet()));
34508
35259
  }
34509
35260
  });
34510
35261
  return hits;
@@ -34513,17 +35264,20 @@ function extractComposerJson(text) {
34513
35264
  const parsed2 = parseJson(text);
34514
35265
  if (parsed2 === null) return [];
34515
35266
  const pkgs = objectKeys(parsed2.require).filter((pkg) => pkg !== "php" && !pkg.startsWith("ext-"));
34516
- return pkgs.map((pkg) => hitAtQuotedKey("composer", pkg, text, "require"));
35267
+ const lines = manifestLines(text);
35268
+ const tokens = quotedTokenOffsets(text);
35269
+ const requireAt = sectionOffset(text, "require");
35270
+ return pkgs.map((pkg) => hitAtQuotedKey("composer", pkg, text, requireAt, lines, tokens));
34517
35271
  }
34518
35272
  var CSPROJ_PACKAGE_REFERENCE = /<PackageReference\s+Include="([^"]+)"/;
34519
35273
  function extractCsproj(text) {
34520
35274
  const hits = [];
34521
35275
  let inComment = false;
34522
- eachLine(text, (rawLine, lineNumber) => {
35276
+ eachLine(text, (rawLine, lineNumber, snippet) => {
34523
35277
  const stripped = stripXmlComments(rawLine, inComment);
34524
35278
  inComment = stripped.inComment;
34525
35279
  const name = CSPROJ_PACKAGE_REFERENCE.exec(stripped.visible)?.[1];
34526
- if (name !== void 0) hits.push(makeHit("nuget", name, lineNumber, rawLine));
35280
+ if (name !== void 0) hits.push(makeHit("nuget", name, lineNumber, snippet()));
34527
35281
  });
34528
35282
  return hits;
34529
35283
  }
@@ -34531,11 +35285,11 @@ var PACKAGES_CONFIG_PACKAGE = /<package\s+id="([^"]+)"/;
34531
35285
  function extractPackagesConfig(text) {
34532
35286
  const hits = [];
34533
35287
  let inComment = false;
34534
- eachLine(text, (rawLine, lineNumber) => {
35288
+ eachLine(text, (rawLine, lineNumber, snippet) => {
34535
35289
  const stripped = stripXmlComments(rawLine, inComment);
34536
35290
  inComment = stripped.inComment;
34537
35291
  const name = PACKAGES_CONFIG_PACKAGE.exec(stripped.visible)?.[1];
34538
- if (name !== void 0) hits.push(makeHit("nuget", name, lineNumber, rawLine));
35292
+ if (name !== void 0) hits.push(makeHit("nuget", name, lineNumber, snippet()));
34539
35293
  });
34540
35294
  return hits;
34541
35295
  }
@@ -34561,7 +35315,9 @@ function stripXmlComments(line, inComment) {
34561
35315
  function eachLine(text, fn) {
34562
35316
  const lines = text.split("\n");
34563
35317
  for (let i = 0; i < lines.length; i += 1) {
34564
- fn(lines[i] ?? "", i + 1);
35318
+ const rawLine = lines[i] ?? "";
35319
+ let cached2;
35320
+ fn(rawLine, i + 1, () => cached2 ??= redactSnippet(rawLine));
34565
35321
  }
34566
35322
  }
34567
35323
  function parseJson(text) {
@@ -34583,24 +35339,76 @@ function objectKeys(value) {
34583
35339
  if (typeof value !== "object" || value === null) return [];
34584
35340
  return Object.keys(value);
34585
35341
  }
34586
- function hitAtQuotedKey(ecosystem, pkg, text, sectionKey) {
34587
- const sectionStart = text.indexOf(`"${sectionKey}"`);
34588
- const searchFrom = sectionStart === -1 ? 0 : sectionStart;
34589
- const index = text.indexOf(`"${pkg}"`, searchFrom);
34590
- if (index === -1) return makeHit(ecosystem, pkg, 1, pkg);
34591
- return makeHit(ecosystem, pkg, lineNumberAt(text, index), lineContaining(text, index));
35342
+ function manifestLines(text) {
35343
+ const starts = lineStartOffsets(text);
35344
+ const snippets = /* @__PURE__ */ new Map();
35345
+ return {
35346
+ numberAt: (index) => lineIndexAt(starts, index) + 1,
35347
+ snippetAt: (index) => {
35348
+ const line = lineIndexAt(starts, index);
35349
+ const cached2 = snippets.get(line);
35350
+ if (cached2 !== void 0) return cached2;
35351
+ const value = redactSnippet(lineTextAt(text, starts, line));
35352
+ snippets.set(line, value);
35353
+ return value;
35354
+ }
35355
+ };
35356
+ }
35357
+ function sectionOffset(text, sectionKey) {
35358
+ const at = text.indexOf(`"${sectionKey}"`);
35359
+ return at === -1 ? 0 : at;
35360
+ }
35361
+ var QUOTE = 34;
35362
+ var BACKSLASH = 92;
35363
+ function quotedTokenOffsets(text) {
35364
+ const at = /* @__PURE__ */ new Map();
35365
+ for (let i = 0; i < text.length; i += 1) {
35366
+ if (text.charCodeAt(i) !== QUOTE) continue;
35367
+ let end = i + 1;
35368
+ while (end < text.length && text.charCodeAt(end) !== QUOTE) {
35369
+ end += text.charCodeAt(end) === BACKSLASH ? 2 : 1;
35370
+ }
35371
+ if (end >= text.length) break;
35372
+ const inner = text.slice(i + 1, end);
35373
+ const name = inner.includes("\\") ? decodeJsonString(text.slice(i, end + 1)) : inner;
35374
+ if (name !== void 0) {
35375
+ const seen = at.get(name);
35376
+ if (seen === void 0) at.set(name, [i]);
35377
+ else seen.push(i);
35378
+ }
35379
+ i = end;
35380
+ }
35381
+ return at;
35382
+ }
35383
+ function decodeJsonString(quoted) {
35384
+ try {
35385
+ return JSON.parse(quoted);
35386
+ } catch {
35387
+ return void 0;
35388
+ }
34592
35389
  }
34593
- function lineNumberAt(text, index) {
34594
- let line = 1;
34595
- for (let i = 0; i < index; i += 1) {
34596
- if (text[i] === "\n") line += 1;
35390
+ function firstAtOrAfter(offsets, from) {
35391
+ let low = 0;
35392
+ let high = offsets.length - 1;
35393
+ let found;
35394
+ while (low <= high) {
35395
+ const mid = low + high >> 1;
35396
+ const at = offsets[mid] ?? 0;
35397
+ if (at >= from) {
35398
+ found = at;
35399
+ high = mid - 1;
35400
+ } else {
35401
+ low = mid + 1;
35402
+ }
34597
35403
  }
34598
- return line;
35404
+ return found;
34599
35405
  }
34600
- function lineContaining(text, index) {
34601
- const start = text.lastIndexOf("\n", index) + 1;
34602
- const end = text.indexOf("\n", index);
34603
- return text.slice(start, end === -1 ? text.length : end);
35406
+ function hitAtQuotedKey(ecosystem, pkg, text, searchFrom, lines, tokens) {
35407
+ const offsets = tokens.get(pkg);
35408
+ const known = offsets === void 0 ? void 0 : firstAtOrAfter(offsets, searchFrom);
35409
+ const index = known ?? text.indexOf(`"${pkg}"`, searchFrom);
35410
+ if (index === -1) return makeHit(ecosystem, pkg, 1, redactSnippet(pkg));
35411
+ return { ecosystem, pkg, line: lines.numberAt(index), snippet: lines.snippetAt(index) };
34604
35412
  }
34605
35413
 
34606
35414
  // ../../packages/detections/src/egress/resolve.ts
@@ -37213,8 +38021,8 @@ function bundledDetections() {
37213
38021
  }
37214
38022
 
37215
38023
  // ../../packages/plugin-sdk/src/repo.ts
37216
- import { existsSync as existsSync9, readFileSync as readFileSync9, statSync as statSync6 } from "fs";
37217
- import { basename as basename2, dirname as dirname4, isAbsolute, join as join16, sep as sep2 } from "path";
38024
+ import { existsSync as existsSync9, readFileSync as readFileSync11, statSync as statSync6 } from "fs";
38025
+ import { basename as basename2, dirname as dirname4, isAbsolute, join as join18, sep as sep2 } from "path";
37218
38026
  function resolveRepoIdentity(cwd) {
37219
38027
  try {
37220
38028
  const root = findGitRoot(cwd);
@@ -37243,36 +38051,36 @@ function resolveWorktreeRoot(cwd) {
37243
38051
  function findGitRoot(start) {
37244
38052
  let dir = start;
37245
38053
  for (; ; ) {
37246
- if (existsSync9(join16(dir, ".git"))) return dir;
38054
+ if (existsSync9(join18(dir, ".git"))) return dir;
37247
38055
  const parent = dirname4(dir);
37248
38056
  if (parent === dir) return void 0;
37249
38057
  dir = parent;
37250
38058
  }
37251
38059
  }
37252
38060
  function resolveGitContext(root) {
37253
- const dotGit = join16(root, ".git");
38061
+ const dotGit = join18(root, ".git");
37254
38062
  try {
37255
38063
  if (statSync6(dotGit).isDirectory()) {
37256
- return { configPath: join16(dotGit, "config"), headRoot: root };
38064
+ return { configPath: join18(dotGit, "config"), headRoot: root };
37257
38065
  }
37258
38066
  } catch {
37259
38067
  return void 0;
37260
38068
  }
37261
38069
  const target = /^gitdir:\s*(.+?)\s*$/m.exec(safeRead(dotGit) ?? "")?.[1];
37262
38070
  if (!target) return void 0;
37263
- const gitdir = isAbsolute(target) ? target : join16(root, target);
37264
- if (existsSync9(join16(gitdir, "config"))) {
37265
- return { configPath: join16(gitdir, "config"), headRoot: root };
38071
+ const gitdir = isAbsolute(target) ? target : join18(root, target);
38072
+ if (existsSync9(join18(gitdir, "config"))) {
38073
+ return { configPath: join18(gitdir, "config"), headRoot: root };
37266
38074
  }
37267
- const commonRaw = safeRead(join16(gitdir, "commondir"))?.trim();
38075
+ const commonRaw = safeRead(join18(gitdir, "commondir"))?.trim();
37268
38076
  if (!commonRaw) return void 0;
37269
- const commonGitDir = isAbsolute(commonRaw) ? commonRaw : join16(gitdir, commonRaw);
38077
+ const commonGitDir = isAbsolute(commonRaw) ? commonRaw : join18(gitdir, commonRaw);
37270
38078
  const headRoot = basename2(commonGitDir) === ".git" ? dirname4(commonGitDir) : root;
37271
- return { configPath: join16(commonGitDir, "config"), headRoot };
38079
+ return { configPath: join18(commonGitDir, "config"), headRoot };
37272
38080
  }
37273
38081
  function safeRead(path) {
37274
38082
  try {
37275
- return readFileSync9(path, "utf8");
38083
+ return readFileSync11(path, "utf8");
37276
38084
  } catch {
37277
38085
  return void 0;
37278
38086
  }
@@ -37816,8 +38624,8 @@ function createGuardedScanner(partition, gateway, opts) {
37816
38624
  }
37817
38625
 
37818
38626
  // ../../packages/plugin-sdk/src/host-floor.ts
37819
- import { readFileSync as readFileSync12 } from "fs";
37820
- import { join as join19 } from "path";
38627
+ import { readFileSync as readFileSync14 } from "fs";
38628
+ import { join as join21 } from "path";
37821
38629
 
37822
38630
  // ../../packages/plugin-sdk/src/model-governance.ts
37823
38631
  import {
@@ -37825,11 +38633,11 @@ import {
37825
38633
  fstatSync,
37826
38634
  mkdirSync as mkdirSync2,
37827
38635
  openSync as openSync2,
37828
- readFileSync as readFileSync11,
38636
+ readFileSync as readFileSync13,
37829
38637
  readSync,
37830
38638
  writeFileSync as writeFileSync5
37831
38639
  } from "fs";
37832
- import { join as join18 } from "path";
38640
+ import { join as join20 } from "path";
37833
38641
  var TAIL_BYTES = 256 * 1024;
37834
38642
 
37835
38643
  // ../../packages/plugin-sdk/src/host-floor.ts
@@ -37852,11 +38660,11 @@ var HOST_FLOORS = {
37852
38660
 
37853
38661
  // ../../packages/plugin-sdk/src/ignore-layers.ts
37854
38662
  var import_ignore = __toESM(require_ignore(), 1);
37855
- import { readFileSync as readFileSync13 } from "fs";
37856
- import { join as join20 } from "path";
38663
+ import { readFileSync as readFileSync15 } from "fs";
38664
+ import { join as join22 } from "path";
37857
38665
  function readIgnoreLayer(dir, filename, anchorLen) {
37858
38666
  try {
37859
- return { matcher: (0, import_ignore.default)().add(readFileSync13(join20(dir, filename), "utf8")), anchorLen };
38667
+ return { matcher: (0, import_ignore.default)().add(readFileSync15(join22(dir, filename), "utf8")), anchorLen };
37860
38668
  } catch {
37861
38669
  return void 0;
37862
38670
  }
@@ -37887,8 +38695,8 @@ function withLayer(layers, layer) {
37887
38695
  import { arch, hostname as hostname4, platform, release } from "os";
37888
38696
 
37889
38697
  // ../../packages/plugin-sdk/src/nudge.ts
37890
- import { mkdirSync as mkdirSync3, readFileSync as readFileSync14, writeFileSync as writeFileSync6 } from "fs";
37891
- import { join as join21 } from "path";
38698
+ import { mkdirSync as mkdirSync3, readFileSync as readFileSync16, writeFileSync as writeFileSync6 } from "fs";
38699
+ import { join as join23 } from "path";
37892
38700
 
37893
38701
  // ../../packages/plugin-sdk/src/paths.ts
37894
38702
  import { readdirSync as readdirSync3, realpathSync as realpathSync3 } from "fs";
@@ -37961,7 +38769,7 @@ function createPolicyResolver(bundle) {
37961
38769
 
37962
38770
  // ../../packages/plugin-sdk/src/project-files.ts
37963
38771
  import { existsSync as existsSync11, readdirSync as readdirSync4 } from "fs";
37964
- import { basename as basename5, join as join22 } from "path";
38772
+ import { basename as basename5, join as join24 } from "path";
37965
38773
 
37966
38774
  // ../../packages/plugin-sdk/src/provider-env-antigravity.ts
37967
38775
  var optionalBaseUrl2 = external_exports.preprocess((v) => {
@@ -38036,7 +38844,7 @@ function createPluginRuntime(gateway, settings, opts) {
38036
38844
  bundlesPacked = true;
38037
38845
  }
38038
38846
  const policyMode = settings.policy;
38039
- const redactFallback = settings.redactFallback;
38847
+ let redactFallback = settings.redactFallback;
38040
38848
  const dataDir2 = opts?.dataDir;
38041
38849
  let rules = [];
38042
38850
  let scanner;
@@ -38080,6 +38888,7 @@ function createPluginRuntime(gateway, settings, opts) {
38080
38888
  rules = [...verified, ...unverified];
38081
38889
  scanner = createGuardedScanner({ verified, unverified }, gateway, opts?.scanIsolation);
38082
38890
  bundleExceptions = bundle.exceptions ?? [];
38891
+ redactFallback = strongerRedactFallback(settings.redactFallback, bundle.redactFallback);
38083
38892
  initialized = true;
38084
38893
  }
38085
38894
  let cachedKey;
@@ -38118,11 +38927,13 @@ function createPluginRuntime(gateway, settings, opts) {
38118
38927
  function decide(findings, text, excepted, rewritable = true) {
38119
38928
  if (findings.length === 0) return { action: "log", text, findings: [] };
38120
38929
  const actionFor = (finding) => actionForFinding(finding, excepted, rewritable);
38930
+ const degradedActions = rewritable ? [] : findings.filter((f) => actionForFinding(f, excepted, true) === "redact").map(actionFor);
38931
+ const degraded = degradedActions.length === 0 ? {} : { redactDegradedTo: degradedActions.reduce((a, b) => strongerAction(a, b)) };
38121
38932
  let worst = "log";
38122
38933
  for (const finding of findings) {
38123
38934
  worst = strongerAction(worst, actionFor(finding));
38124
38935
  }
38125
- if (worst === "block") return { action: "block", text: null, findings };
38936
+ if (worst === "block") return { action: "block", text: null, findings, ...degraded };
38126
38937
  if (worst === "redact") {
38127
38938
  const redactFindings = findings.filter((f) => actionFor(f) === "redact");
38128
38939
  const reversibleFindings = redactFindings.filter((f) => resolver.isReversible(f.ruleId));
@@ -38132,9 +38943,13 @@ function createPluginRuntime(gateway, settings, opts) {
38132
38943
  findings,
38133
38944
  enforcedFindings: redactFindings,
38134
38945
  reversibleFindings
38946
+ // No `degraded` here, and it is not an omission: `rewritable` is per
38947
+ // CAPTURE, so on an unrewritable field every redact has already become
38948
+ // the fallback and this branch is unreachable. Spreading it would read
38949
+ // as a case that can happen.
38135
38950
  };
38136
38951
  }
38137
- return { action: worst, text, findings };
38952
+ return { action: worst, text, findings, ...degraded };
38138
38953
  }
38139
38954
  function fingerprintOf(key, finding, cache) {
38140
38955
  let fp = cache.get(finding);
@@ -38263,8 +39078,8 @@ function createPluginRuntime(gateway, settings, opts) {
38263
39078
  };
38264
39079
  }
38265
39080
  }
38266
- async function processText(text, context) {
38267
- return (await evaluate(text, context, {})).decision;
39081
+ async function processText(text, context, opts2 = {}) {
39082
+ return (await evaluate(text, context, {}, opts2.rewritable)).decision;
38268
39083
  }
38269
39084
  async function capture(input2, opts2 = {}) {
38270
39085
  const timingStartedAt = input2.occurredAt === void 0 ? startTiming() : void 0;
@@ -38287,10 +39102,12 @@ function createPluginRuntime(gateway, settings, opts) {
38287
39102
  );
38288
39103
  const storedContent = maskedFindings.length > 0 ? redact(input2.text, maskedFindings) : input2.text;
38289
39104
  const inspectionMs = elapsedMs(timingStartedAt);
38290
- const metadata = exceptionIds.length > 0 || inspectionMs !== void 0 ? {
39105
+ const redactDegradedTo = decision.redactDegradedTo;
39106
+ const metadata = exceptionIds.length > 0 || inspectionMs !== void 0 || redactDegradedTo !== void 0 ? {
38291
39107
  ...input2.metadata,
38292
39108
  ...exceptionIds.length > 0 ? { exceptionIds } : {},
38293
- ...inspectionMs !== void 0 ? { inspectionMs } : {}
39109
+ ...inspectionMs !== void 0 ? { inspectionMs } : {},
39110
+ ...redactDegradedTo !== void 0 ? { redactDegradedTo } : {}
38294
39111
  } : input2.metadata;
38295
39112
  const event = buildIngestEvent({
38296
39113
  kind: input2.kind,
@@ -38362,7 +39179,7 @@ var THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1e3;
38362
39179
 
38363
39180
  // ../../packages/plugin-sdk/src/throttle.ts
38364
39181
  import { mkdirSync as mkdirSync4, statSync as statSync8, writeFileSync as writeFileSync7 } from "fs";
38365
- import { join as join23 } from "path";
39182
+ import { join as join25 } from "path";
38366
39183
 
38367
39184
  // ../../packages/plugin-runtime/src/attached/forward-policy.ts
38368
39185
  function isInvalidRequest(err) {
@@ -38378,31 +39195,12 @@ function isServerRejection(err) {
38378
39195
  var FORWARD_BUDGET_MS = 1500;
38379
39196
  var DECISION_PATH_BUDGET_MS = 800;
38380
39197
  var BREAKER_FAILURE_THRESHOLD = 3;
38381
- var BREAKER_COOLDOWN_MS = 3e4;
38382
39198
  var CLOSED = { consecutiveFailures: 0, openedAtMs: null, lastFailure: null };
38383
- var FAILURES = /* @__PURE__ */ new Set([
38384
- "unauthorized",
38385
- "forbidden",
38386
- "unreachable"
38387
- ]);
38388
39199
  var FORWARD_STATE_FILENAME = ATTACHED_FORWARD_STATE_FILENAME;
38389
39200
  var STATE_FILENAME = FORWARD_STATE_FILENAME;
38390
- function parseBreakerState(raw, nowMs) {
38391
- try {
38392
- const parsed2 = JSON.parse(raw);
38393
- if (typeof parsed2 !== "object" || parsed2 === null) return null;
38394
- const record2 = parsed2;
38395
- const failures = typeof record2.consecutiveFailures === "number" && record2.consecutiveFailures >= 0 ? record2.consecutiveFailures : 0;
38396
- const openedAtMs = typeof record2.openedAtMs === "number" && Number.isFinite(record2.openedAtMs) && record2.openedAtMs <= nowMs ? record2.openedAtMs : null;
38397
- const lastFailure = typeof record2.lastFailure === "string" && FAILURES.has(record2.lastFailure) ? record2.lastFailure : null;
38398
- return { consecutiveFailures: failures, openedAtMs, lastFailure };
38399
- } catch {
38400
- return null;
38401
- }
38402
- }
38403
39201
  function createForwardPolicy(deps) {
38404
39202
  const now = deps.now ?? (() => Date.now());
38405
- const file2 = join24(deps.dir, STATE_FILENAME);
39203
+ const file2 = join26(deps.dir, STATE_FILENAME);
38406
39204
  let state = null;
38407
39205
  let loading = null;
38408
39206
  async function readState() {
@@ -38412,7 +39210,7 @@ function createForwardPolicy(deps) {
38412
39210
  } catch {
38413
39211
  return { ...CLOSED };
38414
39212
  }
38415
- return parseBreakerState(raw, now()) ?? { ...CLOSED };
39213
+ return parseForwardHealth(raw, now()) ?? { ...CLOSED };
38416
39214
  }
38417
39215
  async function load() {
38418
39216
  if (state !== null) return state;
@@ -38458,7 +39256,7 @@ function createForwardPolicy(deps) {
38458
39256
  };
38459
39257
  const at = now();
38460
39258
  if (current.openedAtMs !== null) {
38461
- if (at - current.openedAtMs < BREAKER_COOLDOWN_MS) {
39259
+ if (isForwardPaused(current, at)) {
38462
39260
  return { ok: false, reason: "breaker-open" };
38463
39261
  }
38464
39262
  await persist({
@@ -38995,7 +39793,18 @@ var AttachedDataGateway = class {
38995
39793
  // and the spread above would otherwise drop the field silently — which is
38996
39794
  // exactly what it did, leaving the whole control inert on every device
38997
39795
  // while every test around it stayed green.
38998
- prohibitedModels: cached2.prohibitedModels
39796
+ prohibitedModels: cached2.prohibitedModels,
39797
+ // NAMED for the same reason as the line above, and it is the same defect
39798
+ // if it is not: `...local` above spreads the DEVICE's bundle, so a field
39799
+ // only the cache carries is dropped in silence. That is what left
39800
+ // `prohibitedModels` inert on every attached device with every test
39801
+ // around it green.
39802
+ //
39803
+ // Taken from the cache rather than merged here, because merging it needs
39804
+ // the device's own SETTING — which is not a bundle field and is not in
39805
+ // scope at this seam. The runtime does that merge, raise-only, where both
39806
+ // values are in hand (createPluginRuntime's ensureInitialized).
39807
+ redactFallback: cached2.redactFallback
38999
39808
  // ALSO HONOURED FROM THE CACHE, and not a bundle field at all: each
39000
39809
  // merged policy's own `provenance`. `mergeRaiseOnly` spreads the policies
39001
39810
  // it emits, so an 'authored' policy arriving from the control plane
@@ -39123,10 +39932,6 @@ function toolAuditEvent(input2) {
39123
39932
  };
39124
39933
  }
39125
39934
 
39126
- // ../../packages/plugin-runtime/src/attached/history-state.ts
39127
- import { readFileSync as readFileSync16 } from "fs";
39128
- import { join as join25 } from "path";
39129
-
39130
39935
  // ../../packages/plugin-runtime/src/attached/history-sync.ts
39131
39936
  import { createHash as createHash6 } from "crypto";
39132
39937
  import { hostname as hostname5 } from "os";
@@ -39135,6 +39940,10 @@ import { hostname as hostname5 } from "os";
39135
39940
  var CORRELATION_ID = EventMetadata.shape.correlationId;
39136
39941
  var TRACE_ID = EventMetadata.shape.traceId;
39137
39942
  var EXCEPTION_ID = EventMetadata.shape.exceptionIds.unwrap().element;
39943
+ var REDACT_DEGRADED_TO = EventMetadata.shape.redactDegradedTo.unwrap();
39944
+
39945
+ // ../../packages/plugin-runtime/src/attached/history-sync.ts
39946
+ var CAPTURE_BATCH_BYTES = 1024 * 1024;
39138
39947
 
39139
39948
  // ../../packages/plugin-runtime/src/attached/history-sync-trigger.ts
39140
39949
  import { spawn } from "child_process";
@@ -39161,7 +39970,7 @@ function createPluginBlock(build, policyStore) {
39161
39970
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
39162
39971
  import { randomUUID as randomUUID16 } from "crypto";
39163
39972
  import { readFile as readFile2, rm, writeFile as writeFile2 } from "fs/promises";
39164
- import { join as join26 } from "path";
39973
+ import { join as join27 } from "path";
39165
39974
 
39166
39975
  // ../../packages/plugin-runtime/src/attached/atomic-publish.ts
39167
39976
  import { rename as rename2 } from "fs/promises";
@@ -39185,7 +39994,7 @@ async function publishByRename(tmp, file2, move = rename2) {
39185
39994
 
39186
39995
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
39187
39996
  function createPolicyStore(dir = dataDir()) {
39188
- const file2 = join26(dir, "policy-cache.json");
39997
+ const file2 = join27(dir, "policy-cache.json");
39189
39998
  async function read() {
39190
39999
  try {
39191
40000
  const raw = await readFile2(file2, "utf8");
@@ -39465,11 +40274,11 @@ function readStorePosture(dbPath2) {
39465
40274
  // ../../packages/plugin-runtime/src/attached/posture-store.ts
39466
40275
  import { randomUUID as randomUUID17 } from "crypto";
39467
40276
  import { readFile as readFile3, rm as rm2, writeFile as writeFile3 } from "fs/promises";
39468
- import { join as join27 } from "path";
40277
+ import { join as join28 } from "path";
39469
40278
  var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
39470
40279
  function createPostureStore(dir = settingsDir(), legacyDir) {
39471
- const file2 = join27(dir, "posture-state.json");
39472
- const legacyFile = legacyDir === void 0 ? null : join27(legacyDir, "posture-state.json");
40280
+ const file2 = join28(dir, "posture-state.json");
40281
+ const legacyFile = legacyDir === void 0 ? null : join28(legacyDir, "posture-state.json");
39473
40282
  async function persist(state) {
39474
40283
  await ensureDataDir(dir);
39475
40284
  const tmp = `${file2}.${randomUUID17()}.tmp`;
@@ -39538,10 +40347,10 @@ function createPostureStore(dir = settingsDir(), legacyDir) {
39538
40347
 
39539
40348
  // ../../packages/plugin-runtime/src/attached/sync-state.ts
39540
40349
  import { readFileSync as readFileSync18 } from "fs";
39541
- import { join as join28 } from "path";
40350
+ import { join as join29 } from "path";
39542
40351
  var SYNC_STATE_FILENAME = ATTACHED_SYNC_STATE_FILENAME;
39543
40352
  function syncStatePath(dataDir2) {
39544
- return join28(dataDir2, SYNC_STATE_FILENAME);
40353
+ return join29(dataDir2, SYNC_STATE_FILENAME);
39545
40354
  }
39546
40355
  function writeSyncState(dataDir2, result) {
39547
40356
  try {
@@ -39594,6 +40403,14 @@ import { spawn as spawn2 } from "child_process";
39594
40403
  import { fileURLToPath as fileURLToPath3 } from "url";
39595
40404
  var SYNC_THROTTLE_MS = 15 * 60 * 1e3;
39596
40405
 
40406
+ // ../../packages/plugin-runtime/src/content-retention-pass.ts
40407
+ var MAX_ROWS_PER_SWEEP = 50 * 1e3;
40408
+
40409
+ // ../../packages/plugin-runtime/src/content-retention-trigger.ts
40410
+ import { spawn as spawn3 } from "child_process";
40411
+ import { fileURLToPath as fileURLToPath4 } from "url";
40412
+ var CONTENT_RETENTION_THROTTLE_MS = 60 * 60 * 1e3;
40413
+
39597
40414
  // ../../packages/plugin-runtime/src/attached/factory.ts
39598
40415
  import { hostname as hostname6 } from "os";
39599
40416
 
@@ -40045,7 +40862,7 @@ var EXCEPTION_RETENTION_MS = 90 * 24 * 60 * 60 * 1e3;
40045
40862
 
40046
40863
  // ../../packages/scanner/src/discover.ts
40047
40864
  import { readdirSync as readdirSync5 } from "fs";
40048
- import { join as join29 } from "path";
40865
+ import { join as join30 } from "path";
40049
40866
 
40050
40867
  // ../../packages/scanner/src/constants.ts
40051
40868
  var COMMON_SKIP_DIRS = ["node_modules", "__pycache__", ".venv", "venv", ".cache"];
@@ -40077,7 +40894,7 @@ import { statSync as statSync11 } from "fs";
40077
40894
 
40078
40895
  // ../../packages/scanner/src/walk.ts
40079
40896
  import { readdirSync as readdirSync6, readFileSync as readFileSync19, statSync as statSync10 } from "fs";
40080
- import { extname, join as join30, relative as relative2, sep as sep4 } from "path";
40897
+ import { extname, join as join31, relative as relative2, sep as sep4 } from "path";
40081
40898
  var import_ignore2 = __toESM(require_ignore(), 1);
40082
40899
  var SOURCE_EXTENSIONS = /* @__PURE__ */ new Set([
40083
40900
  ".ts",
@@ -40128,7 +40945,7 @@ function* walkTree(rootDir, opts = {}) {
40128
40945
  );
40129
40946
  for (const entry of dirents) {
40130
40947
  const name = entry.name;
40131
- const fullPath = join30(dir, name);
40948
+ const fullPath = join31(dir, name);
40132
40949
  if (entry.isDirectory()) {
40133
40950
  const skipState = evaluateIgnore(dirSkipLayers, dirRel, name, true);
40134
40951
  if (skipState !== "unignored" && (SKIP_DIRS.has(name) || skipState === "ignored")) {