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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -50,7 +50,7 @@ var require_ignore = __commonJS({
50
50
  var REGEX_SPLITALL_CRLF = /\r?\n/g;
51
51
  var REGEX_TEST_INVALID_PATH = /^\.{0,2}\/|^\.{1,2}$/;
52
52
  var REGEX_TEST_TRAILING_SLASH = /\/$/;
53
- var SLASH2 = "/";
53
+ var SLASH3 = "/";
54
54
  var TMP_KEY_IGNORE = "node-ignore";
55
55
  if (typeof Symbol !== "undefined") {
56
56
  TMP_KEY_IGNORE = /* @__PURE__ */ Symbol.for("node-ignore");
@@ -422,11 +422,11 @@ var require_ignore = __commonJS({
422
422
  if (!REGEX_TEST_TRAILING_SLASH.test(path)) {
423
423
  return this.test(path);
424
424
  }
425
- const slices = path.split(SLASH2).filter(Boolean);
425
+ const slices = path.split(SLASH3).filter(Boolean);
426
426
  slices.pop();
427
427
  if (slices.length) {
428
428
  const parent = this._t(
429
- slices.join(SLASH2) + SLASH2,
429
+ slices.join(SLASH3) + SLASH3,
430
430
  this._testCache,
431
431
  true,
432
432
  slices
@@ -442,14 +442,14 @@ var require_ignore = __commonJS({
442
442
  return cache[path];
443
443
  }
444
444
  if (!slices) {
445
- slices = path.split(SLASH2).filter(Boolean);
445
+ slices = path.split(SLASH3).filter(Boolean);
446
446
  }
447
447
  slices.pop();
448
448
  if (!slices.length) {
449
449
  return cache[path] = this._rules.test(path, checkUnignored, MODE_IGNORE);
450
450
  }
451
451
  const parent = this._t(
452
- slices.join(SLASH2) + SLASH2,
452
+ slices.join(SLASH3) + SLASH3,
453
453
  cache,
454
454
  checkUnignored,
455
455
  slices
@@ -493,7 +493,7 @@ var require_ignore = __commonJS({
493
493
 
494
494
  // src/remediation/entry.ts
495
495
  import { readFileSync as readFileSync23 } from "fs";
496
- import { fileURLToPath as fileURLToPath5 } from "url";
496
+ import { fileURLToPath as fileURLToPath6 } from "url";
497
497
 
498
498
  // ../../packages/persistence/src/attached-derived.ts
499
499
  import { rmSync } from "fs";
@@ -506,6 +506,14 @@ var ATTACHED_FORWARD_DROPS_FILENAME = "attached-forward-drops.json";
506
506
  import { chmodSync as chmodSync2, lstatSync as lstatSync2, readFileSync, rmSync as rmSync3, statSync } from "fs";
507
507
  import { join as join2 } from "path";
508
508
 
509
+ // ../../packages/schema/src/drizzle/deferred-migrations.ts
510
+ var DEFERRED_MIGRATION_TAGS = [
511
+ "0031_audit_capture_by_time_index",
512
+ "0032_audit_capture_by_id_index",
513
+ "0033_audit_capture_location_index",
514
+ "0034_findings_read_indexes"
515
+ ];
516
+
509
517
  // ../../packages/schema/src/drizzle/sqlite-ddl.ts
510
518
  var SQLITE_MIGRATIONS = [
511
519
  {
@@ -623,6 +631,30 @@ var SQLITE_MIGRATIONS = [
623
631
  {
624
632
  tag: "0028_activity_session_probe_indexes",
625
633
  sql: "CREATE INDEX `idx_audit_session_prompt` ON `audit_events` (`root_session_id`) WHERE event_type = 'prompt';--> statement-breakpoint\nCREATE INDEX `idx_audit_session_share` ON `audit_events` (`root_session_id`) WHERE event_type = 'share';--> statement-breakpoint\nCREATE INDEX `idx_audit_ended_at` ON `audit_events` (`ended_at`,`root_session_id`) WHERE ended_at IS NOT NULL;--> statement-breakpoint\nCREATE INDEX `idx_audit_session_ended` ON `audit_events` (`root_session_id`,`ended_at`) WHERE ended_at IS NOT NULL;--> statement-breakpoint\n-- Expression index for the activity list's turns rollup: a live-captured\n-- session's turns are the DISTINCT `run_key` across its `llm_call` leaves, and\n-- carrying the extracted key in the index answers that count from the index\n-- alone instead of parsing every leaf's attribute bag. Written by hand, as\n-- 0013's `idx_audit_code_change_path` was: drizzle-kit cannot emit an\n-- expression containing a comma, so this index is not declared in sqlite.ts.\nCREATE INDEX `idx_audit_session_run_key` ON `audit_events` (`root_session_id`, json_extract(`attributes`, '$.run_key')) WHERE `event_type` = 'llm_call';\n"
634
+ },
635
+ {
636
+ tag: "0029_audit_capture_rollup_index",
637
+ sql: "CREATE INDEX `idx_audit_capture_rollup` ON `audit_events` (`event_type`,`started_at`,`repo`,`id`) WHERE event_type IN ('prompt','response','code_change','tool_use');"
638
+ },
639
+ {
640
+ tag: "0030_audit_content_expiry",
641
+ sql: "ALTER TABLE `audit_events` ADD `content_expired_at` integer;--> statement-breakpoint\nCREATE INDEX `idx_audit_expirable_body` ON `audit_events` (`started_at`) WHERE content IS NOT NULL;"
642
+ },
643
+ {
644
+ tag: "0031_audit_capture_by_time_index",
645
+ sql: "CREATE INDEX `idx_audit_capture_by_time` ON `audit_events` (`started_at`,`id`,`event_type`,`root_session_id`,`source_tool`,`repo`,`file_path`,`tool_name`) WHERE event_type IN ('prompt','response','code_change','tool_use');"
646
+ },
647
+ {
648
+ tag: "0032_audit_capture_by_id_index",
649
+ sql: "CREATE INDEX `idx_audit_capture_by_id` ON `audit_events` (`id`,`started_at`,`event_type`,`root_session_id`,`source_tool`,`repo`,`file_path`,`tool_name`) WHERE event_type IN ('prompt','response','code_change','tool_use');"
650
+ },
651
+ {
652
+ tag: "0033_audit_capture_location_index",
653
+ sql: "CREATE INDEX `idx_audit_capture_location` ON `audit_events` (`repo`,`file_path`,`started_at`,`id`,`event_type`) WHERE event_type IN ('prompt','response','code_change','tool_use');"
654
+ },
655
+ {
656
+ tag: "0034_findings_read_indexes",
657
+ sql: "CREATE INDEX `idx_inspection_definitions_rule` ON `inspection_definitions` (`rule_id`,`severity`,`category`);--> statement-breakpoint\nCREATE INDEX `idx_inspection_findings_def` ON `inspection_findings` (`inspection_definition_id`,`audit_event_id`);--> statement-breakpoint\nCREATE INDEX `idx_inspection_findings_event_cover` ON `inspection_findings` (`audit_event_id`,`inspection_definition_id`,`action_taken`,`finding_key`,`id`);"
626
658
  }
627
659
  ];
628
660
 
@@ -20670,6 +20702,15 @@ var FindingCategory = external_exports.enum([
20670
20702
  ]).meta({ id: "FindingCategory" });
20671
20703
  var FindingOrigin = external_exports.enum(["in-flight", "at-rest"]).meta({ id: "FindingOrigin" });
20672
20704
  var FindingStatus = external_exports.enum(["open", "handled", "resolved", "dismissed"]).meta({ id: "FindingStatus" });
20705
+ var SyncFailureReason = external_exports.enum(["deployment_refused", "payload_invalid", "detached_undelivered"]).meta({ id: "SyncFailureReason" });
20706
+ var FindingDeliveryState = external_exports.enum(["sent", "queued", "not_sent", "never_offered", "local_scan"]).meta({ id: "FindingDeliveryState" });
20707
+ var FindingDelivery = external_exports.object({
20708
+ state: FindingDeliveryState,
20709
+ // The delivery time for `sent`; the failure time for `not_sent` when recorded.
20710
+ at: external_exports.iso.datetime().optional(),
20711
+ // Only on `not_sent`, and only when a known reason was recorded.
20712
+ reason: SyncFailureReason.optional()
20713
+ }).meta({ id: "FindingDelivery" });
20673
20714
  var ResolutionMethod = external_exports.enum([
20674
20715
  "enforced-in-flight",
20675
20716
  "fixed-at-source",
@@ -20726,7 +20767,10 @@ var FindingInstance = external_exports.object({
20726
20767
  // The session that event belongs to, when it has one — the seam a
20727
20768
  // per-instance "view session" link needs. Absent for events captured
20728
20769
  // outside a session.
20729
- sessionId: external_exports.string().optional()
20770
+ sessionId: external_exports.string().optional(),
20771
+ // The delivery state of the event above (see FindingDelivery). Optional so
20772
+ // readers that do not project it stay valid.
20773
+ delivery: FindingDelivery.optional()
20730
20774
  }).meta({ id: "FindingInstance" });
20731
20775
  var FindingGroup = external_exports.object({
20732
20776
  id: external_exports.string(),
@@ -20778,7 +20822,10 @@ var FindingFacets = external_exports.object({
20778
20822
  // Host tool (attributes.tool_name). Present only on the instance-level
20779
20823
  // reads, which can filter by it; the type-level read omits the dimension
20780
20824
  // because a group spans tools.
20781
- tool: external_exports.array(FindingFacetItem).optional()
20825
+ tool: external_exports.array(FindingFacetItem).optional(),
20826
+ // Delivery states (FindingDeliveryState). Present only on the
20827
+ // instance-level reads, like `tool`.
20828
+ deployment: external_exports.array(FindingFacetItem).optional()
20782
20829
  }).meta({ id: "FindingFacets" });
20783
20830
  var FindingTypeSummary = FindingGroup.omit({ instances: true, match: true }).meta({
20784
20831
  id: "FindingTypeSummary"
@@ -20889,6 +20936,8 @@ var ListFindingInstancesQuery = external_exports.object({
20889
20936
  // Exact host-tool names (attributes.tool_name, e.g. 'Bash'). A real filter,
20890
20937
  // where the free-text `q` can only match the rendered "via Bash" label.
20891
20938
  tool: external_exports.array(external_exports.string()).optional(),
20939
+ // The delivery state of each finding's event (see FindingDelivery).
20940
+ deployment: external_exports.array(FindingDeliveryState).optional(),
20892
20941
  // Exact repository / file-path matches, for the drill-down out of the
20893
20942
  // locations view. A row whose event carries no repo/file matches neither.
20894
20943
  repo: external_exports.string().optional(),
@@ -20909,6 +20958,10 @@ var ListFindingInstancesResponse = external_exports.object({
20909
20958
  items: external_exports.array(FindingInstanceDetail),
20910
20959
  nextCursor: external_exports.string().nullable()
20911
20960
  }).meta({ id: "ListFindingInstancesResponse" });
20961
+ var ListFindingInstancesPage = external_exports.object({
20962
+ items: external_exports.array(FindingInstanceDetail),
20963
+ nextCursor: external_exports.string().nullable()
20964
+ }).meta({ id: "ListFindingInstancesPage" });
20912
20965
  var FindingLocationSummary = external_exports.object({
20913
20966
  // Opaque, stable, minted from the pair by encodeLocationId. It exists
20914
20967
  // because a location's identity is two values and a URL param carries one:
@@ -20951,6 +21004,8 @@ var ListFindingLocationsQuery = external_exports.object({
20951
21004
  // instances that match, and folds its status from those.
20952
21005
  status: external_exports.array(FindingStatus).optional(),
20953
21006
  tool: external_exports.array(external_exports.string()).optional(),
21007
+ // The delivery state of each finding's event (see FindingDelivery).
21008
+ deployment: external_exports.array(FindingDeliveryState).optional(),
20954
21009
  q: external_exports.string().optional(),
20955
21010
  sessionId: external_exports.string().optional(),
20956
21011
  from: external_exports.iso.datetime().optional(),
@@ -21153,6 +21208,10 @@ var CaptureAttributes = external_exports.object({
21153
21208
  // to 'allow' — the enforcement audit trail's link back to the grant that
21154
21209
  // authorized the bypass.
21155
21210
  exception_ids: external_exports.array(external_exports.guid()).optional(),
21211
+ // The persisted spellings of EventMetadata's messageId/conversationId — the
21212
+ // join back to the `llm_call` leaf for the same assistant turn.
21213
+ message_id: external_exports.string().optional(),
21214
+ conversation_id: external_exports.string().optional(),
21156
21215
  // Whole milliseconds this capture's inspection blocked its caller — the
21157
21216
  // plugin's own added latency (see EventMetadata.inspectionMs, whose value
21158
21217
  // this is). Promoted to the `inspection_ms` generated column so the facet is
@@ -21161,7 +21220,19 @@ var CaptureAttributes = external_exports.object({
21161
21220
  // inline json_extract and is not itself an optimization.
21162
21221
  // ABSENT on replayed captures (backfill / worktree scan) and on rows written
21163
21222
  // before the measurement shipped — never present as a placeholder 0.
21164
- inspection_ms: external_exports.number().int().nonnegative().optional()
21223
+ inspection_ms: external_exports.number().int().nonnegative().optional(),
21224
+ // What a `redact` this capture could not carry out became instead (see
21225
+ // EventMetadata.redactDegradedTo, whose value this is). Present only when a
21226
+ // degrade actually happened, so absence is the ordinary case rather than a
21227
+ // reader having to distinguish it from a zero.
21228
+ //
21229
+ // PER CAPTURE, while `inspection_findings.action_taken` is per finding —
21230
+ // so on a multi-finding row this does not say which finding degraded, and
21231
+ // its presence does not mean the fallback decided the capture's action. A
21232
+ // capture denied by another finding's own Block policy carries `block`
21233
+ // here too. The full statement is on EventMetadata.redactDegradedTo; it is
21234
+ // repeated rather than referenced because a store reader opens this file.
21235
+ redact_degraded_to: ActionTaken.optional()
21165
21236
  }).catchall(external_exports.unknown());
21166
21237
  var ToolCallInspection = external_exports.object({
21167
21238
  ruleId: external_exports.string().min(1),
@@ -21360,7 +21431,17 @@ var AuditEvent = external_exports.object({
21360
21431
  /** `share` to a first-party/internal destination. */
21361
21432
  internal: external_exports.boolean(),
21362
21433
  /** Event needs review (e.g. unverified egress). */
21363
- flagged: external_exports.boolean()
21434
+ flagged: external_exports.boolean(),
21435
+ /**
21436
+ * The body this event's `title` is drawn from was cleared by local body
21437
+ * expiry, so an EMPTY title here means "gone", not "never had one".
21438
+ *
21439
+ * A separate flag rather than a sentinel written into `title`: the title is
21440
+ * rendered text, and a store-layer module that invented display copy for it
21441
+ * would be choosing words the view is supposed to choose. Additive and
21442
+ * defaulted, so an older producer still validates.
21443
+ */
21444
+ bodyExpired: external_exports.boolean().default(false)
21364
21445
  }).meta({ id: "ActivityAuditEvent" });
21365
21446
  var ActivitySessionSummary = external_exports.object({
21366
21447
  id: external_exports.string(),
@@ -22701,6 +22782,12 @@ var EventMetadata = external_exports.object({
22701
22782
  // to 'allow' — the enforcement audit trail's link back to the grant that
22702
22783
  // authorized the bypass. Absent on captures where no exception applied.
22703
22784
  exceptionIds: external_exports.array(external_exports.guid()).optional(),
22785
+ // The assistant message this capture belongs to, and the conversation it sits
22786
+ // in — set by the browser extension's network capture so a stored `response`
22787
+ // row can be joined to the `llm_call` leaf describing the same turn. Absent
22788
+ // on every other capture path, which has no such id.
22789
+ messageId: external_exports.string().optional(),
22790
+ conversationId: external_exports.string().optional(),
22704
22791
  // How long THIS capture's inspection blocked its caller, in whole
22705
22792
  // milliseconds — the plugin's own added latency, NOT the LLM call it sat in
22706
22793
  // front of. Measured inside `capture()` (@akasecurity/plugin-sdk) across
@@ -22713,7 +22800,37 @@ var EventMetadata = external_exports.object({
22713
22800
  // Absent is also what every pre-measurement client writes, and what a
22714
22801
  // clock failure degrades to — a reader must treat absence as "not measured"
22715
22802
  // and never as a zero, which would read as "inspection is free".
22716
- inspectionMs: external_exports.number().int().nonnegative().optional()
22803
+ inspectionMs: external_exports.number().int().nonnegative().optional(),
22804
+ // What a `redact` this capture COULD NOT CARRY OUT became instead — the
22805
+ // workspace's `redactFallback`, applied because the field could not be
22806
+ // masked in place (a shell command, a URL, or any argument on a host whose
22807
+ // hook contract offers no rewrite channel).
22808
+ //
22809
+ // It exists because the action alone cannot say why. A finding recorded as
22810
+ // `warn` reads identically whether its detection was ASSIGNED Warn or was
22811
+ // assigned Redact on a field that could not take one — and those are
22812
+ // different facts about the same row: the first is a policy the user chose,
22813
+ // the second is a masking the host could not perform. Absent means no
22814
+ // degrade happened, which is every ordinary capture.
22815
+ //
22816
+ // TWO LIMITS a reader of a stored row has to know, because the grain here
22817
+ // is the CAPTURE while `actionTaken` is per FINDING:
22818
+ //
22819
+ // - It does not say WHICH finding degraded. A capture carrying a degraded
22820
+ // `redact` alongside a finding ASSIGNED the same action stores both
22821
+ // identically and one reason for the pair; attributing it to both
22822
+ // describes the assigned one wrongly, and to neither loses the degrade.
22823
+ // - PRESENCE IS NOT CAUSATION. The value is the action the lost redact
22824
+ // became, not the reason the capture ended as it did — a capture denied
22825
+ // by some other finding's own Block policy still carries `block` here,
22826
+ // and clearing the workspace's fallback would not have let it through.
22827
+ // Gate on the value against what a fallback can produce; never read the
22828
+ // field's presence as "this was the fallback's doing".
22829
+ //
22830
+ // Both are pinned as behaviour in @akasecurity/plugin-sdk's runtime suite.
22831
+ // Closing either means moving the reason onto the finding row, which
22832
+ // already carries its own action.
22833
+ redactDegradedTo: ActionTaken.optional()
22717
22834
  }).meta({ id: "EventMetadata" });
22718
22835
  var Event = external_exports.object({
22719
22836
  id: external_exports.guid(),
@@ -22823,7 +22940,32 @@ var RotateKeyInput = external_exports.object({
22823
22940
  confirmation: external_exports.string()
22824
22941
  });
22825
22942
 
22943
+ // ../../packages/schema/src/zod/finding-delivery.ts
22944
+ var KNOWN_REASONS = SyncFailureReason.options;
22945
+ function knownReason(value) {
22946
+ return value !== null && KNOWN_REASONS.includes(value) ? value : void 0;
22947
+ }
22948
+ function deriveFindingDelivery(row) {
22949
+ if (row.kind === "code_change") return { state: "local_scan" };
22950
+ if (row.syncedAt !== null && row.syncedAt > 0) {
22951
+ return { state: "sent", at: epochMillisToIso(row.syncedAt) };
22952
+ }
22953
+ if (row.syncedAt !== null) {
22954
+ const reason = knownReason(row.syncFailure);
22955
+ return {
22956
+ state: "not_sent",
22957
+ ...row.syncFailedAt === null ? {} : { at: epochMillisToIso(row.syncFailedAt) },
22958
+ ...reason === void 0 ? {} : { reason }
22959
+ };
22960
+ }
22961
+ if (row.outboxOwed === 1 || row.syncClaimedAt !== null) return { state: "queued" };
22962
+ return { state: "never_offered" };
22963
+ }
22964
+
22826
22965
  // ../../packages/schema/src/zod/findings-group-build.ts
22966
+ function lookupOwn(map2, key) {
22967
+ return Object.hasOwn(map2, key) ? map2[key] : void 0;
22968
+ }
22827
22969
  function toApiAction(dbVal) {
22828
22970
  const map2 = {
22829
22971
  log: "monitored",
@@ -22832,7 +22974,7 @@ function toApiAction(dbVal) {
22832
22974
  warn: "warned",
22833
22975
  allow: "allowed"
22834
22976
  };
22835
- return map2[dbVal] ?? "allowed";
22977
+ return lookupOwn(map2, dbVal) ?? "allowed";
22836
22978
  }
22837
22979
  function toApiCategory(dbVal) {
22838
22980
  if (dbVal === "code_context") return "source_code";
@@ -22840,13 +22982,18 @@ function toApiCategory(dbVal) {
22840
22982
  return parsed2.success ? parsed2.data : "custom";
22841
22983
  }
22842
22984
  function toApiProvider(sourceTool) {
22843
- return TOOL_TO_HARNESS[sourceTool] ?? HARNESS.Api;
22985
+ return lookupOwn(TOOL_TO_HARNESS, sourceTool) ?? HARNESS.Api;
22844
22986
  }
22845
- var STATUS_PRECEDENCE = ["open", "handled", "dismissed", "resolved"];
22987
+ var FINDING_STATUS_PRECEDENCE = [
22988
+ "open",
22989
+ "handled",
22990
+ "dismissed",
22991
+ "resolved"
22992
+ ];
22846
22993
  function foldGroupStatus(instanceStatuses) {
22847
22994
  const statuses = new Set(instanceStatuses.filter((s) => s !== void 0));
22848
22995
  if (statuses.size === 0) return void 0;
22849
- for (const candidate of STATUS_PRECEDENCE) {
22996
+ for (const candidate of FINDING_STATUS_PRECEDENCE) {
22850
22997
  if (statuses.has(candidate)) return candidate;
22851
22998
  }
22852
22999
  return void 0;
@@ -22953,11 +23100,16 @@ function applyFindingFilters(types, opts) {
22953
23100
  }
22954
23101
  return filtered;
22955
23102
  }
22956
- var SEVERITY_ORDER = { critical: 0, high: 1, medium: 2, low: 3 };
22957
- var SEVERITY_RANK = SEVERITY_ORDER;
23103
+ function rankByOrder(members2) {
23104
+ return Object.fromEntries(members2.map((member, index) => [member, index]));
23105
+ }
23106
+ var SEVERITY_RANK = rankByOrder(Severity.options);
23107
+ function severityRank(severity) {
23108
+ return lookupOwn(SEVERITY_RANK, severity);
23109
+ }
22958
23110
  function compareFindingGroupOrder(a, b) {
22959
- const rankA = SEVERITY_RANK[a.severity] ?? -1;
22960
- const rankB = SEVERITY_RANK[b.severity] ?? -1;
23111
+ const rankA = severityRank(a.severity) ?? -1;
23112
+ const rankB = severityRank(b.severity) ?? -1;
22961
23113
  const severityDiff = rankA - rankB;
22962
23114
  if (severityDiff !== 0) return severityDiff;
22963
23115
  const recencyDiff = b.latestDetectedAt.localeCompare(a.latestDetectedAt);
@@ -23032,6 +23184,20 @@ function computeFindingFacets(allTypes, opts) {
23032
23184
  }
23033
23185
 
23034
23186
  // ../../packages/schema/src/zod/findings-flat-build.ts
23187
+ function compareCodePoints(a, b) {
23188
+ const aIter = a[Symbol.iterator]();
23189
+ const bIter = b[Symbol.iterator]();
23190
+ for (; ; ) {
23191
+ const aNext = aIter.next();
23192
+ const bNext = bIter.next();
23193
+ if (aNext.done && bNext.done) return 0;
23194
+ if (aNext.done) return -1;
23195
+ if (bNext.done) return 1;
23196
+ const aPoint = aNext.value.codePointAt(0) ?? 0;
23197
+ const bPoint = bNext.value.codePointAt(0) ?? 0;
23198
+ if (aPoint !== bPoint) return aPoint - bPoint;
23199
+ }
23200
+ }
23035
23201
  function rowHaystack(row) {
23036
23202
  return [
23037
23203
  row.ruleId,
@@ -23056,6 +23222,8 @@ function matchesDimension(row, opts, dimension) {
23056
23222
  return !opts.actions?.length || opts.actions.includes(toApiAction(row.actionTaken));
23057
23223
  case "statuses":
23058
23224
  return !opts.statuses?.length || row.status !== void 0 && opts.statuses.includes(row.status);
23225
+ case "deliveries":
23226
+ return !opts.deliveries?.length || row.delivery !== void 0 && opts.deliveries.includes(row.delivery.state);
23059
23227
  case "tools":
23060
23228
  return !opts.tools?.length || row.toolName !== void 0 && opts.tools.includes(row.toolName);
23061
23229
  // An EMPTY value is a real filter here, not an absent one. The location
@@ -23082,6 +23250,7 @@ var DIMENSIONS = [
23082
23250
  "providers",
23083
23251
  "actions",
23084
23252
  "statuses",
23253
+ "deliveries",
23085
23254
  "tools",
23086
23255
  "repo",
23087
23256
  "file",
@@ -23095,10 +23264,19 @@ function matchesInstanceFilters(row, opts, except) {
23095
23264
  return true;
23096
23265
  }
23097
23266
  function toItems(counts) {
23098
- return [...counts.entries()].map(([value, count]) => ({ value, count })).sort((a, b) => b.count - a.count || a.value.localeCompare(b.value));
23267
+ return [...counts.entries()].map(([value, count]) => ({ value, count })).sort(
23268
+ (a, b) => b.count - a.count || a.value.localeCompare(b.value) || // localeCompare reports canonically-equivalent strings (an NFC and an
23269
+ // NFD spelling of the same text) as equal, so a count tie between
23270
+ // them would otherwise be ordered by whichever the Map iteration
23271
+ // produced. compareCodePoints breaks that tie deterministically, which
23272
+ // makes this a TOTAL order — not one that agrees with SQL collation,
23273
+ // which it need not: foldFacetTuples runs this same sort over grouped
23274
+ // tuples, so both paths order facets identically by construction.
23275
+ compareCodePoints(a.value, b.value)
23276
+ );
23099
23277
  }
23100
- function bump(counts, value) {
23101
- counts.set(value, (counts.get(value) ?? 0) + 1);
23278
+ function bump(counts, value, by = 1) {
23279
+ counts.set(value, (counts.get(value) ?? 0) + by);
23102
23280
  }
23103
23281
  function createInstanceFacetAccumulator(opts) {
23104
23282
  const severity = /* @__PURE__ */ new Map();
@@ -23107,6 +23285,7 @@ function createInstanceFacetAccumulator(opts) {
23107
23285
  const action = /* @__PURE__ */ new Map();
23108
23286
  const status = /* @__PURE__ */ new Map();
23109
23287
  const tool = /* @__PURE__ */ new Map();
23288
+ const deployment = /* @__PURE__ */ new Map();
23110
23289
  return {
23111
23290
  add(row) {
23112
23291
  if (matchesInstanceFilters(row, opts, "severity")) bump(severity, row.severity);
@@ -23121,6 +23300,9 @@ function createInstanceFacetAccumulator(opts) {
23121
23300
  if (row.toolName !== void 0 && matchesInstanceFilters(row, opts, "tools")) {
23122
23301
  bump(tool, row.toolName);
23123
23302
  }
23303
+ if (row.delivery !== void 0 && matchesInstanceFilters(row, opts, "deliveries")) {
23304
+ bump(deployment, row.delivery.state);
23305
+ }
23124
23306
  },
23125
23307
  facets: () => ({
23126
23308
  severity: toItems(severity),
@@ -23128,7 +23310,8 @@ function createInstanceFacetAccumulator(opts) {
23128
23310
  provider: toItems(provider),
23129
23311
  action: toItems(action),
23130
23312
  status: toItems(status),
23131
- tool: toItems(tool)
23313
+ tool: toItems(tool),
23314
+ deployment: toItems(deployment)
23132
23315
  })
23133
23316
  };
23134
23317
  }
@@ -23142,6 +23325,7 @@ function toInstanceDetail(row) {
23142
23325
  ...row.toolName === void 0 ? {} : { toolName: row.toolName },
23143
23326
  eventId: row.eventId,
23144
23327
  ...row.sessionId === void 0 ? {} : { sessionId: row.sessionId },
23328
+ ...row.delivery === void 0 ? {} : { delivery: row.delivery },
23145
23329
  ...row.user === void 0 ? {} : { user: row.user },
23146
23330
  action: toApiAction(row.actionTaken),
23147
23331
  detectedAt: row.occurredAt,
@@ -23156,12 +23340,6 @@ function toInstanceDetail(row) {
23156
23340
  policy: { id: `category:${category}`, name: category }
23157
23341
  };
23158
23342
  }
23159
- var SEVERITY_ORDER2 = {
23160
- critical: 0,
23161
- high: 1,
23162
- medium: 2,
23163
- low: 3
23164
- };
23165
23343
  function newLocationAccumulator() {
23166
23344
  return {
23167
23345
  instanceCount: 0,
@@ -23176,7 +23354,7 @@ function newLocationAccumulator() {
23176
23354
  }
23177
23355
  function addToLocation(acc, row) {
23178
23356
  acc.instanceCount += 1;
23179
- const rank = SEVERITY_ORDER2[row.severity] ?? Number.MAX_SAFE_INTEGER - 1;
23357
+ const rank = severityRank(row.severity) ?? Number.MAX_SAFE_INTEGER - 1;
23180
23358
  if (rank < acc.maxSeverityRank) {
23181
23359
  acc.maxSeverityRank = rank;
23182
23360
  acc.maxSeverity = row.severity;
@@ -23186,15 +23364,15 @@ function addToLocation(acc, row) {
23186
23364
  acc.ruleIds.add(row.ruleId);
23187
23365
  }
23188
23366
  function compareLocationOrder(a, b) {
23189
- const rankA = SEVERITY_ORDER2[a.maxSeverity] ?? -1;
23190
- const rankB = SEVERITY_ORDER2[b.maxSeverity] ?? -1;
23367
+ const rankA = severityRank(a.maxSeverity) ?? -1;
23368
+ const rankB = severityRank(b.maxSeverity) ?? -1;
23191
23369
  if (rankA !== rankB) return rankA - rankB;
23192
23370
  if (a.latestDetectedAt !== b.latestDetectedAt) {
23193
23371
  return a.latestDetectedAt < b.latestDetectedAt ? 1 : -1;
23194
23372
  }
23195
- if (a.repo !== b.repo) return a.repo < b.repo ? -1 : 1;
23196
- if (a.file !== b.file) return a.file < b.file ? -1 : 1;
23197
- return 0;
23373
+ const repoDiff = compareCodePoints(a.repo, b.repo);
23374
+ if (repoDiff !== 0) return repoDiff;
23375
+ return compareCodePoints(a.file, b.file);
23198
23376
  }
23199
23377
  function encodeLocationId(repo, file2) {
23200
23378
  return `${encodePart(repo)}/${encodePart(file2)}`;
@@ -23269,6 +23447,11 @@ var Policy = external_exports.object({
23269
23447
  // test `prohibitedModels` passes and `reversibleRuleIds` fails.
23270
23448
  provenance: PolicyProvenance.optional()
23271
23449
  }).meta({ id: "Policy" });
23450
+ var KNOWN_BUILTIN_IDS = ["monitor", "warn", "redact", "vault", "block"];
23451
+ var BuiltinPolicyId = external_exports.enum(KNOWN_BUILTIN_IDS).meta({ id: "BuiltinPolicyId" });
23452
+ var RedactFallback = BuiltinPolicyId.extract(["monitor", "warn", "block"]).meta({
23453
+ id: "RedactFallback"
23454
+ });
23272
23455
  var PolicyBundle = external_exports.object({
23273
23456
  version: external_exports.string(),
23274
23457
  policies: external_exports.array(Policy),
@@ -23316,6 +23499,16 @@ var PolicyBundle = external_exports.object({
23316
23499
  // control plane), so no name resolution stands between the decision and the
23317
23500
  // comparison.
23318
23501
  prohibitedModels: external_exports.array(external_exports.string()).optional(),
23502
+ // What a resolved `redact` becomes on a field the host cannot rewrite, as
23503
+ // the ORGANIZATION would have it. Merged raise-only against the device's own
23504
+ // `WorkspaceSettings.redactFallback` (see strongerRedactFallback below), so
23505
+ // a control plane can tighten a machine and never loosen one — the same
23506
+ // direction `mergeRaiseOnly` enforces for policies.
23507
+ //
23508
+ // Optional so an older backend, and an older on-disk cache, still parses;
23509
+ // absent leaves the device's own setting in force, which is the behaviour
23510
+ // that predates the field and the safe direction to default.
23511
+ redactFallback: RedactFallback.optional(),
23319
23512
  customKeywords: external_exports.array(external_exports.string()),
23320
23513
  fetchedAt: external_exports.iso.datetime()
23321
23514
  }).meta({ id: "PolicyBundle" });
@@ -23345,11 +23538,6 @@ function severityFloorPolicy(category) {
23345
23538
  const peak = CATEGORY_PEAK_SEVERITY[category];
23346
23539
  return peak === "critical" || peak === "high" ? "warn" : "monitor";
23347
23540
  }
23348
- var KNOWN_BUILTIN_IDS = ["monitor", "warn", "redact", "vault", "block"];
23349
- var BuiltinPolicyId = external_exports.enum(KNOWN_BUILTIN_IDS).meta({ id: "BuiltinPolicyId" });
23350
- var RedactFallback = BuiltinPolicyId.extract(["monitor", "warn", "block"]).meta({
23351
- id: "RedactFallback"
23352
- });
23353
23541
  var BUILTIN_ORDER = KNOWN_BUILTIN_IDS;
23354
23542
  var BUILTIN_POLICY_SPECS = {
23355
23543
  monitor: {
@@ -23405,6 +23593,11 @@ function isActionAtLeast(action, floor) {
23405
23593
  function strongerAction(a, b) {
23406
23594
  return actionRank(a) >= actionRank(b) ? a : b;
23407
23595
  }
23596
+ function strongerRedactFallback(local, remote) {
23597
+ if (remote === void 0) return local;
23598
+ const localAction = builtinPolicyToAction(local);
23599
+ return localAction === strongerAction(localAction, builtinPolicyToAction(remote)) ? local : remote;
23600
+ }
23408
23601
  function weakestBuiltinAtLeast(floor) {
23409
23602
  return KNOWN_BUILTIN_IDS.find((id) => isActionAtLeast(builtinPolicyToAction(id), floor)) ?? "block";
23410
23603
  }
@@ -23652,7 +23845,7 @@ function isVaultConsentValid(consent) {
23652
23845
  }
23653
23846
 
23654
23847
  // ../../packages/schema/src/zod/local.ts
23655
- var WORKSPACE_SETTINGS_SPEC_VERSION = 7;
23848
+ var WORKSPACE_SETTINGS_SPEC_VERSION = 8;
23656
23849
  var MODEL_JUDGE_PAYLOAD_VERSION = 1;
23657
23850
  var RunMode = external_exports.enum(["standalone", "attached"]);
23658
23851
  var ControlPlaneConnection = external_exports.object({
@@ -23672,6 +23865,15 @@ var HistorySyncConsent = external_exports.object({
23672
23865
  payloadVersion: external_exports.number().int().positive(),
23673
23866
  endpoint: external_exports.string()
23674
23867
  });
23868
+ var BODY_RETENTION_DEFAULT_DAYS = 30;
23869
+ var BodyRetention = external_exports.object({
23870
+ enabled: external_exports.boolean().default(false),
23871
+ // Never 0, and the ceiling is a fat-finger guard rather than a policy
23872
+ // limit — `enabled` is the real gate. A low value cannot reach a row the
23873
+ // sync ledger still owes: the sweep's age filter only ever NARROWS a
23874
+ // candidate set that is already bounded by "delivered, or never owed".
23875
+ retainDays: external_exports.number().int().min(1).max(3650).default(BODY_RETENTION_DEFAULT_DAYS)
23876
+ }).meta({ id: "BodyRetention" });
23675
23877
  var WorkspaceSettings = external_exports.object({
23676
23878
  specVersion: external_exports.number().int().positive().default(WORKSPACE_SETTINGS_SPEC_VERSION),
23677
23879
  runMode: RunMode.default("standalone"),
@@ -23720,7 +23922,13 @@ var WorkspaceSettings = external_exports.object({
23720
23922
  // carry prompt/reply/tool-output text in `content`; the key name predates
23721
23923
  // both widenings. Absent until granted, and a grant for a different endpoint
23722
23924
  // or an older payload no longer counts.
23723
- historySyncConsent: HistorySyncConsent.optional()
23925
+ historySyncConsent: HistorySyncConsent.optional(),
23926
+ // Local body expiry (see BodyRetention). Off until switched on; expiring a
23927
+ // body never removes the row or its findings.
23928
+ bodyRetention: BodyRetention.default({
23929
+ enabled: false,
23930
+ retainDays: BODY_RETENTION_DEFAULT_DAYS
23931
+ })
23724
23932
  });
23725
23933
  function defaultWorkspaceSettings() {
23726
23934
  return WorkspaceSettings.parse({});
@@ -23815,12 +24023,15 @@ function toCaptureAttributes(event) {
23815
24023
  ...metadata?.traceId !== void 0 ? { trace_id: metadata.traceId } : {},
23816
24024
  ...metadata?.exceptionIds !== void 0 ? { exception_ids: metadata.exceptionIds } : {},
23817
24025
  ...metadata?.inspectionMs !== void 0 ? { inspection_ms: metadata.inspectionMs } : {},
24026
+ ...metadata?.redactDegradedTo !== void 0 ? { redact_degraded_to: metadata.redactDegradedTo } : {},
23818
24027
  // `model`/`turnIndex` have no dedicated CaptureAttributes field (no writer
23819
24028
  // has ever populated either), but every legacy metadata key still rides
23820
24029
  // the bag rather than being silently dropped — CaptureAttributes'
23821
24030
  // `.catchall(z.unknown())` carries the long tail.
23822
24031
  ...metadata?.model !== void 0 ? { model: metadata.model } : {},
23823
- ...metadata?.turnIndex !== void 0 ? { turn_index: metadata.turnIndex } : {}
24032
+ ...metadata?.turnIndex !== void 0 ? { turn_index: metadata.turnIndex } : {},
24033
+ ...metadata?.messageId !== void 0 ? { message_id: metadata.messageId } : {},
24034
+ ...metadata?.conversationId !== void 0 ? { conversation_id: metadata.conversationId } : {}
23824
24035
  };
23825
24036
  }
23826
24037
  function captureDefinitionVersion(finding) {
@@ -23848,13 +24059,22 @@ var ManagedSettingKey = external_exports.enum([
23848
24059
  "vaultInlineReveal",
23849
24060
  "modelJudgeConsent",
23850
24061
  "dataSharesInPlace",
23851
- "redactFallback"
24062
+ "redactFallback",
24063
+ // Pins the toggle and the day count together — see BodyRetention on why the
24064
+ // two are one unit. An administrator mandating a window wants the count
24065
+ // enforced with it, not one a user can widen while the toggle stays on.
24066
+ "bodyRetention"
23852
24067
  ]).meta({ id: "ManagedSettingKey" });
23853
24068
  function isManagedSettingKey(value) {
23854
24069
  return ManagedSettingKey.safeParse(value).success;
23855
24070
  }
23856
24071
  var ManagedSettingsValues = external_exports.object({
23857
24072
  runMode: external_exports.enum(["standalone", "attached"]).optional(),
24073
+ // `controlPlane` and `bodyRetention` are the two nested values, and both are
24074
+ // plain, non-strict objects: a key under either that this build does not know
24075
+ // is stripped and nothing reports it. The unknown-value split in
24076
+ // ManagedSettings below classifies top-level names only, so it stops at
24077
+ // these boundaries.
23858
24078
  controlPlane: external_exports.object({
23859
24079
  endpoint: external_exports.string().min(1),
23860
24080
  label: external_exports.string().min(1).optional()
@@ -23865,7 +24085,8 @@ var ManagedSettingsValues = external_exports.object({
23865
24085
  vaultInlineReveal: external_exports.enum(["masked", "full", "off"]).optional(),
23866
24086
  modelJudgeConsent: external_exports.boolean().optional(),
23867
24087
  dataSharesInPlace: external_exports.boolean().optional(),
23868
- redactFallback: RedactFallback.optional()
24088
+ redactFallback: RedactFallback.optional(),
24089
+ bodyRetention: BodyRetention.optional()
23869
24090
  }).meta({ id: "ManagedSettingsValues" });
23870
24091
  var ManagedSettings = external_exports.object({
23871
24092
  specVersion: external_exports.number().int().positive().default(MANAGED_SETTINGS_SPEC_VERSION),
@@ -23873,7 +24094,21 @@ var ManagedSettings = external_exports.object({
23873
24094
  // decision from a bug. Absent renders as a generic "your organization".
23874
24095
  organization: external_exports.string().min(1).optional(),
23875
24096
  // What the administrator pinned.
23876
- values: ManagedSettingsValues.default({}),
24097
+ //
24098
+ // Parsed as a RECORD rather than as the nested schema, and split below for
24099
+ // the same reason `lockedFields` is parsed as names: a plain `z.object`
24100
+ // drops an unrecognised key and succeeds, so a pin this build does not know
24101
+ // vanished and nothing anywhere said so. A pin with no lock is a supported
24102
+ // shape — it is a DEFAULT the user may still change — so that silence hit
24103
+ // exactly the file an administrator is most likely to write while a fleet
24104
+ // is mid-upgrade.
24105
+ //
24106
+ // Splitting here rather than calling `.strict()`: strict would REFUSE the
24107
+ // file, which is the outcome the lock half already rejected — an older
24108
+ // build then runs entirely unmanaged, every pin and lock gone. A bad KNOWN
24109
+ // value still fails, because the nested schema is re-run over the known
24110
+ // subset and its issues are re-raised on this parse.
24111
+ values: external_exports.record(external_exports.string(), external_exports.unknown()).default({}),
23877
24112
  // Which of those the user may not change. A key here with no matching value
23878
24113
  // freezes whatever the user last chose; a value with no lock is a DEFAULT
23879
24114
  // the user may still override. The two are separable on purpose.
@@ -23886,17 +24121,31 @@ var ManagedSettings = external_exports.object({
23886
24121
  // the fleets most likely to carry a version skew. A name outside the enum
23887
24122
  // is still never HONOURED: the lockable set stays explicit above.
23888
24123
  lockedFields: external_exports.array(external_exports.string()).default([])
23889
- }).transform(({ lockedFields, ...rest }) => {
24124
+ }).transform(({ lockedFields, values, ...rest }, ctx) => {
23890
24125
  const known = [];
23891
24126
  const unknown2 = [];
23892
24127
  for (const name of lockedFields) {
23893
24128
  if (isManagedSettingKey(name)) known.push(name);
23894
24129
  else unknown2.push(name);
23895
24130
  }
24131
+ const knownValues = /* @__PURE__ */ Object.create(null);
24132
+ const unknownValues = [];
24133
+ for (const [name, value] of Object.entries(values)) {
24134
+ if (Object.hasOwn(ManagedSettingsValues.shape, name)) knownValues[name] = value;
24135
+ else unknownValues.push(name);
24136
+ }
24137
+ const pinned = ManagedSettingsValues.safeParse(knownValues);
24138
+ if (!pinned.success) {
24139
+ for (const issue2 of pinned.error.issues)
24140
+ ctx.addIssue({ ...issue2, path: ["values", ...issue2.path] });
24141
+ return external_exports.NEVER;
24142
+ }
23896
24143
  return {
23897
24144
  ...rest,
24145
+ values: pinned.data,
23898
24146
  lockedFields: known,
23899
- ...unknown2.length > 0 ? { unknownLockedFields: unknown2 } : {}
24147
+ ...unknown2.length > 0 ? { unknownLockedFields: unknown2 } : {},
24148
+ ...unknownValues.length > 0 ? { unknownValueFields: unknownValues } : {}
23900
24149
  };
23901
24150
  }).meta({ id: "ManagedSettings" });
23902
24151
 
@@ -24160,7 +24409,23 @@ var SaveSettingsInput = external_exports.object({
24160
24409
  modelJudgeConsent: ModelJudgeConsentChoice,
24161
24410
  historySyncConsent: HistorySyncConsentChoice,
24162
24411
  vaultConsent: external_exports.string(),
24163
- vaultInlineReveal: external_exports.string()
24412
+ vaultInlineReveal: external_exports.string(),
24413
+ // Widened to `string` like its neighbours rather than typed as
24414
+ // `RedactFallback`, on this module's own layering rule: shape here, VALUE at
24415
+ // the call site, so the domain check receives the type it was written for.
24416
+ //
24417
+ // NOT because a narrower schema would reject differently. `parseActionInput`
24418
+ // is a `safeParse` wrapper and throws for no field schema, so either spelling
24419
+ // reaches a recoverable `{ ok: false }` and there is no rejected promise to
24420
+ // trade against. The real cost runs the other way and is the part worth
24421
+ // knowing: a value this schema admits and the domain enum then rejects lands
24422
+ // on the action's shared refusal, which names NO field, where a shape
24423
+ // rejection reaches `malformedInput` and names the schema key.
24424
+ redactFallback: external_exports.string(),
24425
+ // Shape only, the way the enum fields above are strings only: the RANGE is
24426
+ // `BodyRetention`'s and the action checks it there, so there is one place
24427
+ // that decides what a legal horizon is rather than two that can drift.
24428
+ bodyRetention: external_exports.object({ enabled: external_exports.boolean(), retainDays: external_exports.number() })
24164
24429
  });
24165
24430
  var AttachInput = external_exports.object({
24166
24431
  endpoint: external_exports.string(),
@@ -24332,6 +24597,52 @@ function reviewSeverityRank(reasons) {
24332
24597
  return Math.min(...reasons.map((r) => REVIEW_SEVERITY_RANK[r]));
24333
24598
  }
24334
24599
 
24600
+ // ../../packages/schema/src/zod/web-capture.ts
24601
+ var WebUsageSource = external_exports.enum(["site", "estimated", "none"]);
24602
+ var WebUsage = external_exports.object({
24603
+ inputTokens: external_exports.number().int().nonnegative().optional(),
24604
+ outputTokens: external_exports.number().int().nonnegative().optional(),
24605
+ cacheReadInputTokens: external_exports.number().int().nonnegative().optional(),
24606
+ cacheCreationInputTokens: external_exports.number().int().nonnegative().optional()
24607
+ });
24608
+ var WebToolCall = external_exports.object({
24609
+ toolUseId: external_exports.string().min(1),
24610
+ toolName: external_exports.string().min(1),
24611
+ target: external_exports.string().optional(),
24612
+ isError: external_exports.boolean().optional(),
24613
+ inputSize: external_exports.number().int().nonnegative().optional(),
24614
+ outputSize: external_exports.number().int().nonnegative().optional()
24615
+ });
24616
+ var WebExchange = external_exports.object({
24617
+ messageId: external_exports.string().min(1),
24618
+ startedAt: external_exports.iso.datetime(),
24619
+ model: external_exports.string().optional(),
24620
+ usage: WebUsage.optional(),
24621
+ usageSource: WebUsageSource,
24622
+ stopReason: external_exports.string().optional(),
24623
+ conversationId: external_exports.string().optional(),
24624
+ turnIndex: external_exports.number().int().nonnegative().optional(),
24625
+ toolCalls: external_exports.array(WebToolCall).default([]),
24626
+ // Absent when the adapter recovered no text. Capped by the caller at
24627
+ // RESPONSE_TEXT_MAX_BYTES; `truncated` records that the cap was reached, so a
24628
+ // short capture is never mistaken for a short reply.
24629
+ responseText: external_exports.string().optional(),
24630
+ truncated: external_exports.boolean().default(false)
24631
+ });
24632
+ var RESPONSE_TEXT_MAX_BYTES = 2 * 1024 * 1024;
24633
+ var WebCaptureStatus = external_exports.object({
24634
+ patched: external_exports.boolean(),
24635
+ live: external_exports.boolean(),
24636
+ blind: external_exports.boolean(),
24637
+ sendsSeenDom: external_exports.number().int().nonnegative(),
24638
+ exchangesSeenNet: external_exports.number().int().nonnegative(),
24639
+ parseFailures: external_exports.number().int().nonnegative(),
24640
+ unparsedBodies: external_exports.number().int().nonnegative(),
24641
+ // The adapter-declared JSON key paths that were absent from a real payload —
24642
+ // the earliest signal that a site's contract moved.
24643
+ shapeMisses: external_exports.array(external_exports.string()).default([])
24644
+ });
24645
+
24335
24646
  // ../../packages/persistence/src/paths.ts
24336
24647
  import {
24337
24648
  chmodSync,
@@ -24692,6 +25003,22 @@ function discardStore(file2, backup) {
24692
25003
  }
24693
25004
  }
24694
25005
 
25006
+ // ../../packages/persistence/src/internal/sql-functions.ts
25007
+ var utf8 = new TextDecoder();
25008
+ function akaLower(value) {
25009
+ if (value === null) return null;
25010
+ if (typeof value === "string") return value.toLowerCase();
25011
+ if (typeof value === "number" || typeof value === "bigint") return String(value).toLowerCase();
25012
+ return utf8.decode(value).toLowerCase();
25013
+ }
25014
+ function registerSqlFunctions(db) {
25015
+ db.function(
25016
+ "aka_lower",
25017
+ { deterministic: true, directOnly: true, useBigIntArguments: true },
25018
+ akaLower
25019
+ );
25020
+ }
25021
+
24695
25022
  // ../../packages/persistence/src/internal/sql-text.ts
24696
25023
  function escapeLikePattern(s) {
24697
25024
  return s.replace(/\\/g, "\\\\").replace(/%/g, "\\%").replace(/_/g, "\\_");
@@ -24776,6 +25103,11 @@ function schemaObjectExists(db, kind, name) {
24776
25103
  function indexExists(db, name) {
24777
25104
  return schemaObjectExists(db, "index", name);
24778
25105
  }
25106
+ function indexColumns(db, name) {
25107
+ if (!indexExists(db, name)) return [];
25108
+ const columns = db.prepare(`PRAGMA index_info(${name})`).all();
25109
+ return columns.map((c) => c.name).filter((c) => c !== null);
25110
+ }
24779
25111
  function columnNames(db, table2, opts) {
24780
25112
  const pragma = opts?.includeGenerated ? "table_xinfo" : "table_info";
24781
25113
  const columns = db.prepare(`PRAGMA ${pragma}(${table2})`).all();
@@ -24837,176 +25169,818 @@ function mapRowsTolerant(rows, map2) {
24837
25169
  return out;
24838
25170
  }
24839
25171
 
24840
- // ../../packages/persistence/src/migrations.ts
24841
- function describeObject(object2) {
24842
- return object2.kind === "column" ? `column ${object2.table}.${object2.name}` : `table ${object2.name}`;
24843
- }
24844
- function splitStatements(sql) {
24845
- return sql.split(/-->\s*statement-breakpoint/).map((s) => s.trim()).filter((s) => s.length > 0);
24846
- }
24847
- function createdIndexName(statement) {
24848
- const body = statement.replace(/^(?:\s*--[^\n]*\n?)+/, "").trimStart();
24849
- return /^CREATE (?:UNIQUE )?INDEX (?:IF NOT EXISTS )?`([^`]+)`/.exec(body)?.[1];
25172
+ // ../../packages/persistence/src/internal/outbox-lane.ts
25173
+ var OUTBOX_CAPTURE_EVENT_TYPES = ["prompt", "response", "tool_use"];
25174
+ var OUTBOX_CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25175
+
25176
+ // ../../packages/persistence/src/sync-failure.ts
25177
+ var SYNC_FAILURE_REASONS = SyncFailureReason.options;
25178
+ function syncFailureRejectCondition(column = "sync_failure") {
25179
+ const members2 = SYNC_FAILURE_REASONS.map((r) => `'${r}'`).join(", ");
25180
+ return `NEW.${column} IS NOT NULL AND NEW.${column} NOT IN (${members2})`;
24850
25181
  }
24851
- var LEGACY_DROP_MIGRATION_TAG = "0014_drop_legacy_events_findings";
24852
- function applyMigrations(db, file2) {
24853
- const legacyCount = db.prepare("PRAGMA user_version").get().user_version;
24854
- db.exec(
24855
- "CREATE TABLE IF NOT EXISTS migration_ledger (tag TEXT PRIMARY KEY, applied_at INTEGER NOT NULL)"
24856
- );
24857
- const applied = new Set(
24858
- db.prepare("SELECT tag FROM migration_ledger").all().map((r) => r.tag)
24859
- );
24860
- const preLedgerStore = applied.size === 0 && legacyCount > 0;
24861
- const record2 = db.prepare(
24862
- "INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)"
24863
- );
24864
- for (const [index, migration] of SQLITE_MIGRATIONS.entries()) {
24865
- if (applied.has(migration.tag)) continue;
24866
- if (migration.tag === LEGACY_DROP_MIGRATION_TAG) continue;
24867
- const evidence = evidenceObjects(migration.sql);
24868
- const present2 = evidence.filter((o) => evidenceExists(db, o));
24869
- if (present2.length > 0 && present2.length < evidence.length) {
24870
- const missing = evidence.filter((o) => !present2.includes(o));
24871
- const message = `sqlite migration ${migration.tag} has no ledger row, but the store already has ${present2.map(describeObject).join(", ")} while missing ${missing.map(describeObject).join(", ")} \u2014 the schema diverged from the migration history; refusing to replay or skip.`;
24872
- akaWarn(message);
24873
- throw new Error(`[aka] ${message}`);
24874
- }
24875
- const alreadyApplied = evidence.length > 0 ? present2.length === evidence.length : preLedgerStore && index < legacyCount;
24876
- const wantsFkOff = /PRAGMA foreign_keys\s*=\s*OFF/i.test(migration.sql);
24877
- const statements = splitStatements(migration.sql);
24878
- if (wantsFkOff) db.exec("PRAGMA foreign_keys = OFF");
24879
- try {
24880
- withTransaction(
24881
- db,
24882
- () => {
24883
- for (const statement of statements) {
24884
- const indexName = createdIndexName(statement);
24885
- if (indexName === void 0) {
24886
- if (alreadyApplied) continue;
24887
- } else if (indexExists(db, indexName)) {
24888
- continue;
24889
- }
24890
- db.exec(statement);
24891
- }
24892
- if (wantsFkOff && !alreadyApplied) {
24893
- const violations = db.prepare("PRAGMA foreign_key_check").all();
24894
- if (violations.length > 0) {
24895
- throw new Error(
24896
- `[aka] sqlite migration ${migration.tag} left ${String(violations.length)} foreign-key violation(s); rolling back.`
24897
- );
24898
- }
24899
- }
24900
- record2.run(migration.tag, Date.now());
24901
- },
24902
- "IMMEDIATE"
24903
- );
24904
- } finally {
24905
- if (wantsFkOff) db.exec("PRAGMA foreign_keys = ON");
24906
- }
25182
+
25183
+ // ../../packages/persistence/src/repositories/history-sync.ts
25184
+ var STRUCTURAL_EVENT_TYPES = ["session", "llm_call", "tool_call"];
25185
+ var TYPE_LIST = STRUCTURAL_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25186
+ var CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_TYPE_LIST;
25187
+ var COUNTED_EVENT_TYPES = [
25188
+ ...STRUCTURAL_EVENT_TYPES,
25189
+ ...OUTBOX_CAPTURE_EVENT_TYPES
25190
+ ];
25191
+ var COUNTED_TYPE_LIST = COUNTED_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25192
+ var PARTITION_BUCKETS = `
25193
+ SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NULL THEN 1 ELSE 0 END) AS queued,
25194
+ SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NOT NULL THEN 1 ELSE 0 END) AS inProgress,
25195
+ SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS synced,
25196
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25197
+ AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
25198
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25199
+ AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached,
25200
+ -- Spelled as what it INCLUDES rather than what it excludes, so a reason
25201
+ -- added later lands in no bucket and fails the sum assertion, instead
25202
+ -- of silently joining this one.
25203
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25204
+ AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
25205
+ THEN 1 ELSE 0 END) AS failed,
25206
+ COUNT(*) AS total`;
25207
+ var COUNTED_SCOPE = `
25208
+ WHERE event_type IN (${COUNTED_TYPE_LIST})
25209
+ AND (
25210
+ event_type IN (${TYPE_LIST})
25211
+ OR synced_at IS NOT NULL
25212
+ OR outbox_owed = 1
25213
+ )`;
25214
+ var SKIPPED = -1;
25215
+ var ROW_COLUMNS = `id,
25216
+ parent_id AS parentId,
25217
+ root_session_id AS rootSessionId,
25218
+ event_type AS eventType,
25219
+ host_id AS hostId,
25220
+ harness_id AS harnessId,
25221
+ source_project_id AS sourceProjectId,
25222
+ started_at AS startedAt,
25223
+ ended_at AS endedAt,
25224
+ severity,
25225
+ priority,
25226
+ content,
25227
+ content_hash AS contentHash,
25228
+ attributes`;
25229
+ var SqliteHistorySyncRepository = class {
25230
+ constructor(db) {
25231
+ this.db = db;
25232
+ this.ensureRowStmt = db.prepare(`INSERT OR IGNORE INTO history_sync (id) VALUES (1)`);
25233
+ this.sessionsStmt = db.prepare(
25234
+ `SELECT COALESCE(root_session_id, id) AS sessionId, MIN(started_at) AS earliest
25235
+ FROM audit_events
25236
+ WHERE synced_at IS NULL
25237
+ AND event_type IN (${TYPE_LIST})
25238
+ AND started_at < :before
25239
+ GROUP BY sessionId
25240
+ ORDER BY earliest
25241
+ LIMIT :limit`
25242
+ );
25243
+ this.rowsStmt = db.prepare(
25244
+ `SELECT ${ROW_COLUMNS}
25245
+ FROM audit_events
25246
+ WHERE synced_at IS NULL
25247
+ AND event_type IN (${TYPE_LIST})
25248
+ AND started_at < :before
25249
+ AND COALESCE(root_session_id, id) = :sessionId
25250
+ ORDER BY (event_type = 'session') DESC, started_at
25251
+ LIMIT :limit`
25252
+ );
25253
+ this.captureRowsStmt = db.prepare(
25254
+ `SELECT ${ROW_COLUMNS}
25255
+ FROM audit_events
25256
+ WHERE synced_at IS NULL
25257
+ AND sync_claimed_at IS NULL
25258
+ AND outbox_owed = 1
25259
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25260
+ AND started_at < :before
25261
+ ORDER BY started_at
25262
+ LIMIT :limit`
25263
+ );
25264
+ this.markOwedStmt = db.prepare(
25265
+ `UPDATE audit_events SET outbox_owed = 1 WHERE id = :id AND synced_at IS NULL`
25266
+ );
25267
+ this.markCaptureBacklogOwedStmt = db.prepare(
25268
+ `UPDATE audit_events SET outbox_owed = 1
25269
+ WHERE synced_at IS NULL
25270
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25271
+ AND started_at < :before`
25272
+ );
25273
+ this.stampStmt = db.prepare(
25274
+ `UPDATE audit_events
25275
+ SET synced_at = :at,
25276
+ sync_claimed_at = NULL,
25277
+ sync_failed_at = :failedAt,
25278
+ sync_failure = :failure
25279
+ WHERE id = :id`
25280
+ );
25281
+ this.claimRowStmt = db.prepare(
25282
+ `UPDATE audit_events SET sync_claimed_at = :at WHERE id = :id AND synced_at IS NULL`
25283
+ );
25284
+ this.releaseRowStmt = db.prepare(
25285
+ `UPDATE audit_events SET sync_claimed_at = NULL WHERE id = :id`
25286
+ );
25287
+ this.releaseStaleClaimsStmt = db.prepare(
25288
+ `UPDATE audit_events SET sync_claimed_at = NULL
25289
+ WHERE sync_claimed_at IS NOT NULL AND sync_claimed_at < :staleBefore`
25290
+ );
25291
+ this.partitionStmt = db.prepare(`SELECT${PARTITION_BUCKETS}
25292
+ FROM audit_events${COUNTED_SCOPE}`);
25293
+ this.partitionByKindStmt = db.prepare(
25294
+ `SELECT event_type AS kind,${PARTITION_BUCKETS}
25295
+ FROM audit_events INDEXED BY idx_audit_events_sync${COUNTED_SCOPE}
25296
+ GROUP BY event_type`
25297
+ );
25298
+ this.countsStmt = db.prepare(
25299
+ `SELECT
25300
+ SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
25301
+ SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
25302
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25303
+ AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
25304
+ THEN 1 ELSE 0 END) AS skipped,
25305
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25306
+ AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
25307
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25308
+ AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached
25309
+ FROM audit_events
25310
+ WHERE event_type IN (${TYPE_LIST})`
25311
+ );
25312
+ this.captureSkipCountStmt = db.prepare(
25313
+ // EVERY sentinel capture, whatever the reason — deliberately NOT split the
25314
+ // way the structural totals are. The split exists because a refusal is
25315
+ // terminal only against the deployment that gave it, and the structural
25316
+ // re-arm frees it on a change of deployment. The capture lane has no such
25317
+ // escape: re-arming a capture would offer one deployment's undelivered
25318
+ // prompts, with their text, to a deployment that never saw them, which is
25319
+ // exactly what disownCapturesStmt exists to prevent. So on this lane both
25320
+ // reasons mean the same thing — this row will not be sent — and splitting
25321
+ // them would put refused captures in a bucket nothing reads and nothing
25322
+ // frees.
25323
+ `SELECT COUNT(*) AS skipped
25324
+ FROM audit_events
25325
+ WHERE synced_at = ${String(SKIPPED)}
25326
+ AND event_type IN (${CAPTURE_TYPE_LIST})`
25327
+ );
25328
+ this.fingerprintStmt = db.prepare(
25329
+ `SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
25330
+ FROM history_sync WHERE id = 1`
25331
+ );
25332
+ this.setFingerprintStmt = db.prepare(
25333
+ `UPDATE history_sync
25334
+ SET endpoint_fingerprint = :fingerprint, backlog_before = :backlogBefore
25335
+ WHERE id = 1`
25336
+ );
25337
+ this.disownCapturesStmt = db.prepare(
25338
+ `UPDATE audit_events SET outbox_owed = NULL
25339
+ WHERE outbox_owed IS NOT NULL
25340
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25341
+ AND started_at < :attachedAt`
25342
+ );
25343
+ this.rearmStmt = db.prepare(
25344
+ `UPDATE audit_events
25345
+ SET synced_at = NULL, sync_failed_at = NULL, sync_failure = NULL
25346
+ WHERE (synced_at > 0
25347
+ OR sync_failure IN ('deployment_refused', 'detached_undelivered'))
25348
+ AND event_type IN (${TYPE_LIST})`
25349
+ );
25350
+ this.claimStmt = db.prepare(
25351
+ `UPDATE history_sync
25352
+ SET owner_pid = :pid, owner_host = :host, acquired_at = :now, heartbeat_at = :now
25353
+ WHERE id = 1
25354
+ AND (owner_pid IS NULL
25355
+ OR heartbeat_at IS NULL
25356
+ OR heartbeat_at < :staleBefore
25357
+ OR heartbeat_at > :now)`
25358
+ );
25359
+ this.heartbeatStmt = db.prepare(
25360
+ `UPDATE history_sync SET heartbeat_at = :now WHERE id = 1 AND owner_pid = :pid`
25361
+ );
25362
+ this.releaseStmt = db.prepare(
25363
+ `UPDATE history_sync
25364
+ SET owner_pid = NULL, owner_host = NULL, acquired_at = NULL, heartbeat_at = NULL
25365
+ WHERE id = 1 AND owner_pid = :pid`
25366
+ );
25367
+ this.closeWindowStmt = db.prepare(
25368
+ `UPDATE audit_events
25369
+ SET synced_at = ${String(SKIPPED)},
25370
+ sync_failed_at = :at,
25371
+ sync_failure = 'detached_undelivered'
25372
+ WHERE synced_at IS NULL
25373
+ AND event_type IN (${TYPE_LIST})
25374
+ AND started_at >= :attachedAt`
25375
+ );
25376
+ this.releaseBoundaryStmt = db.prepare(
25377
+ `UPDATE history_sync SET backlog_before = NULL WHERE id = 1`
25378
+ );
25379
+ this.freezeBoundaryStmt = db.prepare(
25380
+ `UPDATE history_sync SET backlog_before = :backlogBefore WHERE id = 1`
25381
+ );
25382
+ this.leaseStmt = db.prepare(
25383
+ `SELECT owner_pid AS ownerPid, owner_host AS ownerHost,
25384
+ acquired_at AS acquiredAt, heartbeat_at AS heartbeatAt
25385
+ FROM history_sync WHERE id = 1`
25386
+ );
25387
+ this.inspectionsStmt = db.prepare(
25388
+ `SELECT d.rule_id AS ruleId,
25389
+ d.name AS ruleName,
25390
+ d.version AS ruleVersion,
25391
+ d.category AS category,
25392
+ d.severity AS severity,
25393
+ f.span_start AS spanStart,
25394
+ f.span_end AS spanEnd,
25395
+ f.masked_match AS maskedMatch,
25396
+ f.action_taken AS actionTaken,
25397
+ f.confidence AS confidence
25398
+ FROM inspection_findings f
25399
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
25400
+ WHERE f.audit_event_id = :auditEventId
25401
+ ORDER BY f.span_start, f.id`
25402
+ );
24907
25403
  }
24908
- if (legacyCount < SQLITE_MIGRATIONS.length) {
24909
- db.exec(`PRAGMA user_version = ${String(SQLITE_MIGRATIONS.length)}`);
25404
+ db;
25405
+ ensureRowStmt;
25406
+ sessionsStmt;
25407
+ rowsStmt;
25408
+ stampStmt;
25409
+ countsStmt;
25410
+ fingerprintStmt;
25411
+ setFingerprintStmt;
25412
+ rearmStmt;
25413
+ claimStmt;
25414
+ heartbeatStmt;
25415
+ releaseStmt;
25416
+ leaseStmt;
25417
+ inspectionsStmt;
25418
+ closeWindowStmt;
25419
+ releaseBoundaryStmt;
25420
+ freezeBoundaryStmt;
25421
+ captureRowsStmt;
25422
+ markOwedStmt;
25423
+ markCaptureBacklogOwedStmt;
25424
+ captureSkipCountStmt;
25425
+ disownCapturesStmt;
25426
+ partitionStmt;
25427
+ partitionByKindStmt;
25428
+ claimRowStmt;
25429
+ releaseRowStmt;
25430
+ releaseStaleClaimsStmt;
25431
+ /**
25432
+ * The masked detections recorded against one tool call.
25433
+ *
25434
+ * These travel with the event because a tool call's target is not
25435
+ * re-inspectable from the event alone — unlike a capture, where the text
25436
+ * itself is re-scannable. What crosses is the masked match and the rule that
25437
+ * produced it, never the value.
25438
+ */
25439
+ inspectionsFor(auditEventId) {
25440
+ return allRows(this.inspectionsStmt, { auditEventId });
24910
25441
  }
24911
- ensureSyncedAtColumn(db, "audit_events");
24912
- ensureScanLedgerTable(db);
24913
- ensureHistorySyncTable(db);
24914
- ensureBlockedDetectionsTable(db);
24915
- ensureRuleProbeCacheTable(db);
24916
- ensureWriteGateTrigger(db);
24917
- ensureTokenUsageColumns(db);
24918
- reconcileSourceProjectIds(db);
24919
- if (!applied.has(LEGACY_DROP_MIGRATION_TAG)) {
24920
- const drained = runLegacyHistoryBackfill(db);
24921
- if (drained) applyLegacyDropMigration(db, file2);
25442
+ /**
25443
+ * Sessions with structural rows still to send, oldest first.
25444
+ *
25445
+ * BOUNDED BY THE BACKLOG BOUNDARY, which is the whole correctness of this
25446
+ * read. Anything recorded after the machine attached is the live forward
25447
+ * path's to deliver; this drain exists for what was recorded before it, and a
25448
+ * row both paths send is at best a duplicate request and at worst — for a
25449
+ * session root — an overwrite of the inventory ids the live path resolved.
25450
+ */
25451
+ pendingSessions(limit, before) {
25452
+ return allRows(this.sessionsStmt, { limit, before }).map(
25453
+ (r) => r.sessionId
25454
+ );
24922
25455
  }
24923
- }
24924
- function readLegacyTables(db) {
24925
- let holdsRows = false;
24926
- const marks = [];
24927
- for (const table2 of ["events", "findings"]) {
24928
- try {
24929
- const row = db.prepare(`SELECT count(*) AS n, ifnull(max(rowid), -1) AS hi FROM ${table2}`).get();
24930
- if (row === void 0) {
24931
- holdsRows = true;
24932
- marks.push(`${table2}:unreadable`);
24933
- continue;
24934
- }
24935
- if (row.n > 0) holdsRows = true;
24936
- marks.push(`${table2}:${String(row.n)}:${String(row.hi)}`);
24937
- } catch {
24938
- holdsRows = true;
24939
- marks.push(`${table2}:unreadable`);
24940
- }
25456
+ /** One session's undelivered structural rows within the backlog, root first. */
25457
+ pendingRows(sessionId, limit, before) {
25458
+ return allRows(this.rowsStmt, { sessionId, limit, before });
24941
25459
  }
24942
- return { holdsRows, mark: marks.join("|") };
24943
- }
24944
- function applyLegacyDropMigration(db, file2) {
24945
- const migration = SQLITE_MIGRATIONS.find((m) => m.tag === LEGACY_DROP_MIGRATION_TAG);
24946
- if (!migration) return;
24947
- const before = file2 === void 0 ? void 0 : readLegacyTables(db);
24948
- if (file2 !== void 0 && before?.holdsRows === true) {
24949
- try {
24950
- backupBeforeLegacyDrop(db, file2);
24951
- } catch (error61) {
24952
- akaWarn(`legacy events/findings backup failed; deferring the drop: ${String(error61)}`);
24953
- return;
24954
- }
25460
+ /**
25461
+ * Captures this machine still owes the deployment, oldest first.
25462
+ *
25463
+ * Selected by the `outbox_owed` marker the attached forward path writes, not
25464
+ * by a time window — see captureRowsStmt for why a window could not express
25465
+ * this. `before` is the grace window that leaves a just-recorded capture to
25466
+ * the live path.
25467
+ */
25468
+ pendingCaptureRows(limit, before) {
25469
+ return allRows(this.captureRowsStmt, { limit, before });
24955
25470
  }
24956
- try {
25471
+ /**
25472
+ * Record that a capture is OWED to the deployment.
25473
+ *
25474
+ * Written by the attached forward path when a live send did not confirm
25475
+ * delivery, and read by the drain as the whole of its eligibility test. It is
25476
+ * a fact rather than an inference: the machine was attached, the send did not
25477
+ * land, so the row is owed — which no time window can state, because the same
25478
+ * window that holds the rows a past attachment left owed also holds every
25479
+ * capture recorded while the machine was DETACHED, and those were never
25480
+ * offered to anyone.
25481
+ *
25482
+ * Idempotent, and never un-set: `markSynced` settling the row is what takes it
25483
+ * out of the drain's read.
25484
+ */
25485
+ markCaptureOwed(id) {
25486
+ this.markOwedStmt.run({ id });
25487
+ }
25488
+ /**
25489
+ * Mark every capture already on disk as owed, as of `before`.
25490
+ *
25491
+ * The consent-time backfill, called once from `aka attach` when a human
25492
+ * grants existing-history consent — never from an ongoing drain pass, and
25493
+ * never inferred from a boundary that could later move. `before` is the
25494
+ * caller's own "now" at the moment consent was granted, so what this marks
25495
+ * is exactly the backlog the consent prompt already counted, not whatever a
25496
+ * later re-attach or key rotation might widen it to.
25497
+ *
25498
+ * Returns how many rows matched, for the caller to log or test against. Not a
25499
+ * count of NEWLY marked rows — a row still unsynced from an earlier call
25500
+ * matches again and is counted again, the same as `UPDATE`'s own `changes`.
25501
+ */
25502
+ markCaptureBacklogOwed(before) {
25503
+ return Number(this.markCaptureBacklogOwedStmt.run({ before }).changes);
25504
+ }
25505
+ /**
25506
+ * Record delivery. Called only AFTER the far side has accepted the rows.
25507
+ *
25508
+ * CLEARS any failure reason in the same statement. A row that failed against
25509
+ * one deployment and then landed is delivered, and leaving the reason behind
25510
+ * would leave the store holding two contradictory answers about one row —
25511
+ * with the surface free to render either.
25512
+ */
25513
+ markSynced(ids, atMs) {
25514
+ this.stampAll(ids, atMs, null);
25515
+ }
25516
+ /**
25517
+ * Record that THIS MACHINE cannot express the row on the wire.
25518
+ *
25519
+ * Reserved for a local defect — a row that cannot be rebuilt into a valid
25520
+ * payload, or a body the client itself refused to send. It fails identically
25521
+ * against every deployment, so it is terminal everywhere and the re-arm leaves
25522
+ * it alone. A row that merely failed to REACH the deployment stays NULL, so it
25523
+ * is retried; marking those would turn one outage into permanent data loss.
25524
+ */
25525
+ markSkipped(ids, atMs) {
25526
+ this.stampAll(ids, SKIPPED, "payload_invalid", atMs);
25527
+ }
25528
+ /**
25529
+ * Record that THIS DEPLOYMENT refused the row.
25530
+ *
25531
+ * The same sentinel as `markSkipped`, and deliberately so: both stop the row
25532
+ * being re-offered on this lane, and `synced_at` goes on answering whether a
25533
+ * row is outstanding rather than why. What separates them is the reason, and
25534
+ * what the reason buys is the re-arm — a refusal is one deployment's verdict
25535
+ * on one body, so it is terminal only for as long as this machine points at
25536
+ * that deployment, and `rearmFor` clears it when the deployment changes.
25537
+ *
25538
+ * Leaving such a row NULL instead would be worse than the loss it replaces:
25539
+ * these reads carry no cursor, so an unstamped row the deployment refuses is
25540
+ * the head of every subsequent page, and the lane stalls behind it for ever.
25541
+ */
25542
+ markRefused(ids, atMs) {
25543
+ this.stampAll(ids, SKIPPED, "deployment_refused", atMs);
25544
+ }
25545
+ eachInTransaction(ids, run) {
25546
+ if (ids.length === 0) return;
24957
25547
  withTransaction(
24958
- db,
25548
+ this.db,
24959
25549
  () => {
24960
- const alreadyDropped = db.prepare("SELECT 1 FROM migration_ledger WHERE tag = ?").get(migration.tag);
24961
- if (alreadyDropped) return;
24962
- if (before !== void 0 && readLegacyTables(db).mark !== before.mark) {
24963
- akaWarn(
24964
- "legacy events/findings rows changed after the pre-drop snapshot decision; deferring the drop so the next open can copy them first."
24965
- );
24966
- return;
24967
- }
24968
- for (const statement of splitStatements(migration.sql)) {
24969
- db.exec(statement);
24970
- }
24971
- db.prepare("INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)").run(
24972
- migration.tag,
24973
- Date.now()
24974
- );
25550
+ for (const id of ids) run(id);
24975
25551
  },
24976
25552
  "IMMEDIATE"
24977
25553
  );
24978
- } catch (error61) {
24979
- akaWarn(`legacy events/findings drop failed; deferring: ${String(error61)}`);
24980
25554
  }
24981
- }
24982
- function backupBeforeLegacyDrop(db, file2) {
24983
- reapStalePartials(file2);
24984
- const backup = backupPath(file2, "pre-drop");
24985
- snapshotStore(db, backup);
24986
- return backup;
24987
- }
24988
- var TOKEN_USAGE_COLUMNS = [
24989
- {
24990
- name: "input_tokens",
24991
- ddl: "ALTER TABLE audit_events ADD COLUMN input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.input_tokens')) VIRTUAL"
24992
- },
24993
- {
24994
- name: "output_tokens",
24995
- ddl: "ALTER TABLE audit_events ADD COLUMN output_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.output_tokens')) VIRTUAL"
24996
- },
24997
- {
24998
- name: "cache_creation_input_tokens",
24999
- ddl: "ALTER TABLE audit_events ADD COLUMN cache_creation_input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.cache_creation_input_tokens')) VIRTUAL"
25000
- },
25001
- {
25002
- name: "cache_read_input_tokens",
25003
- ddl: "ALTER TABLE audit_events ADD COLUMN cache_read_input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.cache_read_input_tokens')) VIRTUAL"
25004
- },
25005
- {
25006
- name: "model",
25007
- ddl: "ALTER TABLE audit_events ADD COLUMN model text GENERATED ALWAYS AS (json_extract(attributes, '$.model')) VIRTUAL"
25008
- },
25009
- {
25555
+ stampAll(ids, value, failure, failedAtMs) {
25556
+ if (ids.length === 0) return;
25557
+ const failedAt = failure === null ? null : failedAtMs ?? null;
25558
+ withTransaction(
25559
+ this.db,
25560
+ () => {
25561
+ for (const id of ids) this.stampStmt.run({ at: value, failedAt, failure, id });
25562
+ },
25563
+ "IMMEDIATE"
25564
+ );
25565
+ }
25566
+ /**
25567
+ * Claim rows as in-flight.
25568
+ *
25569
+ * Advisory in exactly the sense the lease is: it records that a send is in
25570
+ * progress so a surface can say so, and a lost claim costs a row showing as
25571
+ * queued while it is actually being sent. It is not exclusion — the far side
25572
+ * settles a duplicate on the row id.
25573
+ */
25574
+ claimRows(ids, atMs) {
25575
+ this.eachInTransaction(ids, (id) => this.claimRowStmt.run({ at: atMs, id }));
25576
+ }
25577
+ /** Give back a claim without settling — the send failed, the row is queued again. */
25578
+ releaseRows(ids) {
25579
+ this.eachInTransaction(ids, (id) => this.releaseRowStmt.run({ id }));
25580
+ }
25581
+ /**
25582
+ * Clear claims older than `staleBefore`, and report how many were cleared.
25583
+ *
25584
+ * A process killed between claiming and settling leaves rows claimed with
25585
+ * nothing left to settle them. Without this they read as "sending" for ever.
25586
+ */
25587
+ releaseStaleClaims(staleBefore) {
25588
+ return Number(this.releaseStaleClaimsStmt.run({ staleBefore }).changes);
25589
+ }
25590
+ /**
25591
+ * Every tracked row in exactly one delivery state.
25592
+ *
25593
+ * Takes no boundary on purpose. The boundary answers "what should the drain
25594
+ * pick up now", which is a different question from "what state is this row
25595
+ * in" — and a machine that has never attached has no boundary to pass, so
25596
+ * requiring one would force a caller to invent one and report the whole store
25597
+ * as queued.
25598
+ */
25599
+ /**
25600
+ * The same partition, one row per kind that a lane carries.
25601
+ *
25602
+ * A kind with nothing to report is ABSENT rather than a row of zeros: the
25603
+ * scope decides which rows exist at all, so a kind that has never been
25604
+ * recorded — or whose captures nobody ever owed — produces no group. A caller
25605
+ * rendering a fixed list of kinds must therefore treat a missing one as "no
25606
+ * rows", never as "zero sent"; the two look identical in a bar and mean
25607
+ * different things.
25608
+ */
25609
+ partitionByKind() {
25610
+ return allRows(
25611
+ this.partitionByKindStmt,
25612
+ {}
25613
+ ).map((row) => ({
25614
+ kind: row.kind,
25615
+ queued: row.queued ?? 0,
25616
+ inProgress: row.inProgress ?? 0,
25617
+ synced: row.synced ?? 0,
25618
+ failed: row.failed ?? 0,
25619
+ refused: row.refused ?? 0,
25620
+ detached: row.detached ?? 0,
25621
+ total: row.total ?? 0
25622
+ }));
25623
+ }
25624
+ partition() {
25625
+ const row = getRow(this.partitionStmt, {});
25626
+ return {
25627
+ queued: row?.queued ?? 0,
25628
+ inProgress: row?.inProgress ?? 0,
25629
+ synced: row?.synced ?? 0,
25630
+ failed: row?.failed ?? 0,
25631
+ refused: row?.refused ?? 0,
25632
+ detached: row?.detached ?? 0,
25633
+ total: row?.total ?? 0
25634
+ };
25635
+ }
25636
+ /** `pending` counts only what is inside the backlog; sent and skipped are totals. */
25637
+ counts(before) {
25638
+ const row = getRow(this.countsStmt, { before });
25639
+ const captures = getRow(this.captureSkipCountStmt);
25640
+ return {
25641
+ pending: row?.pending ?? 0,
25642
+ sent: row?.sent ?? 0,
25643
+ skipped: row?.skipped ?? 0,
25644
+ refused: row?.refused ?? 0,
25645
+ detached: row?.detached ?? 0,
25646
+ capturesSkipped: captures?.skipped ?? 0
25647
+ };
25648
+ }
25649
+ /**
25650
+ * The deployment the current stamps were made against, and where its backlog
25651
+ * ends.
25652
+ *
25653
+ * READ-ONLY. An absent row reads as an absent deployment, which is what a
25654
+ * machine that has never drained is — and every writer below seeds the row
25655
+ * before it needs one, so nothing depends on this creating it. Keeping the
25656
+ * write off the gate path matters because the gate runs on every pass while a
25657
+ * write has to take the database's write lock.
25658
+ */
25659
+ deployment() {
25660
+ const row = getRow(
25661
+ this.fingerprintStmt
25662
+ );
25663
+ return {
25664
+ fingerprint: row?.fingerprint ?? void 0,
25665
+ backlogBefore: row?.backlogBefore ?? void 0
25666
+ };
25667
+ }
25668
+ /**
25669
+ * Point the ledger at a different deployment, discarding what it recorded
25670
+ * about the previous one.
25671
+ *
25672
+ * Delivery is a fact about ONE recipient: rows sent to the deployment a
25673
+ * machine has just left are undelivered as far as the new one is concerned.
25674
+ * All four in one transaction, so a crash between them cannot leave stamps
25675
+ * attributed to the wrong deployment, a boundary that belongs to another, or
25676
+ * a disown with no re-mark to follow it.
25677
+ *
25678
+ * The boundary is written HERE and only here, which is what freezes it: a
25679
+ * re-attach to the SAME deployment (a key rotation) leaves the fingerprint
25680
+ * unchanged, so this never runs and the backlog does not widen back over rows
25681
+ * the live path has since delivered.
25682
+ *
25683
+ * `backfillCapturesBefore` is the caller's OWN "now" at the instant a human
25684
+ * granted existing-history consent for the deployment this call is arming —
25685
+ * a DIFFERENT instant from `backlogBefore`: the re-mark boundary is the GRANT
25686
+ * instant, `backlogBefore` is the ATTACH instant, and the two can be far
25687
+ * apart. Passed only when that grant is valid, since this method has no way
25688
+ * to check consent itself and must not mark a row owed for a machine that
25689
+ * never agreed to it. Applied AFTER the disown above, in the SAME
25690
+ * transaction: what the disown clears is every marker below `backlogBefore`,
25691
+ * which includes this deployment's OWN pre-attach rows — `aka attach` calls
25692
+ * `seedCaptureBacklogOwed` at the attach instant, so every row it marks sits
25693
+ * on the cleared side of that bound — and the re-mark in the same
25694
+ * transaction is what puts those rows back. A crash between the two cannot
25695
+ * strand the ledger disowned with nothing re-marked — the transaction either
25696
+ * lands whole or not at all, and a fingerprint mismatch that has not yet
25697
+ * committed re-enters this method on the very next pass. Omit it (the
25698
+ * structural-only tests do) to exercise the disown in isolation.
25699
+ *
25700
+ * The disown is bounded by `backlogBefore`, which is what keeps it from
25701
+ * touching a marker the NEW deployment's OWN live path has already set: B's
25702
+ * live path can mark a capture owed from the moment `aka attach` writes the
25703
+ * descriptor, before the drain's first pass ever reaches this method, and
25704
+ * such a row sits at or after the bound rather than below it. What keeps the
25705
+ * disown from eating THIS SAME CALL's own re-mark is the order, not the
25706
+ * bound — disown runs first, re-mark second, both inside the one
25707
+ * transaction above.
25708
+ */
25709
+ rearmFor(fingerprint, backlogBefore, backfillCapturesBefore) {
25710
+ this.ensureRowStmt.run();
25711
+ withTransaction(
25712
+ this.db,
25713
+ () => {
25714
+ const previous = getRow(this.fingerprintStmt)?.fingerprint;
25715
+ this.rearmStmt.run();
25716
+ if (previous !== null && previous !== void 0 && previous !== fingerprint) {
25717
+ this.disownCapturesStmt.run({ attachedAt: backlogBefore });
25718
+ }
25719
+ if (backfillCapturesBefore !== void 0) {
25720
+ this.markCaptureBacklogOwedStmt.run({ before: backfillCapturesBefore });
25721
+ }
25722
+ this.setFingerprintStmt.run({ fingerprint, backlogBefore });
25723
+ },
25724
+ "IMMEDIATE"
25725
+ );
25726
+ }
25727
+ /**
25728
+ * End the attached period: hand its rows to the live path, and release the
25729
+ * boundary so the next attachment can freeze a new one.
25730
+ *
25731
+ * WITHOUT THIS, a detach and a re-attach to the same deployment leave a window
25732
+ * nothing delivers. The fingerprint is unchanged, so the boundary is never
25733
+ * re-frozen and stays at the FIRST attachment — while nothing forwards at all
25734
+ * during the detached period, because the machine is not attached. Rows
25735
+ * recorded in that window sit after the boundary and before the re-attach, so
25736
+ * neither path takes them, and the pending count reports none outstanding.
25737
+ *
25738
+ * WHAT IT RECORDS, and what it deliberately does not. These rows were the
25739
+ * closing attachment's to deliver and are no longer outstanding — that is what
25740
+ * lets the boundary move. It is NOT a claim that any of them arrived, and the
25741
+ * distinction is not academic: this used to write a delivery TIME, which every
25742
+ * read treats as delivery, so one detach turned a window of undelivered rows
25743
+ * into a window of delivered ones and no surface could tell. It writes the
25744
+ * skip sentinel and a reason of its own instead, so "no longer owed" and
25745
+ * "received" stop being the same fact.
25746
+ *
25747
+ * A change of deployment still frees them (see the re-arm), because the next
25748
+ * deployment has seen none of this machine's history — so the rows reach it
25749
+ * exactly as they did when this wrote a delivery time.
25750
+ *
25751
+ * ONE TRANSACTION, so a crash cannot release the boundary while leaving the
25752
+ * window unstamped — that half-state would re-send the whole attached period
25753
+ * on the next attach, which is the failure the boundary exists to prevent.
25754
+ */
25755
+ closeAttachedWindow(attachedAtMs, atMs) {
25756
+ this.ensureRowStmt.run();
25757
+ withTransaction(
25758
+ this.db,
25759
+ () => {
25760
+ const row = getRow(this.fingerprintStmt);
25761
+ const from = row?.backlogBefore ?? attachedAtMs;
25762
+ this.closeWindowStmt.run({ at: atMs, attachedAt: from });
25763
+ this.releaseBoundaryStmt.run();
25764
+ },
25765
+ "IMMEDIATE"
25766
+ );
25767
+ }
25768
+ /**
25769
+ * Freeze a boundary for the deployment already on file, KEEPING the stamps.
25770
+ *
25771
+ * The re-attach half of the above. Distinct from `rearmFor`, which is for a
25772
+ * different deployment and therefore discards what was delivered to the old
25773
+ * one: here the recipient is the same, so everything already sent to it stays
25774
+ * sent.
25775
+ */
25776
+ freezeBoundary(backlogBefore) {
25777
+ this.ensureRowStmt.run();
25778
+ this.freezeBoundaryStmt.run({ backlogBefore });
25779
+ }
25780
+ /** Take the claim, or report that someone live already holds it. */
25781
+ claim(pid, host, nowMs, staleAfterMs) {
25782
+ this.ensureRowStmt.run();
25783
+ let taken = false;
25784
+ withTransaction(
25785
+ this.db,
25786
+ () => {
25787
+ const result = this.claimStmt.run({
25788
+ pid,
25789
+ host,
25790
+ now: nowMs,
25791
+ staleBefore: nowMs - staleAfterMs
25792
+ });
25793
+ taken = result.changes === 1;
25794
+ },
25795
+ "IMMEDIATE"
25796
+ );
25797
+ return taken;
25798
+ }
25799
+ /** Say the holder is still alive. A no-op once the claim has moved on. */
25800
+ heartbeat(pid, nowMs) {
25801
+ this.heartbeatStmt.run({ now: nowMs, pid });
25802
+ }
25803
+ /** Give the claim up. Scoped to this holder, so a taken-over claim is left be. */
25804
+ release(pid) {
25805
+ this.releaseStmt.run({ pid });
25806
+ }
25807
+ /** Who holds the claim, if anyone. Read-only, for the same reason as above. */
25808
+ lease() {
25809
+ return getRow(this.leaseStmt);
25810
+ }
25811
+ };
25812
+
25813
+ // ../../packages/persistence/src/migrations.ts
25814
+ function describeObject(object2) {
25815
+ return object2.kind === "column" ? `column ${object2.table}.${object2.name}` : `table ${object2.name}`;
25816
+ }
25817
+ function splitStatements(sql) {
25818
+ return sql.split(/-->\s*statement-breakpoint/).map((s) => s.trim()).filter((s) => s.length > 0);
25819
+ }
25820
+ function createdIndexName(statement) {
25821
+ const body = statement.replace(/^(?:\s*--[^\n]*\n?)+/, "").trimStart();
25822
+ return /^CREATE (?:UNIQUE )?INDEX (?:IF NOT EXISTS )?`([^`]+)`/.exec(body)?.[1];
25823
+ }
25824
+ var LEGACY_DROP_MIGRATION_TAG = "0014_drop_legacy_events_findings";
25825
+ function applyMigrations(db, file2, options = {}) {
25826
+ const legacyCount = db.prepare("PRAGMA user_version").get().user_version;
25827
+ db.exec(
25828
+ "CREATE TABLE IF NOT EXISTS migration_ledger (tag TEXT PRIMARY KEY, applied_at INTEGER NOT NULL)"
25829
+ );
25830
+ const applied = new Set(
25831
+ db.prepare("SELECT tag FROM migration_ledger").all().map((r) => r.tag)
25832
+ );
25833
+ const preLedgerStore = applied.size === 0 && legacyCount > 0;
25834
+ const record2 = db.prepare(
25835
+ "INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)"
25836
+ );
25837
+ for (const [index, migration] of SQLITE_MIGRATIONS.entries()) {
25838
+ if (applied.has(migration.tag)) continue;
25839
+ if (options.skipTags?.has(migration.tag) === true) continue;
25840
+ if (migration.tag === LEGACY_DROP_MIGRATION_TAG) continue;
25841
+ const evidence = evidenceObjects(migration.sql);
25842
+ const present2 = evidence.filter((o) => evidenceExists(db, o));
25843
+ if (present2.length > 0 && present2.length < evidence.length) {
25844
+ const missing = evidence.filter((o) => !present2.includes(o));
25845
+ const message = `sqlite migration ${migration.tag} has no ledger row, but the store already has ${present2.map(describeObject).join(", ")} while missing ${missing.map(describeObject).join(", ")} \u2014 the schema diverged from the migration history; refusing to replay or skip.`;
25846
+ akaWarn(message);
25847
+ throw new Error(`[aka] ${message}`);
25848
+ }
25849
+ const alreadyApplied = evidence.length > 0 ? present2.length === evidence.length : preLedgerStore && index < legacyCount;
25850
+ const wantsFkOff = /PRAGMA foreign_keys\s*=\s*OFF/i.test(migration.sql);
25851
+ const statements = splitStatements(migration.sql);
25852
+ if (wantsFkOff) db.exec("PRAGMA foreign_keys = OFF");
25853
+ try {
25854
+ withTransaction(
25855
+ db,
25856
+ () => {
25857
+ for (const statement of statements) {
25858
+ const indexName = createdIndexName(statement);
25859
+ if (indexName === void 0) {
25860
+ if (alreadyApplied) continue;
25861
+ } else if (indexExists(db, indexName)) {
25862
+ continue;
25863
+ }
25864
+ db.exec(statement);
25865
+ }
25866
+ if (wantsFkOff && !alreadyApplied) {
25867
+ const violations = db.prepare("PRAGMA foreign_key_check").all();
25868
+ if (violations.length > 0) {
25869
+ throw new Error(
25870
+ `[aka] sqlite migration ${migration.tag} left ${String(violations.length)} foreign-key violation(s); rolling back.`
25871
+ );
25872
+ }
25873
+ }
25874
+ record2.run(migration.tag, Date.now());
25875
+ },
25876
+ "IMMEDIATE"
25877
+ );
25878
+ } finally {
25879
+ if (wantsFkOff) db.exec("PRAGMA foreign_keys = ON");
25880
+ }
25881
+ }
25882
+ if (legacyCount < SQLITE_MIGRATIONS.length) {
25883
+ db.exec(`PRAGMA user_version = ${String(SQLITE_MIGRATIONS.length)}`);
25884
+ }
25885
+ ensureSyncedAtColumn(db, "audit_events");
25886
+ ensureScanLedgerTable(db);
25887
+ ensureHistorySyncTable(db);
25888
+ ensureBlockedDetectionsTable(db);
25889
+ ensureRuleProbeCacheTable(db);
25890
+ ensureWriteGateTrigger(db);
25891
+ ensureTokenUsageColumns(db);
25892
+ reconcileSourceProjectIds(db);
25893
+ if (!applied.has(LEGACY_DROP_MIGRATION_TAG)) {
25894
+ const drained = runLegacyHistoryBackfill(db);
25895
+ if (drained) applyLegacyDropMigration(db, file2);
25896
+ }
25897
+ }
25898
+ function readLegacyTables(db) {
25899
+ let holdsRows = false;
25900
+ const marks = [];
25901
+ for (const table2 of ["events", "findings"]) {
25902
+ try {
25903
+ const row = db.prepare(`SELECT count(*) AS n, ifnull(max(rowid), -1) AS hi FROM ${table2}`).get();
25904
+ if (row === void 0) {
25905
+ holdsRows = true;
25906
+ marks.push(`${table2}:unreadable`);
25907
+ continue;
25908
+ }
25909
+ if (row.n > 0) holdsRows = true;
25910
+ marks.push(`${table2}:${String(row.n)}:${String(row.hi)}`);
25911
+ } catch {
25912
+ holdsRows = true;
25913
+ marks.push(`${table2}:unreadable`);
25914
+ }
25915
+ }
25916
+ return { holdsRows, mark: marks.join("|") };
25917
+ }
25918
+ function applyLegacyDropMigration(db, file2) {
25919
+ const migration = SQLITE_MIGRATIONS.find((m) => m.tag === LEGACY_DROP_MIGRATION_TAG);
25920
+ if (!migration) return;
25921
+ const before = file2 === void 0 ? void 0 : readLegacyTables(db);
25922
+ if (file2 !== void 0 && before?.holdsRows === true) {
25923
+ try {
25924
+ backupBeforeLegacyDrop(db, file2);
25925
+ } catch (error61) {
25926
+ akaWarn(`legacy events/findings backup failed; deferring the drop: ${String(error61)}`);
25927
+ return;
25928
+ }
25929
+ }
25930
+ try {
25931
+ withTransaction(
25932
+ db,
25933
+ () => {
25934
+ const alreadyDropped = db.prepare("SELECT 1 FROM migration_ledger WHERE tag = ?").get(migration.tag);
25935
+ if (alreadyDropped) return;
25936
+ if (before !== void 0 && readLegacyTables(db).mark !== before.mark) {
25937
+ akaWarn(
25938
+ "legacy events/findings rows changed after the pre-drop snapshot decision; deferring the drop so the next open can copy them first."
25939
+ );
25940
+ return;
25941
+ }
25942
+ for (const statement of splitStatements(migration.sql)) {
25943
+ db.exec(statement);
25944
+ }
25945
+ db.prepare("INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)").run(
25946
+ migration.tag,
25947
+ Date.now()
25948
+ );
25949
+ },
25950
+ "IMMEDIATE"
25951
+ );
25952
+ } catch (error61) {
25953
+ akaWarn(`legacy events/findings drop failed; deferring: ${String(error61)}`);
25954
+ }
25955
+ }
25956
+ function backupBeforeLegacyDrop(db, file2) {
25957
+ reapStalePartials(file2);
25958
+ const backup = backupPath(file2, "pre-drop");
25959
+ snapshotStore(db, backup);
25960
+ return backup;
25961
+ }
25962
+ var TOKEN_USAGE_COLUMNS = [
25963
+ {
25964
+ name: "input_tokens",
25965
+ ddl: "ALTER TABLE audit_events ADD COLUMN input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.input_tokens')) VIRTUAL"
25966
+ },
25967
+ {
25968
+ name: "output_tokens",
25969
+ ddl: "ALTER TABLE audit_events ADD COLUMN output_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.output_tokens')) VIRTUAL"
25970
+ },
25971
+ {
25972
+ name: "cache_creation_input_tokens",
25973
+ ddl: "ALTER TABLE audit_events ADD COLUMN cache_creation_input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.cache_creation_input_tokens')) VIRTUAL"
25974
+ },
25975
+ {
25976
+ name: "cache_read_input_tokens",
25977
+ ddl: "ALTER TABLE audit_events ADD COLUMN cache_read_input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.cache_read_input_tokens')) VIRTUAL"
25978
+ },
25979
+ {
25980
+ name: "model",
25981
+ ddl: "ALTER TABLE audit_events ADD COLUMN model text GENERATED ALWAYS AS (json_extract(attributes, '$.model')) VIRTUAL"
25982
+ },
25983
+ {
25010
25984
  name: "provider",
25011
25985
  ddl: "ALTER TABLE audit_events ADD COLUMN provider text GENERATED ALWAYS AS (json_extract(attributes, '$.provider')) VIRTUAL"
25012
25986
  }
@@ -25269,10 +26243,62 @@ function ensureSyncedAtColumn(db, table2) {
25269
26243
  if (!columns.includes("outbox_owed")) {
25270
26244
  db.exec(`ALTER TABLE ${table2} ADD COLUMN outbox_owed integer`);
25271
26245
  }
26246
+ if (!columns.includes("sync_failed_at")) {
26247
+ db.exec(`ALTER TABLE ${table2} ADD COLUMN sync_failed_at integer`);
26248
+ }
26249
+ if (!columns.includes("sync_failure")) {
26250
+ withTransaction(
26251
+ db,
26252
+ () => {
26253
+ db.exec(`ALTER TABLE ${table2} ADD COLUMN sync_failure text`);
26254
+ db.exec(
26255
+ `UPDATE ${table2} SET synced_at = NULL
26256
+ WHERE synced_at = -1
26257
+ AND event_type IN (${COUNTED_EVENT_TYPES.map((t) => `'${t}'`).join(", ")})`
26258
+ );
26259
+ },
26260
+ "IMMEDIATE"
26261
+ );
26262
+ }
25272
26263
  db.exec(
25273
- `CREATE INDEX IF NOT EXISTS idx_audit_events_sync
25274
- ON audit_events (event_type, synced_at, sync_claimed_at, started_at)`
26264
+ `CREATE TRIGGER IF NOT EXISTS aka_sync_failure_guard
26265
+ BEFORE UPDATE OF sync_failure ON ${table2}
26266
+ WHEN ${syncFailureRejectCondition()}
26267
+ BEGIN SELECT RAISE(ABORT, 'sync_failure is not one of the recorded reasons'); END`
25275
26268
  );
26269
+ const syncIndexColumns = [
26270
+ "event_type",
26271
+ "synced_at",
26272
+ "sync_claimed_at",
26273
+ "started_at",
26274
+ // Appended LAST on purpose. The delivery-state read now projects it, so it
26275
+ // has to be in the index for the read to stay covered — but putting it
26276
+ // ahead of `started_at` would reorder the prefix the structural drain's
26277
+ // reads match on.
26278
+ "sync_failure"
26279
+ // `outbox_owed` is DELIBERATELY ABSENT, and it was measured both ways.
26280
+ //
26281
+ // The delivery-state read tests it — a capture's state depends on whether a
26282
+ // live forward marked it owed — so carrying it here makes that read covering
26283
+ // rather than a row fetch per row: 16 ms against 40 ms on a real 6 GB store.
26284
+ // But a sixth column changes what the planner charges for this index, and
26285
+ // with no ANALYZE statistics it plans from schema shape alone: measured, it
26286
+ // then stops choosing the per-session index for the token rollup and walks
26287
+ // every `llm_call` in the store through the event-type index instead. That
26288
+ // read grows with the store; this one does not.
26289
+ //
26290
+ // 40 ms on the largest store measured, once per render, is a cost worth
26291
+ // paying to leave every other read's plan where it was.
26292
+ ];
26293
+ const currentSyncIndex = indexColumns(db, "idx_audit_events_sync");
26294
+ const syncIndexMatches = currentSyncIndex.length === syncIndexColumns.length && currentSyncIndex.every((column, i) => column === syncIndexColumns[i]);
26295
+ if (!syncIndexMatches) {
26296
+ db.exec("DROP INDEX IF EXISTS idx_audit_events_sync");
26297
+ db.exec(
26298
+ `CREATE INDEX idx_audit_events_sync
26299
+ ON audit_events (${syncIndexColumns.join(", ")})`
26300
+ );
26301
+ }
25276
26302
  db.exec(
25277
26303
  `CREATE INDEX IF NOT EXISTS idx_audit_outbox_owed
25278
26304
  ON audit_events (event_type, synced_at, sync_claimed_at, started_at) WHERE outbox_owed = 1`
@@ -25494,7 +26520,11 @@ function buildAuditEvent(row) {
25494
26520
  link: linkParsed?.success ? linkParsed.data : null,
25495
26521
  targetId: row.target_id,
25496
26522
  internal: intToBool(row.internal),
25497
- flagged: intToBool(row.flagged)
26523
+ flagged: intToBool(row.flagged),
26524
+ // Only meaningful when the title came out empty — a row whose body was
26525
+ // expired but whose title fell back to `tool_name` still has something to
26526
+ // render, and flagging it would make the view apologise for nothing.
26527
+ bodyExpired: row.content_expired_at !== null && (row.title ?? "") === ""
25498
26528
  };
25499
26529
  }
25500
26530
  var TIMELINE_COLUMNS = `
@@ -25502,6 +26532,7 @@ var TIMELINE_COLUMNS = `
25502
26532
  event_type,
25503
26533
  started_at,
25504
26534
  coalesce(content, json_extract(attributes, '$.tool_name')) AS title,
26535
+ content_expired_at,
25505
26536
  coalesce(json_extract(attributes, '$.detail'), json_extract(attributes, '$.target')) AS detail,
25506
26537
  coalesce(json_extract(attributes, '$.tool_name'), json_extract(attributes, '$.tool')) AS tool,
25507
26538
  json_extract(attributes, '$.severity') AS severity,
@@ -26167,6 +27198,88 @@ var SqliteAuditEventsRepository = class {
26167
27198
  }
26168
27199
  };
26169
27200
 
27201
+ // ../../packages/persistence/src/repositories/body-retention.ts
27202
+ var DEFAULT_BATCH_SIZE = 500;
27203
+ var DEFAULT_MAX_ROWS = 5e4;
27204
+ var SYNC_LANE_TYPES_SQL = OUTBOX_CAPTURE_TYPE_LIST;
27205
+ var SqliteBodyRetentionRepository = class {
27206
+ constructor(db) {
27207
+ this.db = db;
27208
+ const select = (laneClause) => `
27209
+ SELECT id, LENGTH(CAST(content AS BLOB)) AS bytes
27210
+ FROM audit_events
27211
+ WHERE content IS NOT NULL
27212
+ AND started_at < :cutoff
27213
+ AND event_type IN (${CAPTURE_EVENT_TYPES_SQL})
27214
+ ${laneClause}
27215
+ ORDER BY started_at
27216
+ LIMIT :limit`;
27217
+ this.candidatesStmt = this.db.prepare(select(""));
27218
+ this.candidatesSyncSafeStmt = this.db.prepare(
27219
+ select(`AND (event_type NOT IN (${SYNC_LANE_TYPES_SQL}) OR synced_at IS NOT NULL)`)
27220
+ );
27221
+ this.heldBySyncStmt = this.db.prepare(`
27222
+ SELECT COUNT(*) AS n
27223
+ FROM audit_events
27224
+ WHERE content IS NOT NULL
27225
+ AND started_at < :cutoff
27226
+ AND event_type IN (${SYNC_LANE_TYPES_SQL})
27227
+ AND synced_at IS NULL`);
27228
+ this.expireStmt = this.db.prepare(
27229
+ `UPDATE audit_events SET content = NULL, content_expired_at = :now WHERE id = :id`
27230
+ );
27231
+ }
27232
+ db;
27233
+ candidatesStmt;
27234
+ candidatesSyncSafeStmt;
27235
+ heldBySyncStmt;
27236
+ expireStmt;
27237
+ /** How many bytes a pass with these options would free, changing nothing. */
27238
+ preview(opts) {
27239
+ const limit = opts.maxRows ?? DEFAULT_MAX_ROWS;
27240
+ const stmt = opts.sweepSyncLane ? this.candidatesStmt : this.candidatesSyncSafeStmt;
27241
+ const rows = stmt.all({ cutoff: opts.cutoff, limit });
27242
+ return {
27243
+ rowsExpired: rows.length,
27244
+ bytesFreed: rows.reduce((sum, r) => sum + r.bytes, 0),
27245
+ rowsHeldBySync: this.countHeldBySync(opts)
27246
+ };
27247
+ }
27248
+ /** Clear eligible bodies, in bounded batches. */
27249
+ expire(opts) {
27250
+ const batchSize = opts.batchSize ?? DEFAULT_BATCH_SIZE;
27251
+ const maxRows = opts.maxRows ?? DEFAULT_MAX_ROWS;
27252
+ const stmt = opts.sweepSyncLane ? this.candidatesStmt : this.candidatesSyncSafeStmt;
27253
+ let rowsExpired = 0;
27254
+ let bytesFreed = 0;
27255
+ let done = true;
27256
+ while (rowsExpired < maxRows) {
27257
+ const remaining = Math.min(batchSize, maxRows - rowsExpired);
27258
+ const batch = stmt.all({ cutoff: opts.cutoff, limit: remaining });
27259
+ if (batch.length === 0) break;
27260
+ withTransaction(
27261
+ this.db,
27262
+ () => {
27263
+ for (const row of batch) this.expireStmt.run({ id: row.id, now: opts.now });
27264
+ },
27265
+ "IMMEDIATE"
27266
+ );
27267
+ rowsExpired += batch.length;
27268
+ bytesFreed += batch.reduce((sum, r) => sum + r.bytes, 0);
27269
+ if (batch.length < remaining) break;
27270
+ if (rowsExpired >= maxRows) {
27271
+ done = stmt.all({ cutoff: opts.cutoff, limit: 1 }).length === 0;
27272
+ }
27273
+ }
27274
+ return { rowsExpired, bytesFreed, rowsHeldBySync: this.countHeldBySync(opts), done };
27275
+ }
27276
+ countHeldBySync(opts) {
27277
+ if (opts.sweepSyncLane) return 0;
27278
+ const row = this.heldBySyncStmt.get({ cutoff: opts.cutoff });
27279
+ return row.n;
27280
+ }
27281
+ };
27282
+
26170
27283
  // ../../packages/persistence/src/repositories/classified-data.ts
26171
27284
  var SqliteClassifiedDataRepository = class {
26172
27285
  constructor(db) {
@@ -26995,7 +28108,15 @@ function toFlatFindingRow(r) {
26995
28108
  ...r.tool_name === null ? {} : { toolName: r.tool_name },
26996
28109
  eventId: r.event_id,
26997
28110
  ...r.session_id === null ? {} : { sessionId: r.session_id },
26998
- status: deriveInstanceStatus(r)
28111
+ status: deriveInstanceStatus(r),
28112
+ delivery: deriveFindingDelivery({
28113
+ kind: r.kind,
28114
+ syncedAt: r.synced_at,
28115
+ syncClaimedAt: r.sync_claimed_at,
28116
+ syncFailedAt: r.sync_failed_at,
28117
+ syncFailure: r.sync_failure,
28118
+ outboxOwed: r.outbox_owed
28119
+ })
26999
28120
  };
27000
28121
  }
27001
28122
  function encodeGroupCursor(group) {
@@ -27059,7 +28180,10 @@ var FINDING_ROW_COLUMNS_SQL = `f.id AS id, d.rule_id AS rule_id, d.category AS c
27059
28180
  e.tool_name AS tool_name,
27060
28181
  f.audit_event_id AS event_id, e.root_session_id AS session_id,
27061
28182
  e.event_type AS kind, f.finding_key AS finding_key,
27062
- ${latestResolutionStatusSql("f")} AS latest_status`;
28183
+ ${latestResolutionStatusSql("f")} AS latest_status,
28184
+ e.synced_at AS synced_at, e.sync_claimed_at AS sync_claimed_at,
28185
+ e.sync_failed_at AS sync_failed_at, e.sync_failure AS sync_failure,
28186
+ e.outbox_owed AS outbox_owed`;
27063
28187
  var DAY_MS3 = 864e5;
27064
28188
  var SqliteFindingsRepository = class {
27065
28189
  constructor(db) {
@@ -27304,6 +28428,7 @@ var SqliteFindingsRepository = class {
27304
28428
  providers: query.provider,
27305
28429
  actions: query.action,
27306
28430
  statuses: query.status,
28431
+ deliveries: query.deployment,
27307
28432
  tools: query.tool,
27308
28433
  repo: query.repo,
27309
28434
  file: query.file,
@@ -27371,6 +28496,7 @@ var SqliteFindingsRepository = class {
27371
28496
  providers: query.provider,
27372
28497
  actions: query.action,
27373
28498
  statuses: query.status,
28499
+ deliveries: query.deployment,
27374
28500
  tools: query.tool,
27375
28501
  q: query.q
27376
28502
  };
@@ -27634,7 +28760,9 @@ var SqliteFindingsRepository = class {
27634
28760
  )
27635
28761
  );
27636
28762
  for (const row of grouped) {
27637
- if (row.action_taken in byAction) byAction[row.action_taken] = row.c;
28763
+ if (Object.hasOwn(byAction, row.action_taken)) {
28764
+ byAction[row.action_taken] = row.c;
28765
+ }
27638
28766
  }
27639
28767
  const bySeverity = { critical: 0, high: 0, medium: 0, low: 0 };
27640
28768
  const sevRows = allRows(
@@ -27651,7 +28779,9 @@ var SqliteFindingsRepository = class {
27651
28779
  )
27652
28780
  );
27653
28781
  for (const row of sevRows) {
27654
- if (row.severity in bySeverity) bySeverity[row.severity] = row.c;
28782
+ if (Object.hasOwn(bySeverity, row.severity)) {
28783
+ bySeverity[row.severity] = row.c;
28784
+ }
27655
28785
  }
27656
28786
  const categories = ENFORCEABLE_CATEGORIES;
27657
28787
  const enabledRows = allRows(
@@ -27700,525 +28830,6 @@ function isoDay(ms) {
27700
28830
  return new Date(ms).toISOString().slice(0, 10);
27701
28831
  }
27702
28832
 
27703
- // ../../packages/persistence/src/repositories/history-sync.ts
27704
- var STRUCTURAL_EVENT_TYPES = ["session", "llm_call", "tool_call"];
27705
- var TYPE_LIST = STRUCTURAL_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
27706
- var OUTBOX_CAPTURE_EVENT_TYPES = ["prompt", "response", "tool_use"];
27707
- var CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
27708
- var SKIPPED = -1;
27709
- var ROW_COLUMNS = `id,
27710
- parent_id AS parentId,
27711
- root_session_id AS rootSessionId,
27712
- event_type AS eventType,
27713
- host_id AS hostId,
27714
- harness_id AS harnessId,
27715
- source_project_id AS sourceProjectId,
27716
- started_at AS startedAt,
27717
- ended_at AS endedAt,
27718
- severity,
27719
- priority,
27720
- content,
27721
- content_hash AS contentHash,
27722
- attributes`;
27723
- var SqliteHistorySyncRepository = class {
27724
- constructor(db) {
27725
- this.db = db;
27726
- this.ensureRowStmt = db.prepare(`INSERT OR IGNORE INTO history_sync (id) VALUES (1)`);
27727
- this.sessionsStmt = db.prepare(
27728
- `SELECT COALESCE(root_session_id, id) AS sessionId, MIN(started_at) AS earliest
27729
- FROM audit_events
27730
- WHERE synced_at IS NULL
27731
- AND event_type IN (${TYPE_LIST})
27732
- AND started_at < :before
27733
- GROUP BY sessionId
27734
- ORDER BY earliest
27735
- LIMIT :limit`
27736
- );
27737
- this.rowsStmt = db.prepare(
27738
- `SELECT ${ROW_COLUMNS}
27739
- FROM audit_events
27740
- WHERE synced_at IS NULL
27741
- AND event_type IN (${TYPE_LIST})
27742
- AND started_at < :before
27743
- AND COALESCE(root_session_id, id) = :sessionId
27744
- ORDER BY (event_type = 'session') DESC, started_at
27745
- LIMIT :limit`
27746
- );
27747
- this.captureRowsStmt = db.prepare(
27748
- `SELECT ${ROW_COLUMNS}
27749
- FROM audit_events
27750
- WHERE synced_at IS NULL
27751
- AND sync_claimed_at IS NULL
27752
- AND outbox_owed = 1
27753
- AND event_type IN (${CAPTURE_TYPE_LIST})
27754
- AND started_at < :before
27755
- ORDER BY started_at
27756
- LIMIT :limit`
27757
- );
27758
- this.markOwedStmt = db.prepare(
27759
- `UPDATE audit_events SET outbox_owed = 1 WHERE id = :id AND synced_at IS NULL`
27760
- );
27761
- this.markCaptureBacklogOwedStmt = db.prepare(
27762
- `UPDATE audit_events SET outbox_owed = 1
27763
- WHERE synced_at IS NULL
27764
- AND event_type IN (${CAPTURE_TYPE_LIST})
27765
- AND started_at < :before`
27766
- );
27767
- this.stampStmt = db.prepare(
27768
- `UPDATE audit_events SET synced_at = :at, sync_claimed_at = NULL WHERE id = :id`
27769
- );
27770
- this.claimRowStmt = db.prepare(
27771
- `UPDATE audit_events SET sync_claimed_at = :at WHERE id = :id AND synced_at IS NULL`
27772
- );
27773
- this.releaseRowStmt = db.prepare(
27774
- `UPDATE audit_events SET sync_claimed_at = NULL WHERE id = :id`
27775
- );
27776
- this.releaseStaleClaimsStmt = db.prepare(
27777
- `UPDATE audit_events SET sync_claimed_at = NULL
27778
- WHERE sync_claimed_at IS NOT NULL AND sync_claimed_at < :staleBefore`
27779
- );
27780
- this.partitionStmt = db.prepare(
27781
- `SELECT
27782
- SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NULL THEN 1 ELSE 0 END) AS queued,
27783
- SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NOT NULL THEN 1 ELSE 0 END) AS inProgress,
27784
- SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS synced,
27785
- SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0 THEN 1 ELSE 0 END) AS failed,
27786
- COUNT(*) AS total
27787
- FROM audit_events
27788
- WHERE event_type IN (${TYPE_LIST})`
27789
- );
27790
- this.countsStmt = db.prepare(
27791
- `SELECT
27792
- SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
27793
- SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
27794
- SUM(CASE WHEN synced_at = ${String(SKIPPED)} THEN 1 ELSE 0 END) AS skipped
27795
- FROM audit_events
27796
- WHERE event_type IN (${TYPE_LIST})`
27797
- );
27798
- this.captureSkipCountStmt = db.prepare(
27799
- `SELECT COUNT(*) AS skipped
27800
- FROM audit_events
27801
- WHERE synced_at = ${String(SKIPPED)}
27802
- AND event_type IN (${CAPTURE_TYPE_LIST})`
27803
- );
27804
- this.fingerprintStmt = db.prepare(
27805
- `SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
27806
- FROM history_sync WHERE id = 1`
27807
- );
27808
- this.setFingerprintStmt = db.prepare(
27809
- `UPDATE history_sync
27810
- SET endpoint_fingerprint = :fingerprint, backlog_before = :backlogBefore
27811
- WHERE id = 1`
27812
- );
27813
- this.disownCapturesStmt = db.prepare(
27814
- `UPDATE audit_events SET outbox_owed = NULL
27815
- WHERE outbox_owed IS NOT NULL
27816
- AND event_type IN (${CAPTURE_TYPE_LIST})
27817
- AND started_at < :attachedAt`
27818
- );
27819
- this.rearmStmt = db.prepare(
27820
- `UPDATE audit_events SET synced_at = NULL
27821
- WHERE synced_at > 0 AND event_type IN (${TYPE_LIST})`
27822
- );
27823
- this.claimStmt = db.prepare(
27824
- `UPDATE history_sync
27825
- SET owner_pid = :pid, owner_host = :host, acquired_at = :now, heartbeat_at = :now
27826
- WHERE id = 1
27827
- AND (owner_pid IS NULL
27828
- OR heartbeat_at IS NULL
27829
- OR heartbeat_at < :staleBefore
27830
- OR heartbeat_at > :now)`
27831
- );
27832
- this.heartbeatStmt = db.prepare(
27833
- `UPDATE history_sync SET heartbeat_at = :now WHERE id = 1 AND owner_pid = :pid`
27834
- );
27835
- this.releaseStmt = db.prepare(
27836
- `UPDATE history_sync
27837
- SET owner_pid = NULL, owner_host = NULL, acquired_at = NULL, heartbeat_at = NULL
27838
- WHERE id = 1 AND owner_pid = :pid`
27839
- );
27840
- this.closeWindowStmt = db.prepare(
27841
- `UPDATE audit_events SET synced_at = :at
27842
- WHERE synced_at IS NULL
27843
- AND event_type IN (${TYPE_LIST})
27844
- AND started_at >= :attachedAt`
27845
- );
27846
- this.releaseBoundaryStmt = db.prepare(
27847
- `UPDATE history_sync SET backlog_before = NULL WHERE id = 1`
27848
- );
27849
- this.freezeBoundaryStmt = db.prepare(
27850
- `UPDATE history_sync SET backlog_before = :backlogBefore WHERE id = 1`
27851
- );
27852
- this.leaseStmt = db.prepare(
27853
- `SELECT owner_pid AS ownerPid, owner_host AS ownerHost,
27854
- acquired_at AS acquiredAt, heartbeat_at AS heartbeatAt
27855
- FROM history_sync WHERE id = 1`
27856
- );
27857
- this.inspectionsStmt = db.prepare(
27858
- `SELECT d.rule_id AS ruleId,
27859
- d.name AS ruleName,
27860
- d.version AS ruleVersion,
27861
- d.category AS category,
27862
- d.severity AS severity,
27863
- f.span_start AS spanStart,
27864
- f.span_end AS spanEnd,
27865
- f.masked_match AS maskedMatch,
27866
- f.action_taken AS actionTaken,
27867
- f.confidence AS confidence
27868
- FROM inspection_findings f
27869
- JOIN inspection_definitions d ON d.id = f.inspection_definition_id
27870
- WHERE f.audit_event_id = :auditEventId
27871
- ORDER BY f.span_start, f.id`
27872
- );
27873
- }
27874
- db;
27875
- ensureRowStmt;
27876
- sessionsStmt;
27877
- rowsStmt;
27878
- stampStmt;
27879
- countsStmt;
27880
- fingerprintStmt;
27881
- setFingerprintStmt;
27882
- rearmStmt;
27883
- claimStmt;
27884
- heartbeatStmt;
27885
- releaseStmt;
27886
- leaseStmt;
27887
- inspectionsStmt;
27888
- closeWindowStmt;
27889
- releaseBoundaryStmt;
27890
- freezeBoundaryStmt;
27891
- captureRowsStmt;
27892
- markOwedStmt;
27893
- markCaptureBacklogOwedStmt;
27894
- captureSkipCountStmt;
27895
- disownCapturesStmt;
27896
- partitionStmt;
27897
- claimRowStmt;
27898
- releaseRowStmt;
27899
- releaseStaleClaimsStmt;
27900
- /**
27901
- * The masked detections recorded against one tool call.
27902
- *
27903
- * These travel with the event because a tool call's target is not
27904
- * re-inspectable from the event alone — unlike a capture, where the text
27905
- * itself is re-scannable. What crosses is the masked match and the rule that
27906
- * produced it, never the value.
27907
- */
27908
- inspectionsFor(auditEventId) {
27909
- return allRows(this.inspectionsStmt, { auditEventId });
27910
- }
27911
- /**
27912
- * Sessions with structural rows still to send, oldest first.
27913
- *
27914
- * BOUNDED BY THE BACKLOG BOUNDARY, which is the whole correctness of this
27915
- * read. Anything recorded after the machine attached is the live forward
27916
- * path's to deliver; this drain exists for what was recorded before it, and a
27917
- * row both paths send is at best a duplicate request and at worst — for a
27918
- * session root — an overwrite of the inventory ids the live path resolved.
27919
- */
27920
- pendingSessions(limit, before) {
27921
- return allRows(this.sessionsStmt, { limit, before }).map(
27922
- (r) => r.sessionId
27923
- );
27924
- }
27925
- /** One session's undelivered structural rows within the backlog, root first. */
27926
- pendingRows(sessionId, limit, before) {
27927
- return allRows(this.rowsStmt, { sessionId, limit, before });
27928
- }
27929
- /**
27930
- * Captures this machine still owes the deployment, oldest first.
27931
- *
27932
- * Selected by the `outbox_owed` marker the attached forward path writes, not
27933
- * by a time window — see captureRowsStmt for why a window could not express
27934
- * this. `before` is the grace window that leaves a just-recorded capture to
27935
- * the live path.
27936
- */
27937
- pendingCaptureRows(limit, before) {
27938
- return allRows(this.captureRowsStmt, { limit, before });
27939
- }
27940
- /**
27941
- * Record that a capture is OWED to the deployment.
27942
- *
27943
- * Written by the attached forward path when a live send did not confirm
27944
- * delivery, and read by the drain as the whole of its eligibility test. It is
27945
- * a fact rather than an inference: the machine was attached, the send did not
27946
- * land, so the row is owed — which no time window can state, because the same
27947
- * window that holds the rows a past attachment left owed also holds every
27948
- * capture recorded while the machine was DETACHED, and those were never
27949
- * offered to anyone.
27950
- *
27951
- * Idempotent, and never un-set: `markSynced` settling the row is what takes it
27952
- * out of the drain's read.
27953
- */
27954
- markCaptureOwed(id) {
27955
- this.markOwedStmt.run({ id });
27956
- }
27957
- /**
27958
- * Mark every capture already on disk as owed, as of `before`.
27959
- *
27960
- * The consent-time backfill, called once from `aka attach` when a human
27961
- * grants existing-history consent — never from an ongoing drain pass, and
27962
- * never inferred from a boundary that could later move. `before` is the
27963
- * caller's own "now" at the moment consent was granted, so what this marks
27964
- * is exactly the backlog the consent prompt already counted, not whatever a
27965
- * later re-attach or key rotation might widen it to.
27966
- *
27967
- * Returns how many rows matched, for the caller to log or test against. Not a
27968
- * count of NEWLY marked rows — a row still unsynced from an earlier call
27969
- * matches again and is counted again, the same as `UPDATE`'s own `changes`.
27970
- */
27971
- markCaptureBacklogOwed(before) {
27972
- return Number(this.markCaptureBacklogOwedStmt.run({ before }).changes);
27973
- }
27974
- /** Record delivery. Called only AFTER the far side has accepted the rows. */
27975
- markSynced(ids, atMs) {
27976
- this.stampAll(ids, atMs);
27977
- }
27978
- /**
27979
- * Record that a row will never be sent.
27980
- *
27981
- * Reserved for a local defect — a row that cannot be rebuilt into a valid
27982
- * payload. A row that merely failed to reach the deployment stays NULL, so it
27983
- * is retried; marking those would turn one outage into permanent data loss.
27984
- */
27985
- markSkipped(ids) {
27986
- this.stampAll(ids, SKIPPED);
27987
- }
27988
- eachInTransaction(ids, run) {
27989
- if (ids.length === 0) return;
27990
- withTransaction(
27991
- this.db,
27992
- () => {
27993
- for (const id of ids) run(id);
27994
- },
27995
- "IMMEDIATE"
27996
- );
27997
- }
27998
- stampAll(ids, value) {
27999
- if (ids.length === 0) return;
28000
- withTransaction(
28001
- this.db,
28002
- () => {
28003
- for (const id of ids) this.stampStmt.run({ at: value, id });
28004
- },
28005
- "IMMEDIATE"
28006
- );
28007
- }
28008
- /**
28009
- * Claim rows as in-flight.
28010
- *
28011
- * Advisory in exactly the sense the lease is: it records that a send is in
28012
- * progress so a surface can say so, and a lost claim costs a row showing as
28013
- * queued while it is actually being sent. It is not exclusion — the far side
28014
- * settles a duplicate on the row id.
28015
- */
28016
- claimRows(ids, atMs) {
28017
- this.eachInTransaction(ids, (id) => this.claimRowStmt.run({ at: atMs, id }));
28018
- }
28019
- /** Give back a claim without settling — the send failed, the row is queued again. */
28020
- releaseRows(ids) {
28021
- this.eachInTransaction(ids, (id) => this.releaseRowStmt.run({ id }));
28022
- }
28023
- /**
28024
- * Clear claims older than `staleBefore`, and report how many were cleared.
28025
- *
28026
- * A process killed between claiming and settling leaves rows claimed with
28027
- * nothing left to settle them. Without this they read as "sending" for ever.
28028
- */
28029
- releaseStaleClaims(staleBefore) {
28030
- return Number(this.releaseStaleClaimsStmt.run({ staleBefore }).changes);
28031
- }
28032
- /**
28033
- * Every tracked row in exactly one delivery state.
28034
- *
28035
- * Takes no boundary on purpose. The boundary answers "what should the drain
28036
- * pick up now", which is a different question from "what state is this row
28037
- * in" — and a machine that has never attached has no boundary to pass, so
28038
- * requiring one would force a caller to invent one and report the whole store
28039
- * as queued.
28040
- */
28041
- partition() {
28042
- const row = getRow(this.partitionStmt, {});
28043
- return {
28044
- queued: row?.queued ?? 0,
28045
- inProgress: row?.inProgress ?? 0,
28046
- synced: row?.synced ?? 0,
28047
- failed: row?.failed ?? 0,
28048
- total: row?.total ?? 0
28049
- };
28050
- }
28051
- /** `pending` counts only what is inside the backlog; sent and skipped are totals. */
28052
- counts(before) {
28053
- const row = getRow(
28054
- this.countsStmt,
28055
- { before }
28056
- );
28057
- const captures = getRow(this.captureSkipCountStmt);
28058
- return {
28059
- pending: row?.pending ?? 0,
28060
- sent: row?.sent ?? 0,
28061
- skipped: row?.skipped ?? 0,
28062
- capturesSkipped: captures?.skipped ?? 0
28063
- };
28064
- }
28065
- /**
28066
- * The deployment the current stamps were made against, and where its backlog
28067
- * ends.
28068
- *
28069
- * READ-ONLY. An absent row reads as an absent deployment, which is what a
28070
- * machine that has never drained is — and every writer below seeds the row
28071
- * before it needs one, so nothing depends on this creating it. Keeping the
28072
- * write off the gate path matters because the gate runs on every pass while a
28073
- * write has to take the database's write lock.
28074
- */
28075
- deployment() {
28076
- const row = getRow(
28077
- this.fingerprintStmt
28078
- );
28079
- return {
28080
- fingerprint: row?.fingerprint ?? void 0,
28081
- backlogBefore: row?.backlogBefore ?? void 0
28082
- };
28083
- }
28084
- /**
28085
- * Point the ledger at a different deployment, discarding what it recorded
28086
- * about the previous one.
28087
- *
28088
- * Delivery is a fact about ONE recipient: rows sent to the deployment a
28089
- * machine has just left are undelivered as far as the new one is concerned.
28090
- * All four in one transaction, so a crash between them cannot leave stamps
28091
- * attributed to the wrong deployment, a boundary that belongs to another, or
28092
- * a disown with no re-mark to follow it.
28093
- *
28094
- * The boundary is written HERE and only here, which is what freezes it: a
28095
- * re-attach to the SAME deployment (a key rotation) leaves the fingerprint
28096
- * unchanged, so this never runs and the backlog does not widen back over rows
28097
- * the live path has since delivered.
28098
- *
28099
- * `backfillCapturesBefore` is the caller's OWN "now" at the instant a human
28100
- * granted existing-history consent for the deployment this call is arming —
28101
- * a DIFFERENT instant from `backlogBefore`: the re-mark boundary is the GRANT
28102
- * instant, `backlogBefore` is the ATTACH instant, and the two can be far
28103
- * apart. Passed only when that grant is valid, since this method has no way
28104
- * to check consent itself and must not mark a row owed for a machine that
28105
- * never agreed to it. Applied AFTER the disown above, in the SAME
28106
- * transaction: what the disown clears is every marker below `backlogBefore`,
28107
- * which includes this deployment's OWN pre-attach rows — `aka attach` calls
28108
- * `seedCaptureBacklogOwed` at the attach instant, so every row it marks sits
28109
- * on the cleared side of that bound — and the re-mark in the same
28110
- * transaction is what puts those rows back. A crash between the two cannot
28111
- * strand the ledger disowned with nothing re-marked — the transaction either
28112
- * lands whole or not at all, and a fingerprint mismatch that has not yet
28113
- * committed re-enters this method on the very next pass. Omit it (the
28114
- * structural-only tests do) to exercise the disown in isolation.
28115
- *
28116
- * The disown is bounded by `backlogBefore`, which is what keeps it from
28117
- * touching a marker the NEW deployment's OWN live path has already set: B's
28118
- * live path can mark a capture owed from the moment `aka attach` writes the
28119
- * descriptor, before the drain's first pass ever reaches this method, and
28120
- * such a row sits at or after the bound rather than below it. What keeps the
28121
- * disown from eating THIS SAME CALL's own re-mark is the order, not the
28122
- * bound — disown runs first, re-mark second, both inside the one
28123
- * transaction above.
28124
- */
28125
- rearmFor(fingerprint, backlogBefore, backfillCapturesBefore) {
28126
- this.ensureRowStmt.run();
28127
- withTransaction(
28128
- this.db,
28129
- () => {
28130
- const previous = getRow(this.fingerprintStmt)?.fingerprint;
28131
- this.rearmStmt.run();
28132
- if (previous !== null && previous !== void 0 && previous !== fingerprint) {
28133
- this.disownCapturesStmt.run({ attachedAt: backlogBefore });
28134
- }
28135
- if (backfillCapturesBefore !== void 0) {
28136
- this.markCaptureBacklogOwedStmt.run({ before: backfillCapturesBefore });
28137
- }
28138
- this.setFingerprintStmt.run({ fingerprint, backlogBefore });
28139
- },
28140
- "IMMEDIATE"
28141
- );
28142
- }
28143
- /**
28144
- * End the attached period: hand its rows to the live path, and release the
28145
- * boundary so the next attachment can freeze a new one.
28146
- *
28147
- * WITHOUT THIS, a detach and a re-attach to the same deployment leave a window
28148
- * nothing delivers. The fingerprint is unchanged, so the boundary is never
28149
- * re-frozen and stays at the FIRST attachment — while nothing forwards at all
28150
- * during the detached period, because the machine is not attached. Rows
28151
- * recorded in that window sit after the boundary and before the re-attach, so
28152
- * neither path takes them, and the pending count reports none outstanding.
28153
- *
28154
- * Stamping the attached window is not a claim that every one of those rows
28155
- * reached the deployment — the live path drops on failure and says so
28156
- * elsewhere. It records that they were ITS to deliver, which is exactly the
28157
- * status quo: they sit outside the frozen boundary today and are equally never
28158
- * re-sent. Making it explicit is what lets the boundary move.
28159
- *
28160
- * ONE TRANSACTION, so a crash cannot release the boundary while leaving the
28161
- * window unstamped — that half-state would re-send the whole attached period
28162
- * on the next attach, which is the failure the boundary exists to prevent.
28163
- */
28164
- closeAttachedWindow(attachedAtMs, atMs) {
28165
- this.ensureRowStmt.run();
28166
- withTransaction(
28167
- this.db,
28168
- () => {
28169
- const row = getRow(this.fingerprintStmt);
28170
- const from = row?.backlogBefore ?? attachedAtMs;
28171
- this.closeWindowStmt.run({ at: atMs, attachedAt: from });
28172
- this.releaseBoundaryStmt.run();
28173
- },
28174
- "IMMEDIATE"
28175
- );
28176
- }
28177
- /**
28178
- * Freeze a boundary for the deployment already on file, KEEPING the stamps.
28179
- *
28180
- * The re-attach half of the above. Distinct from `rearmFor`, which is for a
28181
- * different deployment and therefore discards what was delivered to the old
28182
- * one: here the recipient is the same, so everything already sent to it stays
28183
- * sent.
28184
- */
28185
- freezeBoundary(backlogBefore) {
28186
- this.ensureRowStmt.run();
28187
- this.freezeBoundaryStmt.run({ backlogBefore });
28188
- }
28189
- /** Take the claim, or report that someone live already holds it. */
28190
- claim(pid, host, nowMs, staleAfterMs) {
28191
- this.ensureRowStmt.run();
28192
- let taken = false;
28193
- withTransaction(
28194
- this.db,
28195
- () => {
28196
- const result = this.claimStmt.run({
28197
- pid,
28198
- host,
28199
- now: nowMs,
28200
- staleBefore: nowMs - staleAfterMs
28201
- });
28202
- taken = result.changes === 1;
28203
- },
28204
- "IMMEDIATE"
28205
- );
28206
- return taken;
28207
- }
28208
- /** Say the holder is still alive. A no-op once the claim has moved on. */
28209
- heartbeat(pid, nowMs) {
28210
- this.heartbeatStmt.run({ now: nowMs, pid });
28211
- }
28212
- /** Give the claim up. Scoped to this holder, so a taken-over claim is left be. */
28213
- release(pid) {
28214
- this.releaseStmt.run({ pid });
28215
- }
28216
- /** Who holds the claim, if anyone. Read-only, for the same reason as above. */
28217
- lease() {
28218
- return getRow(this.leaseStmt);
28219
- }
28220
- };
28221
-
28222
28833
  // ../../packages/persistence/src/repositories/inspection-definitions.ts
28223
28834
  var SqliteInspectionDefinitionsRepository = class {
28224
28835
  constructor(db) {
@@ -28449,6 +29060,7 @@ function overlayManagedSettings(settings, managed, now = () => /* @__PURE__ */ n
28449
29060
  if (values.vaultInlineReveal !== void 0) merged.vaultInlineReveal = values.vaultInlineReveal;
28450
29061
  if (values.dataSharesInPlace !== void 0) merged.dataSharesInPlace = values.dataSharesInPlace;
28451
29062
  if (values.redactFallback !== void 0) merged.redactFallback = values.redactFallback;
29063
+ if (values.bodyRetention !== void 0) merged.bodyRetention = values.bodyRetention;
28452
29064
  if (values.vaultConsent !== void 0) {
28453
29065
  merged.vaultConsent = values.vaultConsent ? (
28454
29066
  // Keep an existing valid grant so its acknowledgedAt survives; mint one
@@ -30956,7 +31568,7 @@ var SqliteSecurityRepository = class {
30956
31568
  ELSE 0
30957
31569
  END) AS open_at_rest
30958
31570
  FROM inspection_findings f
30959
- JOIN audit_events e ON e.id = f.audit_event_id
31571
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
30960
31572
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
30961
31573
  LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
30962
31574
  ON latest.finding_key = f.finding_key
@@ -31182,7 +31794,7 @@ var SqliteSecurityRepository = class {
31182
31794
  this.db.prepare(
31183
31795
  `SELECT e.repo AS repo, count(*) AS c
31184
31796
  FROM inspection_findings f
31185
- JOIN audit_events e ON e.id = f.audit_event_id
31797
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31186
31798
  WHERE e.started_at >= :from AND e.started_at < :to
31187
31799
  AND e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
31188
31800
  AND e.repo IS NOT NULL
@@ -31306,7 +31918,7 @@ var SqliteSecurityRepository = class {
31306
31918
  d.severity AS severity,
31307
31919
  COUNT(*) AS count
31308
31920
  FROM inspection_findings f
31309
- JOIN audit_events e ON e.id = f.audit_event_id
31921
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31310
31922
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
31311
31923
  LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
31312
31924
  ON latest.finding_key = f.finding_key
@@ -31341,7 +31953,7 @@ var SqliteSecurityRepository = class {
31341
31953
  `SELECT e.started_at AS occurred_at, d.severity AS severity, f.action_taken AS action_taken,
31342
31954
  d.rule_id AS rule_id, d.category AS category
31343
31955
  FROM inspection_findings f
31344
- JOIN audit_events e ON e.id = f.audit_event_id
31956
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31345
31957
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
31346
31958
  WHERE e.started_at >= :from AND e.started_at < :to
31347
31959
  AND e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
@@ -32182,6 +32794,7 @@ function openWithPragmas(file2) {
32182
32794
  db.exec("PRAGMA journal_mode = WAL");
32183
32795
  db.exec("PRAGMA busy_timeout = 2000");
32184
32796
  db.exec("PRAGMA foreign_keys = ON");
32797
+ registerSqlFunctions(db);
32185
32798
  } catch (err) {
32186
32799
  closeQuietly(db);
32187
32800
  throw err;
@@ -32211,7 +32824,7 @@ function backupLegacyStore(db, file2) {
32211
32824
  discardStore(file2, backup);
32212
32825
  return backup;
32213
32826
  }
32214
- function openAndInitialize(file2, base) {
32827
+ function openAndInitialize(file2, base, skipTags) {
32215
32828
  let db = openWithPragmas(file2);
32216
32829
  try {
32217
32830
  if (isForeignSqliteLineage(db)) {
@@ -32221,7 +32834,7 @@ function openAndInitialize(file2, base) {
32221
32834
  `Detected an older, incompatible (tenant-bearing) ${DB_FILENAME}; backed it up to ${backup} and created a fresh store.`
32222
32835
  );
32223
32836
  }
32224
- applyMigrations(db, file2);
32837
+ applyMigrations(db, file2, { skipTags });
32225
32838
  tightenPerms(file2);
32226
32839
  const policies = new SqlitePoliciesRepository(db);
32227
32840
  const installedPacks = new SqliteInstalledPacksRepository(db, base);
@@ -32236,6 +32849,7 @@ function openAndInitialize(file2, base) {
32236
32849
  exceptions: new SqliteExceptionsRepository(db),
32237
32850
  resolutions: new SqliteResolutionsRepository(db),
32238
32851
  ruleProbeCache: new SqliteRuleProbeCacheRepository(db),
32852
+ bodyRetention: new SqliteBodyRetentionRepository(db),
32239
32853
  security: new SqliteSecurityRepository(db),
32240
32854
  detections: new SqliteDetectionsRepository(db),
32241
32855
  shares: new SqliteSharesRepository(db),
@@ -32258,7 +32872,8 @@ function openAndInitialize(file2, base) {
32258
32872
  throw err;
32259
32873
  }
32260
32874
  }
32261
- function openLocalDatabase(dir) {
32875
+ var DEFERRED_TAGS = new Set(DEFERRED_MIGRATION_TAGS);
32876
+ function openLocalDatabase(dir, options = {}) {
32262
32877
  ensureDataDirSync(dir);
32263
32878
  const file2 = join7(dir, DB_FILENAME);
32264
32879
  reapStalePartials(file2);
@@ -32270,6 +32885,7 @@ function openLocalDatabase(dir) {
32270
32885
  installedPacks,
32271
32886
  scanLedger,
32272
32887
  historySync,
32888
+ bodyRetention,
32273
32889
  secretVault,
32274
32890
  exceptions,
32275
32891
  resolutions,
@@ -32293,7 +32909,8 @@ function openLocalDatabase(dir) {
32293
32909
  // `dir` is always `<base>/data` — every caller resolves it through
32294
32910
  // `dataDir()` — so its parent is the `~/.aka` base the layout splits into
32295
32911
  // settings/ and data/, and the pack-policy floor needs both halves.
32296
- dirname2(dir)
32912
+ dirname2(dir),
32913
+ options.applyDeferredMigrations === true ? void 0 : DEFERRED_TAGS
32297
32914
  );
32298
32915
  function captureRowId(event) {
32299
32916
  return captureId(
@@ -32486,6 +33103,7 @@ function openLocalDatabase(dir) {
32486
33103
  installedPacks,
32487
33104
  scanLedger,
32488
33105
  historySync,
33106
+ bodyRetention,
32489
33107
  secretVault,
32490
33108
  exceptions,
32491
33109
  resolutions,
@@ -32526,8 +33144,35 @@ function openLocalDatabase(dir) {
32526
33144
 
32527
33145
  // ../../packages/persistence/src/egress-wire.ts
32528
33146
  import { createHash as createHash3 } from "crypto";
33147
+ var PROJECT_KEY_DIGEST_VERSION = "v2";
33148
+ var SCP_FORM = /^(?:[^@/]+@)?([^/:]+):(.+)$/;
33149
+ var DOS_DRIVE = /^[A-Za-z]:[\\/]/;
33150
+ var FILE_URL = /^file:\/\//i;
33151
+ var SCHEME_FORM = /^[a-z][a-z0-9+.-]*:\/\/(?:[^@/]+@)?([^/:]+)(?::\d+)?(\/.*)?$/i;
33152
+ var SLASH = "/".charCodeAt(0);
33153
+ var GIT_SUFFIX = ".git";
33154
+ function trimSlashes(path) {
33155
+ let start = 0;
33156
+ let end = path.length;
33157
+ while (start < end && path.charCodeAt(start) === SLASH) start += 1;
33158
+ while (end > start && path.charCodeAt(end - 1) === SLASH) end -= 1;
33159
+ return path.slice(start, end);
33160
+ }
33161
+ function canonicalGitUrl(url2) {
33162
+ const trimmed = url2.trim();
33163
+ if (DOS_DRIVE.test(trimmed) || FILE_URL.test(trimmed)) return trimmed;
33164
+ const scheme = SCHEME_FORM.exec(trimmed);
33165
+ const scp = scheme === null ? SCP_FORM.exec(trimmed) : null;
33166
+ const host = (scheme?.[1] ?? scp?.[1])?.toLowerCase();
33167
+ if (host === void 0) return trimmed;
33168
+ const path = (scheme === null ? scp?.[2] : scheme[2]) ?? "";
33169
+ const bare = trimSlashes(path);
33170
+ const cleaned = bare.endsWith(GIT_SUFFIX) ? bare.slice(0, -GIT_SUFFIX.length) : bare;
33171
+ return cleaned === "" ? host : `${host}/${cleaned}`;
33172
+ }
32529
33173
  function hashProjectKey(projectKey) {
32530
- return createHash3("sha256").update(projectKey, "utf8").digest("hex");
33174
+ const canonical = projectKey.startsWith("git:") ? `git:${canonicalGitUrl(projectKey.slice("git:".length))}` : projectKey;
33175
+ return createHash3("sha256").update(`${PROJECT_KEY_DIGEST_VERSION}:${canonical}`, "utf8").digest("hex");
32531
33176
  }
32532
33177
  function toIngestHit(hit) {
32533
33178
  return {
@@ -32714,18 +33359,50 @@ function fingerprintValue(key, raw) {
32714
33359
  return createHmac("sha256", key.material).update(raw, "utf8").digest("hex");
32715
33360
  }
32716
33361
 
33362
+ // ../../packages/persistence/src/forward-health.ts
33363
+ import { readFileSync as readFileSync7 } from "fs";
33364
+ import { join as join9 } from "path";
33365
+ var FAILURES = /* @__PURE__ */ new Set([
33366
+ "unauthorized",
33367
+ "forbidden",
33368
+ "unreachable"
33369
+ ]);
33370
+ var BREAKER_COOLDOWN_MS = 3e4;
33371
+ function parseForwardHealth(raw, nowMs) {
33372
+ try {
33373
+ const parsed2 = JSON.parse(raw);
33374
+ if (typeof parsed2 !== "object" || parsed2 === null) return null;
33375
+ const record2 = parsed2;
33376
+ const failures = typeof record2.consecutiveFailures === "number" && record2.consecutiveFailures >= 0 ? record2.consecutiveFailures : 0;
33377
+ const openedAtMs = typeof record2.openedAtMs === "number" && Number.isFinite(record2.openedAtMs) && record2.openedAtMs <= nowMs ? record2.openedAtMs : null;
33378
+ const lastFailure = typeof record2.lastFailure === "string" && FAILURES.has(record2.lastFailure) ? record2.lastFailure : null;
33379
+ return { consecutiveFailures: failures, openedAtMs, lastFailure };
33380
+ } catch {
33381
+ return null;
33382
+ }
33383
+ }
33384
+ function isForwardPaused(health, nowMs) {
33385
+ const openedAtMs = health?.openedAtMs ?? null;
33386
+ if (openedAtMs === null) return false;
33387
+ return nowMs - openedAtMs < BREAKER_COOLDOWN_MS;
33388
+ }
33389
+
32717
33390
  // ../../packages/persistence/src/history-backfill.ts
32718
33391
  import { existsSync as existsSync4 } from "fs";
32719
- import { join as join9 } from "path";
33392
+ import { join as join10 } from "path";
32720
33393
 
32721
33394
  // ../../packages/persistence/src/history-preview.ts
32722
33395
  import { existsSync as existsSync5 } from "fs";
32723
- import { join as join10 } from "path";
33396
+ import { join as join11 } from "path";
32724
33397
  import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
32725
33398
 
33399
+ // ../../packages/persistence/src/history-sync-state.ts
33400
+ import { readFileSync as readFileSync8 } from "fs";
33401
+ import { join as join12 } from "path";
33402
+
32726
33403
  // ../../packages/persistence/src/store-symlinks.ts
32727
33404
  import { existsSync as existsSync6, lstatSync as lstatSync3, readlinkSync, realpathSync, statSync as statSync4 } from "fs";
32728
- import { dirname as dirname3, join as join11, resolve } from "path";
33405
+ import { dirname as dirname3, join as join13, resolve } from "path";
32729
33406
 
32730
33407
  // ../../packages/persistence/src/vault/crypto.ts
32731
33408
  import {
@@ -32838,8 +33515,8 @@ function formatPointer(category, keyVersion, pointerId, tag) {
32838
33515
  // ../../packages/persistence/src/vault/key-provider.ts
32839
33516
  import { execFileSync } from "child_process";
32840
33517
  import { randomBytes as randomBytes2 } from "crypto";
32841
- import { chmodSync as chmodSync3, readFileSync as readFileSync7, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
32842
- import { join as join12 } from "path";
33518
+ import { chmodSync as chmodSync3, readFileSync as readFileSync9, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
33519
+ import { join as join14 } from "path";
32843
33520
  var VAULT_OCCUPANT_REASON = {
32844
33521
  symlink: "the path is a symlink; remove it so a keyring can be created",
32845
33522
  gone: "the path was occupied but holds no keyring (removed while it was being created)",
@@ -32938,7 +33615,7 @@ function claimRotationLock(lock, owner) {
32938
33615
  throw asError(err);
32939
33616
  }
32940
33617
  try {
32941
- writeFileSync3(join12(lock, LOCK_OWNER_FILE), `${owner}
33618
+ writeFileSync3(join14(lock, LOCK_OWNER_FILE), `${owner}
32942
33619
  `, { mode: DATA_FILE_MODE });
32943
33620
  return true;
32944
33621
  } catch (err) {
@@ -32947,7 +33624,7 @@ function claimRotationLock(lock, owner) {
32947
33624
  }
32948
33625
  }
32949
33626
  function acquireRotationLock(keysDir2) {
32950
- const lock = join12(keysDir2, `${VAULT_KEY_FILENAME}.lock`);
33627
+ const lock = join14(keysDir2, `${VAULT_KEY_FILENAME}.lock`);
32951
33628
  const owner = randomBytes2(16).toString("hex");
32952
33629
  if (claimRotationLock(lock, owner)) return { lock, owner };
32953
33630
  let held;
@@ -32974,7 +33651,7 @@ function acquireRotationLock(keysDir2) {
32974
33651
  }
32975
33652
  function releaseRotationLock(lease) {
32976
33653
  try {
32977
- if (readFileSync7(join12(lease.lock, LOCK_OWNER_FILE), "utf8").trim() !== lease.owner) return;
33654
+ if (readFileSync9(join14(lease.lock, LOCK_OWNER_FILE), "utf8").trim() !== lease.owner) return;
32978
33655
  } catch {
32979
33656
  return;
32980
33657
  }
@@ -32995,7 +33672,7 @@ var FileKeyProvider = class {
32995
33672
  this.#keysDir = keysDir2;
32996
33673
  }
32997
33674
  get filePath() {
32998
- return join12(this.#keysDir, VAULT_KEY_FILENAME);
33675
+ return join14(this.#keysDir, VAULT_KEY_FILENAME);
32999
33676
  }
33000
33677
  loadOrCreate() {
33001
33678
  return asAsync(() => {
@@ -33025,7 +33702,7 @@ var FileKeyProvider = class {
33025
33702
  #read() {
33026
33703
  let raw;
33027
33704
  try {
33028
- raw = readFileSync7(this.filePath, "utf8");
33705
+ raw = readFileSync9(this.filePath, "utf8");
33029
33706
  } catch (err) {
33030
33707
  if (err.code === "ENOENT") return null;
33031
33708
  throw err instanceof Error ? err : new Error(String(err));
@@ -33661,11 +34338,11 @@ var SecretVault = class {
33661
34338
 
33662
34339
  // ../../packages/persistence/src/warn-era-cap.ts
33663
34340
  import { existsSync as existsSync7, writeFileSync as writeFileSync4 } from "fs";
33664
- import { join as join13 } from "path";
34341
+ import { join as join15 } from "path";
33665
34342
  var MARKER = "warn-era-capped";
33666
34343
  function capWarnEraEnforcementOnce(db, policyMode, dataDir2) {
33667
34344
  if (policyMode !== "warn") return { capped: 0, skipped: "not-warn" };
33668
- const marker = join13(dataDir2, MARKER);
34345
+ const marker = join15(dataDir2, MARKER);
33669
34346
  if (existsSync7(marker)) return { capped: 0, skipped: "already-run" };
33670
34347
  const capped = db.policies.capCategoryActions();
33671
34348
  writeFileSync4(marker, `${new Date(Date.now()).toISOString()}
@@ -33675,7 +34352,7 @@ function capWarnEraEnforcementOnce(db, policyMode, dataDir2) {
33675
34352
 
33676
34353
  // ../../packages/plugin-sdk/src/config.ts
33677
34354
  import { existsSync as existsSync8 } from "fs";
33678
- import { join as join14 } from "path";
34355
+ import { join as join16 } from "path";
33679
34356
 
33680
34357
  // ../../packages/plugin-sdk/src/provider-env.ts
33681
34358
  var DEFAULT_ANTHROPIC_HOST = "api.anthropic.com";
@@ -33729,7 +34406,7 @@ function resolveProvider() {
33729
34406
  function loadConfig(base = defaultDataDir(), resolveProviderFn = resolveProvider) {
33730
34407
  try {
33731
34408
  ensureLayoutDirSync(base);
33732
- const settingsFile = join14(settingsDir(base), "settings.json");
34409
+ const settingsFile = join16(settingsDir(base), "settings.json");
33733
34410
  if (existsSync8(settingsFile)) tightenFile(settingsFile);
33734
34411
  } catch {
33735
34412
  }
@@ -33753,9 +34430,9 @@ function resolveProviderSafe(resolveProviderFn) {
33753
34430
  }
33754
34431
 
33755
34432
  // ../../packages/plugin-sdk/src/config-inventory.ts
33756
- import { readdirSync as readdirSync2, readFileSync as readFileSync9, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
34433
+ import { readdirSync as readdirSync2, readFileSync as readFileSync11, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
33757
34434
  import { homedir as homedir2 } from "os";
33758
- import { basename as basename3, join as join16 } from "path";
34435
+ import { basename as basename3, join as join18 } from "path";
33759
34436
 
33760
34437
  // ../../packages/detections/src/egress/registry.ts
33761
34438
  var EXTRACTOR_VERSION = "1";
@@ -36844,8 +37521,8 @@ function bundledDetections() {
36844
37521
  }
36845
37522
 
36846
37523
  // ../../packages/plugin-sdk/src/repo.ts
36847
- import { existsSync as existsSync9, readFileSync as readFileSync8, statSync as statSync6 } from "fs";
36848
- import { basename as basename2, dirname as dirname4, isAbsolute, join as join15, sep as sep2 } from "path";
37524
+ import { existsSync as existsSync9, readFileSync as readFileSync10, statSync as statSync6 } from "fs";
37525
+ import { basename as basename2, dirname as dirname4, isAbsolute, join as join17, sep as sep2 } from "path";
36849
37526
  function resolveRepo(cwd) {
36850
37527
  try {
36851
37528
  const root = findGitRoot(cwd);
@@ -36867,36 +37544,36 @@ function resolveWorktreeRoot(cwd) {
36867
37544
  function findGitRoot(start) {
36868
37545
  let dir = start;
36869
37546
  for (; ; ) {
36870
- if (existsSync9(join15(dir, ".git"))) return dir;
37547
+ if (existsSync9(join17(dir, ".git"))) return dir;
36871
37548
  const parent = dirname4(dir);
36872
37549
  if (parent === dir) return void 0;
36873
37550
  dir = parent;
36874
37551
  }
36875
37552
  }
36876
37553
  function resolveGitContext(root) {
36877
- const dotGit = join15(root, ".git");
37554
+ const dotGit = join17(root, ".git");
36878
37555
  try {
36879
37556
  if (statSync6(dotGit).isDirectory()) {
36880
- return { configPath: join15(dotGit, "config"), headRoot: root };
37557
+ return { configPath: join17(dotGit, "config"), headRoot: root };
36881
37558
  }
36882
37559
  } catch {
36883
37560
  return void 0;
36884
37561
  }
36885
37562
  const target = /^gitdir:\s*(.+?)\s*$/m.exec(safeRead(dotGit) ?? "")?.[1];
36886
37563
  if (!target) return void 0;
36887
- const gitdir = isAbsolute(target) ? target : join15(root, target);
36888
- if (existsSync9(join15(gitdir, "config"))) {
36889
- return { configPath: join15(gitdir, "config"), headRoot: root };
37564
+ const gitdir = isAbsolute(target) ? target : join17(root, target);
37565
+ if (existsSync9(join17(gitdir, "config"))) {
37566
+ return { configPath: join17(gitdir, "config"), headRoot: root };
36890
37567
  }
36891
- const commonRaw = safeRead(join15(gitdir, "commondir"))?.trim();
37568
+ const commonRaw = safeRead(join17(gitdir, "commondir"))?.trim();
36892
37569
  if (!commonRaw) return void 0;
36893
- const commonGitDir = isAbsolute(commonRaw) ? commonRaw : join15(gitdir, commonRaw);
37570
+ const commonGitDir = isAbsolute(commonRaw) ? commonRaw : join17(gitdir, commonRaw);
36894
37571
  const headRoot = basename2(commonGitDir) === ".git" ? dirname4(commonGitDir) : root;
36895
- return { configPath: join15(commonGitDir, "config"), headRoot };
37572
+ return { configPath: join17(commonGitDir, "config"), headRoot };
36896
37573
  }
36897
37574
  function safeRead(path) {
36898
37575
  try {
36899
- return readFileSync8(path, "utf8");
37576
+ return readFileSync10(path, "utf8");
36900
37577
  } catch {
36901
37578
  return void 0;
36902
37579
  }
@@ -37440,8 +38117,8 @@ function createGuardedScanner(partition, gateway, opts) {
37440
38117
  }
37441
38118
 
37442
38119
  // ../../packages/plugin-sdk/src/host-floor.ts
37443
- import { readFileSync as readFileSync11 } from "fs";
37444
- import { join as join18 } from "path";
38120
+ import { readFileSync as readFileSync13 } from "fs";
38121
+ import { join as join20 } from "path";
37445
38122
 
37446
38123
  // ../../packages/plugin-sdk/src/model-governance.ts
37447
38124
  import {
@@ -37449,11 +38126,11 @@ import {
37449
38126
  fstatSync,
37450
38127
  mkdirSync as mkdirSync2,
37451
38128
  openSync as openSync2,
37452
- readFileSync as readFileSync10,
38129
+ readFileSync as readFileSync12,
37453
38130
  readSync,
37454
38131
  writeFileSync as writeFileSync5
37455
38132
  } from "fs";
37456
- import { join as join17 } from "path";
38133
+ import { join as join19 } from "path";
37457
38134
  var TAIL_BYTES = 256 * 1024;
37458
38135
 
37459
38136
  // ../../packages/plugin-sdk/src/host-floor.ts
@@ -37476,15 +38153,15 @@ var HOST_FLOORS = {
37476
38153
 
37477
38154
  // ../../packages/plugin-sdk/src/ignore-layers.ts
37478
38155
  var import_ignore = __toESM(require_ignore(), 1);
37479
- import { readFileSync as readFileSync12 } from "fs";
37480
- import { join as join19 } from "path";
38156
+ import { readFileSync as readFileSync14 } from "fs";
38157
+ import { join as join21 } from "path";
37481
38158
 
37482
38159
  // ../../packages/plugin-sdk/src/inventory-resolver.ts
37483
38160
  import { arch, hostname as hostname4, platform, release } from "os";
37484
38161
 
37485
38162
  // ../../packages/plugin-sdk/src/nudge.ts
37486
- import { mkdirSync as mkdirSync3, readFileSync as readFileSync13, writeFileSync as writeFileSync6 } from "fs";
37487
- import { join as join20 } from "path";
38163
+ import { mkdirSync as mkdirSync3, readFileSync as readFileSync15, writeFileSync as writeFileSync6 } from "fs";
38164
+ import { join as join22 } from "path";
37488
38165
 
37489
38166
  // ../../packages/plugin-sdk/src/paths.ts
37490
38167
  import { readdirSync as readdirSync3, realpathSync as realpathSync3 } from "fs";
@@ -37537,7 +38214,7 @@ function applyCategoryPosture(posture, repo, mode = "fill-gaps") {
37537
38214
 
37538
38215
  // ../../packages/plugin-sdk/src/project-files.ts
37539
38216
  import { existsSync as existsSync11, readdirSync as readdirSync4 } from "fs";
37540
- import { basename as basename5, join as join21 } from "path";
38217
+ import { basename as basename5, join as join23 } from "path";
37541
38218
 
37542
38219
  // ../../packages/plugin-sdk/src/provider-env-antigravity.ts
37543
38220
  var optionalBaseUrl2 = external_exports.preprocess((v) => {
@@ -37622,7 +38299,7 @@ function createPluginRuntime(gateway, settings, opts) {
37622
38299
  bundlesPacked = true;
37623
38300
  }
37624
38301
  const policyMode = settings.policy;
37625
- const redactFallback = settings.redactFallback;
38302
+ let redactFallback = settings.redactFallback;
37626
38303
  const dataDir2 = opts?.dataDir;
37627
38304
  let rules = [];
37628
38305
  let scanner;
@@ -37666,6 +38343,7 @@ function createPluginRuntime(gateway, settings, opts) {
37666
38343
  rules = [...verified, ...unverified];
37667
38344
  scanner = createGuardedScanner({ verified, unverified }, gateway, opts?.scanIsolation);
37668
38345
  bundleExceptions = bundle.exceptions ?? [];
38346
+ redactFallback = strongerRedactFallback(settings.redactFallback, bundle.redactFallback);
37669
38347
  initialized = true;
37670
38348
  }
37671
38349
  let cachedKey;
@@ -37704,11 +38382,13 @@ function createPluginRuntime(gateway, settings, opts) {
37704
38382
  function decide(findings, text, excepted, rewritable = true) {
37705
38383
  if (findings.length === 0) return { action: "log", text, findings: [] };
37706
38384
  const actionFor = (finding) => actionForFinding(finding, excepted, rewritable);
38385
+ const degradedActions = rewritable ? [] : findings.filter((f) => actionForFinding(f, excepted, true) === "redact").map(actionFor);
38386
+ const degraded = degradedActions.length === 0 ? {} : { redactDegradedTo: degradedActions.reduce((a, b) => strongerAction(a, b)) };
37707
38387
  let worst = "log";
37708
38388
  for (const finding of findings) {
37709
38389
  worst = strongerAction(worst, actionFor(finding));
37710
38390
  }
37711
- if (worst === "block") return { action: "block", text: null, findings };
38391
+ if (worst === "block") return { action: "block", text: null, findings, ...degraded };
37712
38392
  if (worst === "redact") {
37713
38393
  const redactFindings = findings.filter((f) => actionFor(f) === "redact");
37714
38394
  const reversibleFindings = redactFindings.filter((f) => resolver.isReversible(f.ruleId));
@@ -37718,9 +38398,13 @@ function createPluginRuntime(gateway, settings, opts) {
37718
38398
  findings,
37719
38399
  enforcedFindings: redactFindings,
37720
38400
  reversibleFindings
38401
+ // No `degraded` here, and it is not an omission: `rewritable` is per
38402
+ // CAPTURE, so on an unrewritable field every redact has already become
38403
+ // the fallback and this branch is unreachable. Spreading it would read
38404
+ // as a case that can happen.
37721
38405
  };
37722
38406
  }
37723
- return { action: worst, text, findings };
38407
+ return { action: worst, text, findings, ...degraded };
37724
38408
  }
37725
38409
  function fingerprintOf(key, finding, cache) {
37726
38410
  let fp = cache.get(finding);
@@ -37849,8 +38533,8 @@ function createPluginRuntime(gateway, settings, opts) {
37849
38533
  };
37850
38534
  }
37851
38535
  }
37852
- async function processText(text, context) {
37853
- return (await evaluate(text, context, {})).decision;
38536
+ async function processText(text, context, opts2 = {}) {
38537
+ return (await evaluate(text, context, {}, opts2.rewritable)).decision;
37854
38538
  }
37855
38539
  async function capture(input2, opts2 = {}) {
37856
38540
  const timingStartedAt = input2.occurredAt === void 0 ? startTiming() : void 0;
@@ -37873,10 +38557,12 @@ function createPluginRuntime(gateway, settings, opts) {
37873
38557
  );
37874
38558
  const storedContent = maskedFindings.length > 0 ? redact(input2.text, maskedFindings) : input2.text;
37875
38559
  const inspectionMs = elapsedMs(timingStartedAt);
37876
- const metadata = exceptionIds.length > 0 || inspectionMs !== void 0 ? {
38560
+ const redactDegradedTo = decision.redactDegradedTo;
38561
+ const metadata = exceptionIds.length > 0 || inspectionMs !== void 0 || redactDegradedTo !== void 0 ? {
37877
38562
  ...input2.metadata,
37878
38563
  ...exceptionIds.length > 0 ? { exceptionIds } : {},
37879
- ...inspectionMs !== void 0 ? { inspectionMs } : {}
38564
+ ...inspectionMs !== void 0 ? { inspectionMs } : {},
38565
+ ...redactDegradedTo !== void 0 ? { redactDegradedTo } : {}
37880
38566
  } : input2.metadata;
37881
38567
  const event = buildIngestEvent({
37882
38568
  kind: input2.kind,
@@ -37948,7 +38634,7 @@ var THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1e3;
37948
38634
 
37949
38635
  // ../../packages/plugin-sdk/src/throttle.ts
37950
38636
  import { mkdirSync as mkdirSync4, statSync as statSync8, writeFileSync as writeFileSync7 } from "fs";
37951
- import { join as join22 } from "path";
38637
+ import { join as join24 } from "path";
37952
38638
 
37953
38639
  // ../../packages/plugin-sdk/src/tokenize.ts
37954
38640
  function redactedPlaceholder(category) {
@@ -38304,7 +38990,7 @@ function routeRemediationOption(option, handlers) {
38304
38990
 
38305
38991
  // ../../packages/setup-wizard/src/remediation/rotation-checklist.ts
38306
38992
  import { writeFileSync as writeFileSync8 } from "fs";
38307
- import { join as join23 } from "path";
38993
+ import { join as join25 } from "path";
38308
38994
  var GENERIC_CONSOLE_PATH = "rotate via the provider's own console";
38309
38995
  var CONSOLE_PATHS = {
38310
38996
  anthropic: "console.anthropic.com \u2192 Settings \u2192 API keys",
@@ -38404,7 +39090,7 @@ function generateRotationChecklist(input2) {
38404
39090
  try {
38405
39091
  const target = resolveRotationChecklistTarget(input2.cwd);
38406
39092
  targetDirectory = target.directory;
38407
- const filePath = join23(target.directory, "rotation-checklist.md");
39093
+ const filePath = join25(target.directory, "rotation-checklist.md");
38408
39094
  writeRotationChecklist(input2.entries, target.directory);
38409
39095
  return {
38410
39096
  status: "written",
@@ -38515,9 +39201,9 @@ var RANK = Object.fromEntries(
38515
39201
  );
38516
39202
 
38517
39203
  // ../../packages/setup-wizard/src/triage/plan-file.ts
38518
- import { mkdtempSync, readFileSync as readFileSync14, rmdirSync, rmSync as rmSync7, writeFileSync as writeFileSync9 } from "fs";
39204
+ import { mkdtempSync, readFileSync as readFileSync16, rmdirSync, rmSync as rmSync7, writeFileSync as writeFileSync9 } from "fs";
38519
39205
  import { tmpdir } from "os";
38520
- import { basename as basename6, dirname as dirname6, join as join24 } from "path";
39206
+ import { basename as basename6, dirname as dirname6, join as join26 } from "path";
38521
39207
  var SuppressionEntrySchema = external_exports.object({
38522
39208
  ruleId: external_exports.string(),
38523
39209
  category: DetectionCategory,
@@ -38906,10 +39592,10 @@ function parsed(schema, body, route2) {
38906
39592
  }
38907
39593
  function withoutTrailingSlashes(endpoint) {
38908
39594
  let end = endpoint.length;
38909
- while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH) end -= 1;
39595
+ while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH2) end -= 1;
38910
39596
  return endpoint.slice(0, end);
38911
39597
  }
38912
- var SLASH = "/".charCodeAt(0);
39598
+ var SLASH2 = "/".charCodeAt(0);
38913
39599
  function createRemoteClient(options) {
38914
39600
  const base = withoutTrailingSlashes(options.endpoint);
38915
39601
  const url2 = (route2) => `${base}${route2}`;
@@ -39091,11 +39777,11 @@ function withTimeout(promise2, ms) {
39091
39777
  }
39092
39778
 
39093
39779
  // ../../packages/plugin-runtime/src/attached/forward-drops.ts
39094
- import { readFileSync as readFileSync15 } from "fs";
39095
- import { join as join25 } from "path";
39780
+ import { readFileSync as readFileSync17 } from "fs";
39781
+ import { join as join27 } from "path";
39096
39782
  var FORWARD_DROPS_FILENAME = ATTACHED_FORWARD_DROPS_FILENAME;
39097
39783
  function forwardDropsPath(dataDir2) {
39098
- return join25(dataDir2, FORWARD_DROPS_FILENAME);
39784
+ return join27(dataDir2, FORWARD_DROPS_FILENAME);
39099
39785
  }
39100
39786
  function recordForwardDrops(dataDir2, count, nowMs) {
39101
39787
  if (count <= 0) return;
@@ -39113,7 +39799,7 @@ function recordForwardDrops(dataDir2, count, nowMs) {
39113
39799
  }
39114
39800
  function readForwardDrops(dataDir2) {
39115
39801
  try {
39116
- const parsed2 = JSON.parse(readFileSync15(forwardDropsPath(dataDir2), "utf8"));
39802
+ const parsed2 = JSON.parse(readFileSync17(forwardDropsPath(dataDir2), "utf8"));
39117
39803
  if (typeof parsed2 !== "object" || parsed2 === null) return null;
39118
39804
  const record2 = parsed2;
39119
39805
  if (typeof record2.droppedForwards !== "number" || !Number.isFinite(record2.droppedForwards)) {
@@ -39131,9 +39817,8 @@ function readForwardDrops(dataDir2) {
39131
39817
 
39132
39818
  // ../../packages/plugin-runtime/src/attached/forward-policy.ts
39133
39819
  import { randomUUID as randomUUID15 } from "crypto";
39134
- import { readFileSync as readFileSync16 } from "fs";
39135
39820
  import { readFile, rename, writeFile } from "fs/promises";
39136
- import { join as join26 } from "path";
39821
+ import { join as join28 } from "path";
39137
39822
  function isInvalidRequest(err) {
39138
39823
  return typeof err === "object" && err !== null && err.name === "RemoteRequestInvalid";
39139
39824
  }
@@ -39147,31 +39832,12 @@ function isServerRejection(err) {
39147
39832
  var FORWARD_BUDGET_MS = 1500;
39148
39833
  var DECISION_PATH_BUDGET_MS = 800;
39149
39834
  var BREAKER_FAILURE_THRESHOLD = 3;
39150
- var BREAKER_COOLDOWN_MS = 3e4;
39151
39835
  var CLOSED = { consecutiveFailures: 0, openedAtMs: null, lastFailure: null };
39152
- var FAILURES = /* @__PURE__ */ new Set([
39153
- "unauthorized",
39154
- "forbidden",
39155
- "unreachable"
39156
- ]);
39157
39836
  var FORWARD_STATE_FILENAME = ATTACHED_FORWARD_STATE_FILENAME;
39158
39837
  var STATE_FILENAME = FORWARD_STATE_FILENAME;
39159
- function parseBreakerState(raw, nowMs) {
39160
- try {
39161
- const parsed2 = JSON.parse(raw);
39162
- if (typeof parsed2 !== "object" || parsed2 === null) return null;
39163
- const record2 = parsed2;
39164
- const failures = typeof record2.consecutiveFailures === "number" && record2.consecutiveFailures >= 0 ? record2.consecutiveFailures : 0;
39165
- const openedAtMs = typeof record2.openedAtMs === "number" && Number.isFinite(record2.openedAtMs) && record2.openedAtMs <= nowMs ? record2.openedAtMs : null;
39166
- const lastFailure = typeof record2.lastFailure === "string" && FAILURES.has(record2.lastFailure) ? record2.lastFailure : null;
39167
- return { consecutiveFailures: failures, openedAtMs, lastFailure };
39168
- } catch {
39169
- return null;
39170
- }
39171
- }
39172
39838
  function createForwardPolicy(deps) {
39173
39839
  const now = deps.now ?? (() => Date.now());
39174
- const file2 = join26(deps.dir, STATE_FILENAME);
39840
+ const file2 = join28(deps.dir, STATE_FILENAME);
39175
39841
  let state = null;
39176
39842
  let loading = null;
39177
39843
  async function readState() {
@@ -39181,7 +39847,7 @@ function createForwardPolicy(deps) {
39181
39847
  } catch {
39182
39848
  return { ...CLOSED };
39183
39849
  }
39184
- return parseBreakerState(raw, now()) ?? { ...CLOSED };
39850
+ return parseForwardHealth(raw, now()) ?? { ...CLOSED };
39185
39851
  }
39186
39852
  async function load() {
39187
39853
  if (state !== null) return state;
@@ -39227,7 +39893,7 @@ function createForwardPolicy(deps) {
39227
39893
  };
39228
39894
  const at = now();
39229
39895
  if (current.openedAtMs !== null) {
39230
- if (at - current.openedAtMs < BREAKER_COOLDOWN_MS) {
39896
+ if (isForwardPaused(current, at)) {
39231
39897
  return { ok: false, reason: "breaker-open" };
39232
39898
  }
39233
39899
  await persist({
@@ -39764,7 +40430,18 @@ var AttachedDataGateway = class {
39764
40430
  // and the spread above would otherwise drop the field silently — which is
39765
40431
  // exactly what it did, leaving the whole control inert on every device
39766
40432
  // while every test around it stayed green.
39767
- prohibitedModels: cached2.prohibitedModels
40433
+ prohibitedModels: cached2.prohibitedModels,
40434
+ // NAMED for the same reason as the line above, and it is the same defect
40435
+ // if it is not: `...local` above spreads the DEVICE's bundle, so a field
40436
+ // only the cache carries is dropped in silence. That is what left
40437
+ // `prohibitedModels` inert on every attached device with every test
40438
+ // around it green.
40439
+ //
40440
+ // Taken from the cache rather than merged here, because merging it needs
40441
+ // the device's own SETTING — which is not a bundle field and is not in
40442
+ // scope at this seam. The runtime does that merge, raise-only, where both
40443
+ // values are in hand (createPluginRuntime's ensureInitialized).
40444
+ redactFallback: cached2.redactFallback
39768
40445
  // ALSO HONOURED FROM THE CACHE, and not a bundle field at all: each
39769
40446
  // merged policy's own `provenance`. `mergeRaiseOnly` spreads the policies
39770
40447
  // it emits, so an 'authored' policy arriving from the control plane
@@ -39892,10 +40569,6 @@ function toolAuditEvent(input2) {
39892
40569
  };
39893
40570
  }
39894
40571
 
39895
- // ../../packages/plugin-runtime/src/attached/history-state.ts
39896
- import { readFileSync as readFileSync17 } from "fs";
39897
- import { join as join27 } from "path";
39898
-
39899
40572
  // ../../packages/plugin-runtime/src/attached/history-sync.ts
39900
40573
  import { createHash as createHash6 } from "crypto";
39901
40574
  import { hostname as hostname5 } from "os";
@@ -39904,6 +40577,10 @@ import { hostname as hostname5 } from "os";
39904
40577
  var CORRELATION_ID = EventMetadata.shape.correlationId;
39905
40578
  var TRACE_ID = EventMetadata.shape.traceId;
39906
40579
  var EXCEPTION_ID = EventMetadata.shape.exceptionIds.unwrap().element;
40580
+ var REDACT_DEGRADED_TO = EventMetadata.shape.redactDegradedTo.unwrap();
40581
+
40582
+ // ../../packages/plugin-runtime/src/attached/history-sync.ts
40583
+ var CAPTURE_BATCH_BYTES = 1024 * 1024;
39907
40584
 
39908
40585
  // ../../packages/plugin-runtime/src/attached/history-sync-trigger.ts
39909
40586
  import { spawn } from "child_process";
@@ -39930,7 +40607,7 @@ function createPluginBlock(build, policyStore) {
39930
40607
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
39931
40608
  import { randomUUID as randomUUID16 } from "crypto";
39932
40609
  import { readFile as readFile2, rm, writeFile as writeFile2 } from "fs/promises";
39933
- import { join as join28 } from "path";
40610
+ import { join as join29 } from "path";
39934
40611
 
39935
40612
  // ../../packages/plugin-runtime/src/attached/atomic-publish.ts
39936
40613
  import { rename as rename2 } from "fs/promises";
@@ -39954,7 +40631,7 @@ async function publishByRename(tmp, file2, move = rename2) {
39954
40631
 
39955
40632
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
39956
40633
  function createPolicyStore(dir = dataDir()) {
39957
- const file2 = join28(dir, "policy-cache.json");
40634
+ const file2 = join29(dir, "policy-cache.json");
39958
40635
  async function read() {
39959
40636
  try {
39960
40637
  const raw = await readFile2(file2, "utf8");
@@ -40185,11 +40862,11 @@ function readStorePosture(dbPath2) {
40185
40862
  // ../../packages/plugin-runtime/src/attached/posture-store.ts
40186
40863
  import { randomUUID as randomUUID17 } from "crypto";
40187
40864
  import { readFile as readFile3, rm as rm2, writeFile as writeFile3 } from "fs/promises";
40188
- import { join as join29 } from "path";
40865
+ import { join as join30 } from "path";
40189
40866
  var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
40190
40867
  function createPostureStore(dir = settingsDir(), legacyDir) {
40191
- const file2 = join29(dir, "posture-state.json");
40192
- const legacyFile = legacyDir === void 0 ? null : join29(legacyDir, "posture-state.json");
40868
+ const file2 = join30(dir, "posture-state.json");
40869
+ const legacyFile = legacyDir === void 0 ? null : join30(legacyDir, "posture-state.json");
40193
40870
  async function persist(state) {
40194
40871
  await ensureDataDir(dir);
40195
40872
  const tmp = `${file2}.${randomUUID17()}.tmp`;
@@ -40258,7 +40935,7 @@ function createPostureStore(dir = settingsDir(), legacyDir) {
40258
40935
 
40259
40936
  // ../../packages/plugin-runtime/src/attached/sync-state.ts
40260
40937
  import { readFileSync as readFileSync19 } from "fs";
40261
- import { join as join30 } from "path";
40938
+ import { join as join31 } from "path";
40262
40939
 
40263
40940
  // ../../packages/plugin-runtime/src/attached/status.ts
40264
40941
  var REFUSAL_LINES = {
@@ -40279,6 +40956,14 @@ import { spawn as spawn2 } from "child_process";
40279
40956
  import { fileURLToPath as fileURLToPath4 } from "url";
40280
40957
  var SYNC_THROTTLE_MS = 15 * 60 * 1e3;
40281
40958
 
40959
+ // ../../packages/plugin-runtime/src/content-retention-pass.ts
40960
+ var MAX_ROWS_PER_SWEEP = 50 * 1e3;
40961
+
40962
+ // ../../packages/plugin-runtime/src/content-retention-trigger.ts
40963
+ import { spawn as spawn3 } from "child_process";
40964
+ import { fileURLToPath as fileURLToPath5 } from "url";
40965
+ var CONTENT_RETENTION_THROTTLE_MS = 60 * 60 * 1e3;
40966
+
40282
40967
  // ../../packages/plugin-runtime/src/attached/factory.ts
40283
40968
  import { hostname as hostname6 } from "os";
40284
40969
 
@@ -40731,9 +41416,9 @@ var EXCEPTION_RETENTION_MS = 90 * 24 * 60 * 60 * 1e3;
40731
41416
  // src/history/transcripts.ts
40732
41417
  import { readdirSync as readdirSync6, readFileSync as readFileSync20 } from "fs";
40733
41418
  import { homedir as homedir3 } from "os";
40734
- import { join as join31 } from "path";
41419
+ import { join as join32 } from "path";
40735
41420
  function transcriptsDir(home) {
40736
- return join31(home ?? homedir3(), ".claude", "projects");
41421
+ return join32(home ?? homedir3(), ".claude", "projects");
40737
41422
  }
40738
41423
  var DAY_MS5 = 24 * 60 * 60 * 1e3;
40739
41424
 
@@ -40748,7 +41433,7 @@ import {
40748
41433
  statSync as statSync10,
40749
41434
  writeFileSync as writeFileSync10
40750
41435
  } from "fs";
40751
- import { basename as basename7, dirname as dirname7, isAbsolute as isAbsolute2, join as join32, relative, resolve as resolve2 } from "path";
41436
+ import { basename as basename7, dirname as dirname7, isAbsolute as isAbsolute2, join as join33, relative, resolve as resolve2 } from "path";
40752
41437
  var REDACTED_PLACEHOLDER = "[REDACTED:SECRET]";
40753
41438
  var REPLACE_PATTERN_SEQUENCE = /\$[$&`'<0-9]/;
40754
41439
  function replacementFor(rawValue, replacements) {
@@ -40807,7 +41492,7 @@ function sweepStrandedTemps(realPath) {
40807
41492
  const pid = Number(pidPart);
40808
41493
  if (pid !== process.pid && isProcessAlive(pid)) continue;
40809
41494
  try {
40810
- const stranded = join32(dir, name);
41495
+ const stranded = join33(dir, name);
40811
41496
  if (!lstatSync4(stranded).isFile()) continue;
40812
41497
  rmSync8(stranded, { force: true });
40813
41498
  } catch {
@@ -41118,7 +41803,7 @@ async function route(frameText, rawOption, rawPosture) {
41118
41803
  break;
41119
41804
  }
41120
41805
  }
41121
- if (process.argv[1] && fileURLToPath5(import.meta.url) === process.argv[1]) {
41806
+ if (process.argv[1] && fileURLToPath6(import.meta.url) === process.argv[1]) {
41122
41807
  try {
41123
41808
  const argv = process.argv.slice(2);
41124
41809
  const optionIndex = argv.indexOf("--option");