@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
  // ../../packages/plugin-sdk/src/config.ts
495
495
  import { existsSync as existsSync8 } from "fs";
496
- import { join as join14 } from "path";
496
+ import { join as join16 } from "path";
497
497
 
498
498
  // ../../packages/persistence/src/attached-derived.ts
499
499
  import { rmSync } from "fs";
@@ -506,6 +506,14 @@ var ATTACHED_FORWARD_DROPS_FILENAME = "attached-forward-drops.json";
506
506
  import { chmodSync as chmodSync2, lstatSync as lstatSync2, readFileSync, rmSync as rmSync3, statSync } from "fs";
507
507
  import { join as join2 } from "path";
508
508
 
509
+ // ../../packages/schema/src/drizzle/deferred-migrations.ts
510
+ var DEFERRED_MIGRATION_TAGS = [
511
+ "0031_audit_capture_by_time_index",
512
+ "0032_audit_capture_by_id_index",
513
+ "0033_audit_capture_location_index",
514
+ "0034_findings_read_indexes"
515
+ ];
516
+
509
517
  // ../../packages/schema/src/drizzle/sqlite-ddl.ts
510
518
  var SQLITE_MIGRATIONS = [
511
519
  {
@@ -623,6 +631,30 @@ var SQLITE_MIGRATIONS = [
623
631
  {
624
632
  tag: "0028_activity_session_probe_indexes",
625
633
  sql: "CREATE INDEX `idx_audit_session_prompt` ON `audit_events` (`root_session_id`) WHERE event_type = 'prompt';--> statement-breakpoint\nCREATE INDEX `idx_audit_session_share` ON `audit_events` (`root_session_id`) WHERE event_type = 'share';--> statement-breakpoint\nCREATE INDEX `idx_audit_ended_at` ON `audit_events` (`ended_at`,`root_session_id`) WHERE ended_at IS NOT NULL;--> statement-breakpoint\nCREATE INDEX `idx_audit_session_ended` ON `audit_events` (`root_session_id`,`ended_at`) WHERE ended_at IS NOT NULL;--> statement-breakpoint\n-- Expression index for the activity list's turns rollup: a live-captured\n-- session's turns are the DISTINCT `run_key` across its `llm_call` leaves, and\n-- carrying the extracted key in the index answers that count from the index\n-- alone instead of parsing every leaf's attribute bag. Written by hand, as\n-- 0013's `idx_audit_code_change_path` was: drizzle-kit cannot emit an\n-- expression containing a comma, so this index is not declared in sqlite.ts.\nCREATE INDEX `idx_audit_session_run_key` ON `audit_events` (`root_session_id`, json_extract(`attributes`, '$.run_key')) WHERE `event_type` = 'llm_call';\n"
634
+ },
635
+ {
636
+ tag: "0029_audit_capture_rollup_index",
637
+ sql: "CREATE INDEX `idx_audit_capture_rollup` ON `audit_events` (`event_type`,`started_at`,`repo`,`id`) WHERE event_type IN ('prompt','response','code_change','tool_use');"
638
+ },
639
+ {
640
+ tag: "0030_audit_content_expiry",
641
+ sql: "ALTER TABLE `audit_events` ADD `content_expired_at` integer;--> statement-breakpoint\nCREATE INDEX `idx_audit_expirable_body` ON `audit_events` (`started_at`) WHERE content IS NOT NULL;"
642
+ },
643
+ {
644
+ tag: "0031_audit_capture_by_time_index",
645
+ sql: "CREATE INDEX `idx_audit_capture_by_time` ON `audit_events` (`started_at`,`id`,`event_type`,`root_session_id`,`source_tool`,`repo`,`file_path`,`tool_name`) WHERE event_type IN ('prompt','response','code_change','tool_use');"
646
+ },
647
+ {
648
+ tag: "0032_audit_capture_by_id_index",
649
+ sql: "CREATE INDEX `idx_audit_capture_by_id` ON `audit_events` (`id`,`started_at`,`event_type`,`root_session_id`,`source_tool`,`repo`,`file_path`,`tool_name`) WHERE event_type IN ('prompt','response','code_change','tool_use');"
650
+ },
651
+ {
652
+ tag: "0033_audit_capture_location_index",
653
+ sql: "CREATE INDEX `idx_audit_capture_location` ON `audit_events` (`repo`,`file_path`,`started_at`,`id`,`event_type`) WHERE event_type IN ('prompt','response','code_change','tool_use');"
654
+ },
655
+ {
656
+ tag: "0034_findings_read_indexes",
657
+ sql: "CREATE INDEX `idx_inspection_definitions_rule` ON `inspection_definitions` (`rule_id`,`severity`,`category`);--> statement-breakpoint\nCREATE INDEX `idx_inspection_findings_def` ON `inspection_findings` (`inspection_definition_id`,`audit_event_id`);--> statement-breakpoint\nCREATE INDEX `idx_inspection_findings_event_cover` ON `inspection_findings` (`audit_event_id`,`inspection_definition_id`,`action_taken`,`finding_key`,`id`);"
626
658
  }
627
659
  ];
628
660
 
@@ -20623,7 +20655,7 @@ var TOOL_TO_HARNESS = {
20623
20655
  [SOURCE_TOOL.ClaudeAi]: HARNESS.ClaudeAi
20624
20656
  };
20625
20657
  function harnessFromTool(tool) {
20626
- return TOOL_TO_HARNESS[tool] ?? tool;
20658
+ return (Object.hasOwn(TOOL_TO_HARNESS, tool) ? TOOL_TO_HARNESS[tool] : void 0) ?? tool;
20627
20659
  }
20628
20660
 
20629
20661
  // ../../packages/schema/src/zod/finding.ts
@@ -20673,6 +20705,15 @@ var FindingCategory = external_exports.enum([
20673
20705
  ]).meta({ id: "FindingCategory" });
20674
20706
  var FindingOrigin = external_exports.enum(["in-flight", "at-rest"]).meta({ id: "FindingOrigin" });
20675
20707
  var FindingStatus = external_exports.enum(["open", "handled", "resolved", "dismissed"]).meta({ id: "FindingStatus" });
20708
+ var SyncFailureReason = external_exports.enum(["deployment_refused", "payload_invalid", "detached_undelivered"]).meta({ id: "SyncFailureReason" });
20709
+ var FindingDeliveryState = external_exports.enum(["sent", "queued", "not_sent", "never_offered", "local_scan"]).meta({ id: "FindingDeliveryState" });
20710
+ var FindingDelivery = external_exports.object({
20711
+ state: FindingDeliveryState,
20712
+ // The delivery time for `sent`; the failure time for `not_sent` when recorded.
20713
+ at: external_exports.iso.datetime().optional(),
20714
+ // Only on `not_sent`, and only when a known reason was recorded.
20715
+ reason: SyncFailureReason.optional()
20716
+ }).meta({ id: "FindingDelivery" });
20676
20717
  var ResolutionMethod = external_exports.enum([
20677
20718
  "enforced-in-flight",
20678
20719
  "fixed-at-source",
@@ -20729,7 +20770,10 @@ var FindingInstance = external_exports.object({
20729
20770
  // The session that event belongs to, when it has one — the seam a
20730
20771
  // per-instance "view session" link needs. Absent for events captured
20731
20772
  // outside a session.
20732
- sessionId: external_exports.string().optional()
20773
+ sessionId: external_exports.string().optional(),
20774
+ // The delivery state of the event above (see FindingDelivery). Optional so
20775
+ // readers that do not project it stay valid.
20776
+ delivery: FindingDelivery.optional()
20733
20777
  }).meta({ id: "FindingInstance" });
20734
20778
  var FindingGroup = external_exports.object({
20735
20779
  id: external_exports.string(),
@@ -20781,7 +20825,10 @@ var FindingFacets = external_exports.object({
20781
20825
  // Host tool (attributes.tool_name). Present only on the instance-level
20782
20826
  // reads, which can filter by it; the type-level read omits the dimension
20783
20827
  // because a group spans tools.
20784
- tool: external_exports.array(FindingFacetItem).optional()
20828
+ tool: external_exports.array(FindingFacetItem).optional(),
20829
+ // Delivery states (FindingDeliveryState). Present only on the
20830
+ // instance-level reads, like `tool`.
20831
+ deployment: external_exports.array(FindingFacetItem).optional()
20785
20832
  }).meta({ id: "FindingFacets" });
20786
20833
  var FindingTypeSummary = FindingGroup.omit({ instances: true, match: true }).meta({
20787
20834
  id: "FindingTypeSummary"
@@ -20892,6 +20939,8 @@ var ListFindingInstancesQuery = external_exports.object({
20892
20939
  // Exact host-tool names (attributes.tool_name, e.g. 'Bash'). A real filter,
20893
20940
  // where the free-text `q` can only match the rendered "via Bash" label.
20894
20941
  tool: external_exports.array(external_exports.string()).optional(),
20942
+ // The delivery state of each finding's event (see FindingDelivery).
20943
+ deployment: external_exports.array(FindingDeliveryState).optional(),
20895
20944
  // Exact repository / file-path matches, for the drill-down out of the
20896
20945
  // locations view. A row whose event carries no repo/file matches neither.
20897
20946
  repo: external_exports.string().optional(),
@@ -20912,6 +20961,10 @@ var ListFindingInstancesResponse = external_exports.object({
20912
20961
  items: external_exports.array(FindingInstanceDetail),
20913
20962
  nextCursor: external_exports.string().nullable()
20914
20963
  }).meta({ id: "ListFindingInstancesResponse" });
20964
+ var ListFindingInstancesPage = external_exports.object({
20965
+ items: external_exports.array(FindingInstanceDetail),
20966
+ nextCursor: external_exports.string().nullable()
20967
+ }).meta({ id: "ListFindingInstancesPage" });
20915
20968
  var FindingLocationSummary = external_exports.object({
20916
20969
  // Opaque, stable, minted from the pair by encodeLocationId. It exists
20917
20970
  // because a location's identity is two values and a URL param carries one:
@@ -20954,6 +21007,8 @@ var ListFindingLocationsQuery = external_exports.object({
20954
21007
  // instances that match, and folds its status from those.
20955
21008
  status: external_exports.array(FindingStatus).optional(),
20956
21009
  tool: external_exports.array(external_exports.string()).optional(),
21010
+ // The delivery state of each finding's event (see FindingDelivery).
21011
+ deployment: external_exports.array(FindingDeliveryState).optional(),
20957
21012
  q: external_exports.string().optional(),
20958
21013
  sessionId: external_exports.string().optional(),
20959
21014
  from: external_exports.iso.datetime().optional(),
@@ -21156,6 +21211,10 @@ var CaptureAttributes = external_exports.object({
21156
21211
  // to 'allow' — the enforcement audit trail's link back to the grant that
21157
21212
  // authorized the bypass.
21158
21213
  exception_ids: external_exports.array(external_exports.guid()).optional(),
21214
+ // The persisted spellings of EventMetadata's messageId/conversationId — the
21215
+ // join back to the `llm_call` leaf for the same assistant turn.
21216
+ message_id: external_exports.string().optional(),
21217
+ conversation_id: external_exports.string().optional(),
21159
21218
  // Whole milliseconds this capture's inspection blocked its caller — the
21160
21219
  // plugin's own added latency (see EventMetadata.inspectionMs, whose value
21161
21220
  // this is). Promoted to the `inspection_ms` generated column so the facet is
@@ -21164,7 +21223,19 @@ var CaptureAttributes = external_exports.object({
21164
21223
  // inline json_extract and is not itself an optimization.
21165
21224
  // ABSENT on replayed captures (backfill / worktree scan) and on rows written
21166
21225
  // before the measurement shipped — never present as a placeholder 0.
21167
- inspection_ms: external_exports.number().int().nonnegative().optional()
21226
+ inspection_ms: external_exports.number().int().nonnegative().optional(),
21227
+ // What a `redact` this capture could not carry out became instead (see
21228
+ // EventMetadata.redactDegradedTo, whose value this is). Present only when a
21229
+ // degrade actually happened, so absence is the ordinary case rather than a
21230
+ // reader having to distinguish it from a zero.
21231
+ //
21232
+ // PER CAPTURE, while `inspection_findings.action_taken` is per finding —
21233
+ // so on a multi-finding row this does not say which finding degraded, and
21234
+ // its presence does not mean the fallback decided the capture's action. A
21235
+ // capture denied by another finding's own Block policy carries `block`
21236
+ // here too. The full statement is on EventMetadata.redactDegradedTo; it is
21237
+ // repeated rather than referenced because a store reader opens this file.
21238
+ redact_degraded_to: ActionTaken.optional()
21168
21239
  }).catchall(external_exports.unknown());
21169
21240
  var ToolCallInspection = external_exports.object({
21170
21241
  ruleId: external_exports.string().min(1),
@@ -21363,7 +21434,17 @@ var AuditEvent = external_exports.object({
21363
21434
  /** `share` to a first-party/internal destination. */
21364
21435
  internal: external_exports.boolean(),
21365
21436
  /** Event needs review (e.g. unverified egress). */
21366
- flagged: external_exports.boolean()
21437
+ flagged: external_exports.boolean(),
21438
+ /**
21439
+ * The body this event's `title` is drawn from was cleared by local body
21440
+ * expiry, so an EMPTY title here means "gone", not "never had one".
21441
+ *
21442
+ * A separate flag rather than a sentinel written into `title`: the title is
21443
+ * rendered text, and a store-layer module that invented display copy for it
21444
+ * would be choosing words the view is supposed to choose. Additive and
21445
+ * defaulted, so an older producer still validates.
21446
+ */
21447
+ bodyExpired: external_exports.boolean().default(false)
21367
21448
  }).meta({ id: "ActivityAuditEvent" });
21368
21449
  var ActivitySessionSummary = external_exports.object({
21369
21450
  id: external_exports.string(),
@@ -22704,6 +22785,12 @@ var EventMetadata = external_exports.object({
22704
22785
  // to 'allow' — the enforcement audit trail's link back to the grant that
22705
22786
  // authorized the bypass. Absent on captures where no exception applied.
22706
22787
  exceptionIds: external_exports.array(external_exports.guid()).optional(),
22788
+ // The assistant message this capture belongs to, and the conversation it sits
22789
+ // in — set by the browser extension's network capture so a stored `response`
22790
+ // row can be joined to the `llm_call` leaf describing the same turn. Absent
22791
+ // on every other capture path, which has no such id.
22792
+ messageId: external_exports.string().optional(),
22793
+ conversationId: external_exports.string().optional(),
22707
22794
  // How long THIS capture's inspection blocked its caller, in whole
22708
22795
  // milliseconds — the plugin's own added latency, NOT the LLM call it sat in
22709
22796
  // front of. Measured inside `capture()` (@akasecurity/plugin-sdk) across
@@ -22716,7 +22803,37 @@ var EventMetadata = external_exports.object({
22716
22803
  // Absent is also what every pre-measurement client writes, and what a
22717
22804
  // clock failure degrades to — a reader must treat absence as "not measured"
22718
22805
  // and never as a zero, which would read as "inspection is free".
22719
- inspectionMs: external_exports.number().int().nonnegative().optional()
22806
+ inspectionMs: external_exports.number().int().nonnegative().optional(),
22807
+ // What a `redact` this capture COULD NOT CARRY OUT became instead — the
22808
+ // workspace's `redactFallback`, applied because the field could not be
22809
+ // masked in place (a shell command, a URL, or any argument on a host whose
22810
+ // hook contract offers no rewrite channel).
22811
+ //
22812
+ // It exists because the action alone cannot say why. A finding recorded as
22813
+ // `warn` reads identically whether its detection was ASSIGNED Warn or was
22814
+ // assigned Redact on a field that could not take one — and those are
22815
+ // different facts about the same row: the first is a policy the user chose,
22816
+ // the second is a masking the host could not perform. Absent means no
22817
+ // degrade happened, which is every ordinary capture.
22818
+ //
22819
+ // TWO LIMITS a reader of a stored row has to know, because the grain here
22820
+ // is the CAPTURE while `actionTaken` is per FINDING:
22821
+ //
22822
+ // - It does not say WHICH finding degraded. A capture carrying a degraded
22823
+ // `redact` alongside a finding ASSIGNED the same action stores both
22824
+ // identically and one reason for the pair; attributing it to both
22825
+ // describes the assigned one wrongly, and to neither loses the degrade.
22826
+ // - PRESENCE IS NOT CAUSATION. The value is the action the lost redact
22827
+ // became, not the reason the capture ended as it did — a capture denied
22828
+ // by some other finding's own Block policy still carries `block` here,
22829
+ // and clearing the workspace's fallback would not have let it through.
22830
+ // Gate on the value against what a fallback can produce; never read the
22831
+ // field's presence as "this was the fallback's doing".
22832
+ //
22833
+ // Both are pinned as behaviour in @akasecurity/plugin-sdk's runtime suite.
22834
+ // Closing either means moving the reason onto the finding row, which
22835
+ // already carries its own action.
22836
+ redactDegradedTo: ActionTaken.optional()
22720
22837
  }).meta({ id: "EventMetadata" });
22721
22838
  var Event = external_exports.object({
22722
22839
  id: external_exports.guid(),
@@ -22826,7 +22943,32 @@ var RotateKeyInput = external_exports.object({
22826
22943
  confirmation: external_exports.string()
22827
22944
  });
22828
22945
 
22946
+ // ../../packages/schema/src/zod/finding-delivery.ts
22947
+ var KNOWN_REASONS = SyncFailureReason.options;
22948
+ function knownReason(value) {
22949
+ return value !== null && KNOWN_REASONS.includes(value) ? value : void 0;
22950
+ }
22951
+ function deriveFindingDelivery(row) {
22952
+ if (row.kind === "code_change") return { state: "local_scan" };
22953
+ if (row.syncedAt !== null && row.syncedAt > 0) {
22954
+ return { state: "sent", at: epochMillisToIso(row.syncedAt) };
22955
+ }
22956
+ if (row.syncedAt !== null) {
22957
+ const reason = knownReason(row.syncFailure);
22958
+ return {
22959
+ state: "not_sent",
22960
+ ...row.syncFailedAt === null ? {} : { at: epochMillisToIso(row.syncFailedAt) },
22961
+ ...reason === void 0 ? {} : { reason }
22962
+ };
22963
+ }
22964
+ if (row.outboxOwed === 1 || row.syncClaimedAt !== null) return { state: "queued" };
22965
+ return { state: "never_offered" };
22966
+ }
22967
+
22829
22968
  // ../../packages/schema/src/zod/findings-group-build.ts
22969
+ function lookupOwn(map2, key) {
22970
+ return Object.hasOwn(map2, key) ? map2[key] : void 0;
22971
+ }
22830
22972
  function toApiAction(dbVal) {
22831
22973
  const map2 = {
22832
22974
  log: "monitored",
@@ -22835,7 +22977,7 @@ function toApiAction(dbVal) {
22835
22977
  warn: "warned",
22836
22978
  allow: "allowed"
22837
22979
  };
22838
- return map2[dbVal] ?? "allowed";
22980
+ return lookupOwn(map2, dbVal) ?? "allowed";
22839
22981
  }
22840
22982
  function toApiCategory(dbVal) {
22841
22983
  if (dbVal === "code_context") return "source_code";
@@ -22843,13 +22985,18 @@ function toApiCategory(dbVal) {
22843
22985
  return parsed2.success ? parsed2.data : "custom";
22844
22986
  }
22845
22987
  function toApiProvider(sourceTool) {
22846
- return TOOL_TO_HARNESS[sourceTool] ?? HARNESS.Api;
22988
+ return lookupOwn(TOOL_TO_HARNESS, sourceTool) ?? HARNESS.Api;
22847
22989
  }
22848
- var STATUS_PRECEDENCE = ["open", "handled", "dismissed", "resolved"];
22990
+ var FINDING_STATUS_PRECEDENCE = [
22991
+ "open",
22992
+ "handled",
22993
+ "dismissed",
22994
+ "resolved"
22995
+ ];
22849
22996
  function foldGroupStatus(instanceStatuses) {
22850
22997
  const statuses = new Set(instanceStatuses.filter((s) => s !== void 0));
22851
22998
  if (statuses.size === 0) return void 0;
22852
- for (const candidate of STATUS_PRECEDENCE) {
22999
+ for (const candidate of FINDING_STATUS_PRECEDENCE) {
22853
23000
  if (statuses.has(candidate)) return candidate;
22854
23001
  }
22855
23002
  return void 0;
@@ -22956,11 +23103,16 @@ function applyFindingFilters(types, opts) {
22956
23103
  }
22957
23104
  return filtered;
22958
23105
  }
22959
- var SEVERITY_ORDER = { critical: 0, high: 1, medium: 2, low: 3 };
22960
- var SEVERITY_RANK = SEVERITY_ORDER;
23106
+ function rankByOrder(members2) {
23107
+ return Object.fromEntries(members2.map((member, index) => [member, index]));
23108
+ }
23109
+ var SEVERITY_RANK = rankByOrder(Severity.options);
23110
+ function severityRank(severity) {
23111
+ return lookupOwn(SEVERITY_RANK, severity);
23112
+ }
22961
23113
  function compareFindingGroupOrder(a, b) {
22962
- const rankA = SEVERITY_RANK[a.severity] ?? -1;
22963
- const rankB = SEVERITY_RANK[b.severity] ?? -1;
23114
+ const rankA = severityRank(a.severity) ?? -1;
23115
+ const rankB = severityRank(b.severity) ?? -1;
22964
23116
  const severityDiff = rankA - rankB;
22965
23117
  if (severityDiff !== 0) return severityDiff;
22966
23118
  const recencyDiff = b.latestDetectedAt.localeCompare(a.latestDetectedAt);
@@ -23035,6 +23187,20 @@ function computeFindingFacets(allTypes, opts) {
23035
23187
  }
23036
23188
 
23037
23189
  // ../../packages/schema/src/zod/findings-flat-build.ts
23190
+ function compareCodePoints(a, b) {
23191
+ const aIter = a[Symbol.iterator]();
23192
+ const bIter = b[Symbol.iterator]();
23193
+ for (; ; ) {
23194
+ const aNext = aIter.next();
23195
+ const bNext = bIter.next();
23196
+ if (aNext.done && bNext.done) return 0;
23197
+ if (aNext.done) return -1;
23198
+ if (bNext.done) return 1;
23199
+ const aPoint = aNext.value.codePointAt(0) ?? 0;
23200
+ const bPoint = bNext.value.codePointAt(0) ?? 0;
23201
+ if (aPoint !== bPoint) return aPoint - bPoint;
23202
+ }
23203
+ }
23038
23204
  function rowHaystack(row) {
23039
23205
  return [
23040
23206
  row.ruleId,
@@ -23059,6 +23225,8 @@ function matchesDimension(row, opts, dimension) {
23059
23225
  return !opts.actions?.length || opts.actions.includes(toApiAction(row.actionTaken));
23060
23226
  case "statuses":
23061
23227
  return !opts.statuses?.length || row.status !== void 0 && opts.statuses.includes(row.status);
23228
+ case "deliveries":
23229
+ return !opts.deliveries?.length || row.delivery !== void 0 && opts.deliveries.includes(row.delivery.state);
23062
23230
  case "tools":
23063
23231
  return !opts.tools?.length || row.toolName !== void 0 && opts.tools.includes(row.toolName);
23064
23232
  // An EMPTY value is a real filter here, not an absent one. The location
@@ -23085,6 +23253,7 @@ var DIMENSIONS = [
23085
23253
  "providers",
23086
23254
  "actions",
23087
23255
  "statuses",
23256
+ "deliveries",
23088
23257
  "tools",
23089
23258
  "repo",
23090
23259
  "file",
@@ -23098,10 +23267,19 @@ function matchesInstanceFilters(row, opts, except) {
23098
23267
  return true;
23099
23268
  }
23100
23269
  function toItems(counts) {
23101
- return [...counts.entries()].map(([value, count]) => ({ value, count })).sort((a, b) => b.count - a.count || a.value.localeCompare(b.value));
23270
+ return [...counts.entries()].map(([value, count]) => ({ value, count })).sort(
23271
+ (a, b) => b.count - a.count || a.value.localeCompare(b.value) || // localeCompare reports canonically-equivalent strings (an NFC and an
23272
+ // NFD spelling of the same text) as equal, so a count tie between
23273
+ // them would otherwise be ordered by whichever the Map iteration
23274
+ // produced. compareCodePoints breaks that tie deterministically, which
23275
+ // makes this a TOTAL order — not one that agrees with SQL collation,
23276
+ // which it need not: foldFacetTuples runs this same sort over grouped
23277
+ // tuples, so both paths order facets identically by construction.
23278
+ compareCodePoints(a.value, b.value)
23279
+ );
23102
23280
  }
23103
- function bump(counts, value) {
23104
- counts.set(value, (counts.get(value) ?? 0) + 1);
23281
+ function bump(counts, value, by = 1) {
23282
+ counts.set(value, (counts.get(value) ?? 0) + by);
23105
23283
  }
23106
23284
  function createInstanceFacetAccumulator(opts) {
23107
23285
  const severity = /* @__PURE__ */ new Map();
@@ -23110,6 +23288,7 @@ function createInstanceFacetAccumulator(opts) {
23110
23288
  const action = /* @__PURE__ */ new Map();
23111
23289
  const status = /* @__PURE__ */ new Map();
23112
23290
  const tool = /* @__PURE__ */ new Map();
23291
+ const deployment = /* @__PURE__ */ new Map();
23113
23292
  return {
23114
23293
  add(row) {
23115
23294
  if (matchesInstanceFilters(row, opts, "severity")) bump(severity, row.severity);
@@ -23124,6 +23303,9 @@ function createInstanceFacetAccumulator(opts) {
23124
23303
  if (row.toolName !== void 0 && matchesInstanceFilters(row, opts, "tools")) {
23125
23304
  bump(tool, row.toolName);
23126
23305
  }
23306
+ if (row.delivery !== void 0 && matchesInstanceFilters(row, opts, "deliveries")) {
23307
+ bump(deployment, row.delivery.state);
23308
+ }
23127
23309
  },
23128
23310
  facets: () => ({
23129
23311
  severity: toItems(severity),
@@ -23131,7 +23313,8 @@ function createInstanceFacetAccumulator(opts) {
23131
23313
  provider: toItems(provider),
23132
23314
  action: toItems(action),
23133
23315
  status: toItems(status),
23134
- tool: toItems(tool)
23316
+ tool: toItems(tool),
23317
+ deployment: toItems(deployment)
23135
23318
  })
23136
23319
  };
23137
23320
  }
@@ -23145,6 +23328,7 @@ function toInstanceDetail(row) {
23145
23328
  ...row.toolName === void 0 ? {} : { toolName: row.toolName },
23146
23329
  eventId: row.eventId,
23147
23330
  ...row.sessionId === void 0 ? {} : { sessionId: row.sessionId },
23331
+ ...row.delivery === void 0 ? {} : { delivery: row.delivery },
23148
23332
  ...row.user === void 0 ? {} : { user: row.user },
23149
23333
  action: toApiAction(row.actionTaken),
23150
23334
  detectedAt: row.occurredAt,
@@ -23159,12 +23343,6 @@ function toInstanceDetail(row) {
23159
23343
  policy: { id: `category:${category}`, name: category }
23160
23344
  };
23161
23345
  }
23162
- var SEVERITY_ORDER2 = {
23163
- critical: 0,
23164
- high: 1,
23165
- medium: 2,
23166
- low: 3
23167
- };
23168
23346
  function newLocationAccumulator() {
23169
23347
  return {
23170
23348
  instanceCount: 0,
@@ -23179,7 +23357,7 @@ function newLocationAccumulator() {
23179
23357
  }
23180
23358
  function addToLocation(acc, row) {
23181
23359
  acc.instanceCount += 1;
23182
- const rank = SEVERITY_ORDER2[row.severity] ?? Number.MAX_SAFE_INTEGER - 1;
23360
+ const rank = severityRank(row.severity) ?? Number.MAX_SAFE_INTEGER - 1;
23183
23361
  if (rank < acc.maxSeverityRank) {
23184
23362
  acc.maxSeverityRank = rank;
23185
23363
  acc.maxSeverity = row.severity;
@@ -23189,15 +23367,15 @@ function addToLocation(acc, row) {
23189
23367
  acc.ruleIds.add(row.ruleId);
23190
23368
  }
23191
23369
  function compareLocationOrder(a, b) {
23192
- const rankA = SEVERITY_ORDER2[a.maxSeverity] ?? -1;
23193
- const rankB = SEVERITY_ORDER2[b.maxSeverity] ?? -1;
23370
+ const rankA = severityRank(a.maxSeverity) ?? -1;
23371
+ const rankB = severityRank(b.maxSeverity) ?? -1;
23194
23372
  if (rankA !== rankB) return rankA - rankB;
23195
23373
  if (a.latestDetectedAt !== b.latestDetectedAt) {
23196
23374
  return a.latestDetectedAt < b.latestDetectedAt ? 1 : -1;
23197
23375
  }
23198
- if (a.repo !== b.repo) return a.repo < b.repo ? -1 : 1;
23199
- if (a.file !== b.file) return a.file < b.file ? -1 : 1;
23200
- return 0;
23376
+ const repoDiff = compareCodePoints(a.repo, b.repo);
23377
+ if (repoDiff !== 0) return repoDiff;
23378
+ return compareCodePoints(a.file, b.file);
23201
23379
  }
23202
23380
  function encodeLocationId(repo, file2) {
23203
23381
  return `${encodePart(repo)}/${encodePart(file2)}`;
@@ -23272,6 +23450,11 @@ var Policy = external_exports.object({
23272
23450
  // test `prohibitedModels` passes and `reversibleRuleIds` fails.
23273
23451
  provenance: PolicyProvenance.optional()
23274
23452
  }).meta({ id: "Policy" });
23453
+ var KNOWN_BUILTIN_IDS = ["monitor", "warn", "redact", "vault", "block"];
23454
+ var BuiltinPolicyId = external_exports.enum(KNOWN_BUILTIN_IDS).meta({ id: "BuiltinPolicyId" });
23455
+ var RedactFallback = BuiltinPolicyId.extract(["monitor", "warn", "block"]).meta({
23456
+ id: "RedactFallback"
23457
+ });
23275
23458
  var PolicyBundle = external_exports.object({
23276
23459
  version: external_exports.string(),
23277
23460
  policies: external_exports.array(Policy),
@@ -23319,6 +23502,16 @@ var PolicyBundle = external_exports.object({
23319
23502
  // control plane), so no name resolution stands between the decision and the
23320
23503
  // comparison.
23321
23504
  prohibitedModels: external_exports.array(external_exports.string()).optional(),
23505
+ // What a resolved `redact` becomes on a field the host cannot rewrite, as
23506
+ // the ORGANIZATION would have it. Merged raise-only against the device's own
23507
+ // `WorkspaceSettings.redactFallback` (see strongerRedactFallback below), so
23508
+ // a control plane can tighten a machine and never loosen one — the same
23509
+ // direction `mergeRaiseOnly` enforces for policies.
23510
+ //
23511
+ // Optional so an older backend, and an older on-disk cache, still parses;
23512
+ // absent leaves the device's own setting in force, which is the behaviour
23513
+ // that predates the field and the safe direction to default.
23514
+ redactFallback: RedactFallback.optional(),
23322
23515
  customKeywords: external_exports.array(external_exports.string()),
23323
23516
  fetchedAt: external_exports.iso.datetime()
23324
23517
  }).meta({ id: "PolicyBundle" });
@@ -23348,11 +23541,6 @@ function severityFloorPolicy(category) {
23348
23541
  const peak = CATEGORY_PEAK_SEVERITY[category];
23349
23542
  return peak === "critical" || peak === "high" ? "warn" : "monitor";
23350
23543
  }
23351
- var KNOWN_BUILTIN_IDS = ["monitor", "warn", "redact", "vault", "block"];
23352
- var BuiltinPolicyId = external_exports.enum(KNOWN_BUILTIN_IDS).meta({ id: "BuiltinPolicyId" });
23353
- var RedactFallback = BuiltinPolicyId.extract(["monitor", "warn", "block"]).meta({
23354
- id: "RedactFallback"
23355
- });
23356
23544
  var BUILTIN_ORDER = KNOWN_BUILTIN_IDS;
23357
23545
  var BUILTIN_POLICY_SPECS = {
23358
23546
  monitor: {
@@ -23655,7 +23843,7 @@ function isVaultConsentValid(consent) {
23655
23843
  }
23656
23844
 
23657
23845
  // ../../packages/schema/src/zod/local.ts
23658
- var WORKSPACE_SETTINGS_SPEC_VERSION = 7;
23846
+ var WORKSPACE_SETTINGS_SPEC_VERSION = 8;
23659
23847
  var MODEL_JUDGE_PAYLOAD_VERSION = 1;
23660
23848
  var RunMode = external_exports.enum(["standalone", "attached"]);
23661
23849
  var ControlPlaneConnection = external_exports.object({
@@ -23675,6 +23863,15 @@ var HistorySyncConsent = external_exports.object({
23675
23863
  payloadVersion: external_exports.number().int().positive(),
23676
23864
  endpoint: external_exports.string()
23677
23865
  });
23866
+ var BODY_RETENTION_DEFAULT_DAYS = 30;
23867
+ var BodyRetention = external_exports.object({
23868
+ enabled: external_exports.boolean().default(false),
23869
+ // Never 0, and the ceiling is a fat-finger guard rather than a policy
23870
+ // limit — `enabled` is the real gate. A low value cannot reach a row the
23871
+ // sync ledger still owes: the sweep's age filter only ever NARROWS a
23872
+ // candidate set that is already bounded by "delivered, or never owed".
23873
+ retainDays: external_exports.number().int().min(1).max(3650).default(BODY_RETENTION_DEFAULT_DAYS)
23874
+ }).meta({ id: "BodyRetention" });
23678
23875
  var WorkspaceSettings = external_exports.object({
23679
23876
  specVersion: external_exports.number().int().positive().default(WORKSPACE_SETTINGS_SPEC_VERSION),
23680
23877
  runMode: RunMode.default("standalone"),
@@ -23723,7 +23920,13 @@ var WorkspaceSettings = external_exports.object({
23723
23920
  // carry prompt/reply/tool-output text in `content`; the key name predates
23724
23921
  // both widenings. Absent until granted, and a grant for a different endpoint
23725
23922
  // or an older payload no longer counts.
23726
- historySyncConsent: HistorySyncConsent.optional()
23923
+ historySyncConsent: HistorySyncConsent.optional(),
23924
+ // Local body expiry (see BodyRetention). Off until switched on; expiring a
23925
+ // body never removes the row or its findings.
23926
+ bodyRetention: BodyRetention.default({
23927
+ enabled: false,
23928
+ retainDays: BODY_RETENTION_DEFAULT_DAYS
23929
+ })
23727
23930
  });
23728
23931
  function defaultWorkspaceSettings() {
23729
23932
  return WorkspaceSettings.parse({});
@@ -23818,12 +24021,15 @@ function toCaptureAttributes(event) {
23818
24021
  ...metadata?.traceId !== void 0 ? { trace_id: metadata.traceId } : {},
23819
24022
  ...metadata?.exceptionIds !== void 0 ? { exception_ids: metadata.exceptionIds } : {},
23820
24023
  ...metadata?.inspectionMs !== void 0 ? { inspection_ms: metadata.inspectionMs } : {},
24024
+ ...metadata?.redactDegradedTo !== void 0 ? { redact_degraded_to: metadata.redactDegradedTo } : {},
23821
24025
  // `model`/`turnIndex` have no dedicated CaptureAttributes field (no writer
23822
24026
  // has ever populated either), but every legacy metadata key still rides
23823
24027
  // the bag rather than being silently dropped — CaptureAttributes'
23824
24028
  // `.catchall(z.unknown())` carries the long tail.
23825
24029
  ...metadata?.model !== void 0 ? { model: metadata.model } : {},
23826
- ...metadata?.turnIndex !== void 0 ? { turn_index: metadata.turnIndex } : {}
24030
+ ...metadata?.turnIndex !== void 0 ? { turn_index: metadata.turnIndex } : {},
24031
+ ...metadata?.messageId !== void 0 ? { message_id: metadata.messageId } : {},
24032
+ ...metadata?.conversationId !== void 0 ? { conversation_id: metadata.conversationId } : {}
23827
24033
  };
23828
24034
  }
23829
24035
  function captureDefinitionVersion(finding) {
@@ -23851,13 +24057,22 @@ var ManagedSettingKey = external_exports.enum([
23851
24057
  "vaultInlineReveal",
23852
24058
  "modelJudgeConsent",
23853
24059
  "dataSharesInPlace",
23854
- "redactFallback"
24060
+ "redactFallback",
24061
+ // Pins the toggle and the day count together — see BodyRetention on why the
24062
+ // two are one unit. An administrator mandating a window wants the count
24063
+ // enforced with it, not one a user can widen while the toggle stays on.
24064
+ "bodyRetention"
23855
24065
  ]).meta({ id: "ManagedSettingKey" });
23856
24066
  function isManagedSettingKey(value) {
23857
24067
  return ManagedSettingKey.safeParse(value).success;
23858
24068
  }
23859
24069
  var ManagedSettingsValues = external_exports.object({
23860
24070
  runMode: external_exports.enum(["standalone", "attached"]).optional(),
24071
+ // `controlPlane` and `bodyRetention` are the two nested values, and both are
24072
+ // plain, non-strict objects: a key under either that this build does not know
24073
+ // is stripped and nothing reports it. The unknown-value split in
24074
+ // ManagedSettings below classifies top-level names only, so it stops at
24075
+ // these boundaries.
23861
24076
  controlPlane: external_exports.object({
23862
24077
  endpoint: external_exports.string().min(1),
23863
24078
  label: external_exports.string().min(1).optional()
@@ -23868,7 +24083,8 @@ var ManagedSettingsValues = external_exports.object({
23868
24083
  vaultInlineReveal: external_exports.enum(["masked", "full", "off"]).optional(),
23869
24084
  modelJudgeConsent: external_exports.boolean().optional(),
23870
24085
  dataSharesInPlace: external_exports.boolean().optional(),
23871
- redactFallback: RedactFallback.optional()
24086
+ redactFallback: RedactFallback.optional(),
24087
+ bodyRetention: BodyRetention.optional()
23872
24088
  }).meta({ id: "ManagedSettingsValues" });
23873
24089
  var ManagedSettings = external_exports.object({
23874
24090
  specVersion: external_exports.number().int().positive().default(MANAGED_SETTINGS_SPEC_VERSION),
@@ -23876,7 +24092,21 @@ var ManagedSettings = external_exports.object({
23876
24092
  // decision from a bug. Absent renders as a generic "your organization".
23877
24093
  organization: external_exports.string().min(1).optional(),
23878
24094
  // What the administrator pinned.
23879
- values: ManagedSettingsValues.default({}),
24095
+ //
24096
+ // Parsed as a RECORD rather than as the nested schema, and split below for
24097
+ // the same reason `lockedFields` is parsed as names: a plain `z.object`
24098
+ // drops an unrecognised key and succeeds, so a pin this build does not know
24099
+ // vanished and nothing anywhere said so. A pin with no lock is a supported
24100
+ // shape — it is a DEFAULT the user may still change — so that silence hit
24101
+ // exactly the file an administrator is most likely to write while a fleet
24102
+ // is mid-upgrade.
24103
+ //
24104
+ // Splitting here rather than calling `.strict()`: strict would REFUSE the
24105
+ // file, which is the outcome the lock half already rejected — an older
24106
+ // build then runs entirely unmanaged, every pin and lock gone. A bad KNOWN
24107
+ // value still fails, because the nested schema is re-run over the known
24108
+ // subset and its issues are re-raised on this parse.
24109
+ values: external_exports.record(external_exports.string(), external_exports.unknown()).default({}),
23880
24110
  // Which of those the user may not change. A key here with no matching value
23881
24111
  // freezes whatever the user last chose; a value with no lock is a DEFAULT
23882
24112
  // the user may still override. The two are separable on purpose.
@@ -23889,17 +24119,31 @@ var ManagedSettings = external_exports.object({
23889
24119
  // the fleets most likely to carry a version skew. A name outside the enum
23890
24120
  // is still never HONOURED: the lockable set stays explicit above.
23891
24121
  lockedFields: external_exports.array(external_exports.string()).default([])
23892
- }).transform(({ lockedFields, ...rest }) => {
24122
+ }).transform(({ lockedFields, values, ...rest }, ctx) => {
23893
24123
  const known = [];
23894
24124
  const unknown2 = [];
23895
24125
  for (const name of lockedFields) {
23896
24126
  if (isManagedSettingKey(name)) known.push(name);
23897
24127
  else unknown2.push(name);
23898
24128
  }
24129
+ const knownValues = /* @__PURE__ */ Object.create(null);
24130
+ const unknownValues = [];
24131
+ for (const [name, value] of Object.entries(values)) {
24132
+ if (Object.hasOwn(ManagedSettingsValues.shape, name)) knownValues[name] = value;
24133
+ else unknownValues.push(name);
24134
+ }
24135
+ const pinned = ManagedSettingsValues.safeParse(knownValues);
24136
+ if (!pinned.success) {
24137
+ for (const issue2 of pinned.error.issues)
24138
+ ctx.addIssue({ ...issue2, path: ["values", ...issue2.path] });
24139
+ return external_exports.NEVER;
24140
+ }
23899
24141
  return {
23900
24142
  ...rest,
24143
+ values: pinned.data,
23901
24144
  lockedFields: known,
23902
- ...unknown2.length > 0 ? { unknownLockedFields: unknown2 } : {}
24145
+ ...unknown2.length > 0 ? { unknownLockedFields: unknown2 } : {},
24146
+ ...unknownValues.length > 0 ? { unknownValueFields: unknownValues } : {}
23903
24147
  };
23904
24148
  }).meta({ id: "ManagedSettings" });
23905
24149
 
@@ -24163,7 +24407,23 @@ var SaveSettingsInput = external_exports.object({
24163
24407
  modelJudgeConsent: ModelJudgeConsentChoice,
24164
24408
  historySyncConsent: HistorySyncConsentChoice,
24165
24409
  vaultConsent: external_exports.string(),
24166
- vaultInlineReveal: external_exports.string()
24410
+ vaultInlineReveal: external_exports.string(),
24411
+ // Widened to `string` like its neighbours rather than typed as
24412
+ // `RedactFallback`, on this module's own layering rule: shape here, VALUE at
24413
+ // the call site, so the domain check receives the type it was written for.
24414
+ //
24415
+ // NOT because a narrower schema would reject differently. `parseActionInput`
24416
+ // is a `safeParse` wrapper and throws for no field schema, so either spelling
24417
+ // reaches a recoverable `{ ok: false }` and there is no rejected promise to
24418
+ // trade against. The real cost runs the other way and is the part worth
24419
+ // knowing: a value this schema admits and the domain enum then rejects lands
24420
+ // on the action's shared refusal, which names NO field, where a shape
24421
+ // rejection reaches `malformedInput` and names the schema key.
24422
+ redactFallback: external_exports.string(),
24423
+ // Shape only, the way the enum fields above are strings only: the RANGE is
24424
+ // `BodyRetention`'s and the action checks it there, so there is one place
24425
+ // that decides what a legal horizon is rather than two that can drift.
24426
+ bodyRetention: external_exports.object({ enabled: external_exports.boolean(), retainDays: external_exports.number() })
24167
24427
  });
24168
24428
  var AttachInput = external_exports.object({
24169
24429
  endpoint: external_exports.string(),
@@ -24335,6 +24595,52 @@ function reviewSeverityRank(reasons) {
24335
24595
  return Math.min(...reasons.map((r) => REVIEW_SEVERITY_RANK[r]));
24336
24596
  }
24337
24597
 
24598
+ // ../../packages/schema/src/zod/web-capture.ts
24599
+ var WebUsageSource = external_exports.enum(["site", "estimated", "none"]);
24600
+ var WebUsage = external_exports.object({
24601
+ inputTokens: external_exports.number().int().nonnegative().optional(),
24602
+ outputTokens: external_exports.number().int().nonnegative().optional(),
24603
+ cacheReadInputTokens: external_exports.number().int().nonnegative().optional(),
24604
+ cacheCreationInputTokens: external_exports.number().int().nonnegative().optional()
24605
+ });
24606
+ var WebToolCall = external_exports.object({
24607
+ toolUseId: external_exports.string().min(1),
24608
+ toolName: external_exports.string().min(1),
24609
+ target: external_exports.string().optional(),
24610
+ isError: external_exports.boolean().optional(),
24611
+ inputSize: external_exports.number().int().nonnegative().optional(),
24612
+ outputSize: external_exports.number().int().nonnegative().optional()
24613
+ });
24614
+ var WebExchange = external_exports.object({
24615
+ messageId: external_exports.string().min(1),
24616
+ startedAt: external_exports.iso.datetime(),
24617
+ model: external_exports.string().optional(),
24618
+ usage: WebUsage.optional(),
24619
+ usageSource: WebUsageSource,
24620
+ stopReason: external_exports.string().optional(),
24621
+ conversationId: external_exports.string().optional(),
24622
+ turnIndex: external_exports.number().int().nonnegative().optional(),
24623
+ toolCalls: external_exports.array(WebToolCall).default([]),
24624
+ // Absent when the adapter recovered no text. Capped by the caller at
24625
+ // RESPONSE_TEXT_MAX_BYTES; `truncated` records that the cap was reached, so a
24626
+ // short capture is never mistaken for a short reply.
24627
+ responseText: external_exports.string().optional(),
24628
+ truncated: external_exports.boolean().default(false)
24629
+ });
24630
+ var RESPONSE_TEXT_MAX_BYTES = 2 * 1024 * 1024;
24631
+ var WebCaptureStatus = external_exports.object({
24632
+ patched: external_exports.boolean(),
24633
+ live: external_exports.boolean(),
24634
+ blind: external_exports.boolean(),
24635
+ sendsSeenDom: external_exports.number().int().nonnegative(),
24636
+ exchangesSeenNet: external_exports.number().int().nonnegative(),
24637
+ parseFailures: external_exports.number().int().nonnegative(),
24638
+ unparsedBodies: external_exports.number().int().nonnegative(),
24639
+ // The adapter-declared JSON key paths that were absent from a real payload —
24640
+ // the earliest signal that a site's contract moved.
24641
+ shapeMisses: external_exports.array(external_exports.string()).default([])
24642
+ });
24643
+
24338
24644
  // ../../packages/persistence/src/paths.ts
24339
24645
  import {
24340
24646
  chmodSync,
@@ -24685,6 +24991,22 @@ function discardStore(file2, backup) {
24685
24991
  }
24686
24992
  }
24687
24993
 
24994
+ // ../../packages/persistence/src/internal/sql-functions.ts
24995
+ var utf8 = new TextDecoder();
24996
+ function akaLower(value) {
24997
+ if (value === null) return null;
24998
+ if (typeof value === "string") return value.toLowerCase();
24999
+ if (typeof value === "number" || typeof value === "bigint") return String(value).toLowerCase();
25000
+ return utf8.decode(value).toLowerCase();
25001
+ }
25002
+ function registerSqlFunctions(db) {
25003
+ db.function(
25004
+ "aka_lower",
25005
+ { deterministic: true, directOnly: true, useBigIntArguments: true },
25006
+ akaLower
25007
+ );
25008
+ }
25009
+
24688
25010
  // ../../packages/persistence/src/internal/sql-text.ts
24689
25011
  function escapeLikePattern(s) {
24690
25012
  return s.replace(/\\/g, "\\\\").replace(/%/g, "\\%").replace(/_/g, "\\_");
@@ -24769,6 +25091,11 @@ function schemaObjectExists(db, kind, name) {
24769
25091
  function indexExists(db, name) {
24770
25092
  return schemaObjectExists(db, "index", name);
24771
25093
  }
25094
+ function indexColumns(db, name) {
25095
+ if (!indexExists(db, name)) return [];
25096
+ const columns = db.prepare(`PRAGMA index_info(${name})`).all();
25097
+ return columns.map((c) => c.name).filter((c) => c !== null);
25098
+ }
24772
25099
  function columnNames(db, table, opts) {
24773
25100
  const pragma = opts?.includeGenerated ? "table_xinfo" : "table_info";
24774
25101
  const columns = db.prepare(`PRAGMA ${pragma}(${table})`).all();
@@ -24830,177 +25157,819 @@ function mapRowsTolerant(rows, map2) {
24830
25157
  return out;
24831
25158
  }
24832
25159
 
24833
- // ../../packages/persistence/src/migrations.ts
24834
- function describeObject(object2) {
24835
- return object2.kind === "column" ? `column ${object2.table}.${object2.name}` : `table ${object2.name}`;
24836
- }
24837
- function splitStatements(sql) {
24838
- return sql.split(/-->\s*statement-breakpoint/).map((s) => s.trim()).filter((s) => s.length > 0);
24839
- }
24840
- function createdIndexName(statement) {
24841
- const body = statement.replace(/^(?:\s*--[^\n]*\n?)+/, "").trimStart();
24842
- return /^CREATE (?:UNIQUE )?INDEX (?:IF NOT EXISTS )?`([^`]+)`/.exec(body)?.[1];
25160
+ // ../../packages/persistence/src/internal/outbox-lane.ts
25161
+ var OUTBOX_CAPTURE_EVENT_TYPES = ["prompt", "response", "tool_use"];
25162
+ var OUTBOX_CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25163
+
25164
+ // ../../packages/persistence/src/sync-failure.ts
25165
+ var SYNC_FAILURE_REASONS = SyncFailureReason.options;
25166
+ function syncFailureRejectCondition(column = "sync_failure") {
25167
+ const members2 = SYNC_FAILURE_REASONS.map((r) => `'${r}'`).join(", ");
25168
+ return `NEW.${column} IS NOT NULL AND NEW.${column} NOT IN (${members2})`;
24843
25169
  }
24844
- var LEGACY_DROP_MIGRATION_TAG = "0014_drop_legacy_events_findings";
24845
- function applyMigrations(db, file2) {
24846
- const legacyCount = db.prepare("PRAGMA user_version").get().user_version;
24847
- db.exec(
24848
- "CREATE TABLE IF NOT EXISTS migration_ledger (tag TEXT PRIMARY KEY, applied_at INTEGER NOT NULL)"
24849
- );
24850
- const applied = new Set(
24851
- db.prepare("SELECT tag FROM migration_ledger").all().map((r) => r.tag)
24852
- );
24853
- const preLedgerStore = applied.size === 0 && legacyCount > 0;
24854
- const record2 = db.prepare(
24855
- "INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)"
24856
- );
24857
- for (const [index, migration] of SQLITE_MIGRATIONS.entries()) {
24858
- if (applied.has(migration.tag)) continue;
24859
- if (migration.tag === LEGACY_DROP_MIGRATION_TAG) continue;
24860
- const evidence = evidenceObjects(migration.sql);
24861
- const present = evidence.filter((o) => evidenceExists(db, o));
24862
- if (present.length > 0 && present.length < evidence.length) {
24863
- const missing = evidence.filter((o) => !present.includes(o));
24864
- const message = `sqlite migration ${migration.tag} has no ledger row, but the store already has ${present.map(describeObject).join(", ")} while missing ${missing.map(describeObject).join(", ")} \u2014 the schema diverged from the migration history; refusing to replay or skip.`;
24865
- akaWarn(message);
24866
- throw new Error(`[aka] ${message}`);
24867
- }
24868
- const alreadyApplied = evidence.length > 0 ? present.length === evidence.length : preLedgerStore && index < legacyCount;
24869
- const wantsFkOff = /PRAGMA foreign_keys\s*=\s*OFF/i.test(migration.sql);
24870
- const statements = splitStatements(migration.sql);
24871
- if (wantsFkOff) db.exec("PRAGMA foreign_keys = OFF");
24872
- try {
24873
- withTransaction(
24874
- db,
24875
- () => {
24876
- for (const statement of statements) {
24877
- const indexName = createdIndexName(statement);
24878
- if (indexName === void 0) {
24879
- if (alreadyApplied) continue;
24880
- } else if (indexExists(db, indexName)) {
24881
- continue;
24882
- }
24883
- db.exec(statement);
24884
- }
24885
- if (wantsFkOff && !alreadyApplied) {
24886
- const violations = db.prepare("PRAGMA foreign_key_check").all();
24887
- if (violations.length > 0) {
24888
- throw new Error(
24889
- `[aka] sqlite migration ${migration.tag} left ${String(violations.length)} foreign-key violation(s); rolling back.`
24890
- );
24891
- }
24892
- }
24893
- record2.run(migration.tag, Date.now());
24894
- },
24895
- "IMMEDIATE"
24896
- );
24897
- } finally {
24898
- if (wantsFkOff) db.exec("PRAGMA foreign_keys = ON");
24899
- }
25170
+
25171
+ // ../../packages/persistence/src/repositories/history-sync.ts
25172
+ var STRUCTURAL_EVENT_TYPES = ["session", "llm_call", "tool_call"];
25173
+ var TYPE_LIST = STRUCTURAL_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25174
+ var CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_TYPE_LIST;
25175
+ var COUNTED_EVENT_TYPES = [
25176
+ ...STRUCTURAL_EVENT_TYPES,
25177
+ ...OUTBOX_CAPTURE_EVENT_TYPES
25178
+ ];
25179
+ var COUNTED_TYPE_LIST = COUNTED_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25180
+ var PARTITION_BUCKETS = `
25181
+ SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NULL THEN 1 ELSE 0 END) AS queued,
25182
+ SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NOT NULL THEN 1 ELSE 0 END) AS inProgress,
25183
+ SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS synced,
25184
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25185
+ AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
25186
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25187
+ AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached,
25188
+ -- Spelled as what it INCLUDES rather than what it excludes, so a reason
25189
+ -- added later lands in no bucket and fails the sum assertion, instead
25190
+ -- of silently joining this one.
25191
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25192
+ AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
25193
+ THEN 1 ELSE 0 END) AS failed,
25194
+ COUNT(*) AS total`;
25195
+ var COUNTED_SCOPE = `
25196
+ WHERE event_type IN (${COUNTED_TYPE_LIST})
25197
+ AND (
25198
+ event_type IN (${TYPE_LIST})
25199
+ OR synced_at IS NOT NULL
25200
+ OR outbox_owed = 1
25201
+ )`;
25202
+ var SKIPPED = -1;
25203
+ var ROW_COLUMNS = `id,
25204
+ parent_id AS parentId,
25205
+ root_session_id AS rootSessionId,
25206
+ event_type AS eventType,
25207
+ host_id AS hostId,
25208
+ harness_id AS harnessId,
25209
+ source_project_id AS sourceProjectId,
25210
+ started_at AS startedAt,
25211
+ ended_at AS endedAt,
25212
+ severity,
25213
+ priority,
25214
+ content,
25215
+ content_hash AS contentHash,
25216
+ attributes`;
25217
+ var SqliteHistorySyncRepository = class {
25218
+ constructor(db) {
25219
+ this.db = db;
25220
+ this.ensureRowStmt = db.prepare(`INSERT OR IGNORE INTO history_sync (id) VALUES (1)`);
25221
+ this.sessionsStmt = db.prepare(
25222
+ `SELECT COALESCE(root_session_id, id) AS sessionId, MIN(started_at) AS earliest
25223
+ FROM audit_events
25224
+ WHERE synced_at IS NULL
25225
+ AND event_type IN (${TYPE_LIST})
25226
+ AND started_at < :before
25227
+ GROUP BY sessionId
25228
+ ORDER BY earliest
25229
+ LIMIT :limit`
25230
+ );
25231
+ this.rowsStmt = db.prepare(
25232
+ `SELECT ${ROW_COLUMNS}
25233
+ FROM audit_events
25234
+ WHERE synced_at IS NULL
25235
+ AND event_type IN (${TYPE_LIST})
25236
+ AND started_at < :before
25237
+ AND COALESCE(root_session_id, id) = :sessionId
25238
+ ORDER BY (event_type = 'session') DESC, started_at
25239
+ LIMIT :limit`
25240
+ );
25241
+ this.captureRowsStmt = db.prepare(
25242
+ `SELECT ${ROW_COLUMNS}
25243
+ FROM audit_events
25244
+ WHERE synced_at IS NULL
25245
+ AND sync_claimed_at IS NULL
25246
+ AND outbox_owed = 1
25247
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25248
+ AND started_at < :before
25249
+ ORDER BY started_at
25250
+ LIMIT :limit`
25251
+ );
25252
+ this.markOwedStmt = db.prepare(
25253
+ `UPDATE audit_events SET outbox_owed = 1 WHERE id = :id AND synced_at IS NULL`
25254
+ );
25255
+ this.markCaptureBacklogOwedStmt = db.prepare(
25256
+ `UPDATE audit_events SET outbox_owed = 1
25257
+ WHERE synced_at IS NULL
25258
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25259
+ AND started_at < :before`
25260
+ );
25261
+ this.stampStmt = db.prepare(
25262
+ `UPDATE audit_events
25263
+ SET synced_at = :at,
25264
+ sync_claimed_at = NULL,
25265
+ sync_failed_at = :failedAt,
25266
+ sync_failure = :failure
25267
+ WHERE id = :id`
25268
+ );
25269
+ this.claimRowStmt = db.prepare(
25270
+ `UPDATE audit_events SET sync_claimed_at = :at WHERE id = :id AND synced_at IS NULL`
25271
+ );
25272
+ this.releaseRowStmt = db.prepare(
25273
+ `UPDATE audit_events SET sync_claimed_at = NULL WHERE id = :id`
25274
+ );
25275
+ this.releaseStaleClaimsStmt = db.prepare(
25276
+ `UPDATE audit_events SET sync_claimed_at = NULL
25277
+ WHERE sync_claimed_at IS NOT NULL AND sync_claimed_at < :staleBefore`
25278
+ );
25279
+ this.partitionStmt = db.prepare(`SELECT${PARTITION_BUCKETS}
25280
+ FROM audit_events${COUNTED_SCOPE}`);
25281
+ this.partitionByKindStmt = db.prepare(
25282
+ `SELECT event_type AS kind,${PARTITION_BUCKETS}
25283
+ FROM audit_events INDEXED BY idx_audit_events_sync${COUNTED_SCOPE}
25284
+ GROUP BY event_type`
25285
+ );
25286
+ this.countsStmt = db.prepare(
25287
+ `SELECT
25288
+ SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
25289
+ SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
25290
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25291
+ AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
25292
+ THEN 1 ELSE 0 END) AS skipped,
25293
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25294
+ AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
25295
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25296
+ AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached
25297
+ FROM audit_events
25298
+ WHERE event_type IN (${TYPE_LIST})`
25299
+ );
25300
+ this.captureSkipCountStmt = db.prepare(
25301
+ // EVERY sentinel capture, whatever the reason — deliberately NOT split the
25302
+ // way the structural totals are. The split exists because a refusal is
25303
+ // terminal only against the deployment that gave it, and the structural
25304
+ // re-arm frees it on a change of deployment. The capture lane has no such
25305
+ // escape: re-arming a capture would offer one deployment's undelivered
25306
+ // prompts, with their text, to a deployment that never saw them, which is
25307
+ // exactly what disownCapturesStmt exists to prevent. So on this lane both
25308
+ // reasons mean the same thing — this row will not be sent — and splitting
25309
+ // them would put refused captures in a bucket nothing reads and nothing
25310
+ // frees.
25311
+ `SELECT COUNT(*) AS skipped
25312
+ FROM audit_events
25313
+ WHERE synced_at = ${String(SKIPPED)}
25314
+ AND event_type IN (${CAPTURE_TYPE_LIST})`
25315
+ );
25316
+ this.fingerprintStmt = db.prepare(
25317
+ `SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
25318
+ FROM history_sync WHERE id = 1`
25319
+ );
25320
+ this.setFingerprintStmt = db.prepare(
25321
+ `UPDATE history_sync
25322
+ SET endpoint_fingerprint = :fingerprint, backlog_before = :backlogBefore
25323
+ WHERE id = 1`
25324
+ );
25325
+ this.disownCapturesStmt = db.prepare(
25326
+ `UPDATE audit_events SET outbox_owed = NULL
25327
+ WHERE outbox_owed IS NOT NULL
25328
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25329
+ AND started_at < :attachedAt`
25330
+ );
25331
+ this.rearmStmt = db.prepare(
25332
+ `UPDATE audit_events
25333
+ SET synced_at = NULL, sync_failed_at = NULL, sync_failure = NULL
25334
+ WHERE (synced_at > 0
25335
+ OR sync_failure IN ('deployment_refused', 'detached_undelivered'))
25336
+ AND event_type IN (${TYPE_LIST})`
25337
+ );
25338
+ this.claimStmt = db.prepare(
25339
+ `UPDATE history_sync
25340
+ SET owner_pid = :pid, owner_host = :host, acquired_at = :now, heartbeat_at = :now
25341
+ WHERE id = 1
25342
+ AND (owner_pid IS NULL
25343
+ OR heartbeat_at IS NULL
25344
+ OR heartbeat_at < :staleBefore
25345
+ OR heartbeat_at > :now)`
25346
+ );
25347
+ this.heartbeatStmt = db.prepare(
25348
+ `UPDATE history_sync SET heartbeat_at = :now WHERE id = 1 AND owner_pid = :pid`
25349
+ );
25350
+ this.releaseStmt = db.prepare(
25351
+ `UPDATE history_sync
25352
+ SET owner_pid = NULL, owner_host = NULL, acquired_at = NULL, heartbeat_at = NULL
25353
+ WHERE id = 1 AND owner_pid = :pid`
25354
+ );
25355
+ this.closeWindowStmt = db.prepare(
25356
+ `UPDATE audit_events
25357
+ SET synced_at = ${String(SKIPPED)},
25358
+ sync_failed_at = :at,
25359
+ sync_failure = 'detached_undelivered'
25360
+ WHERE synced_at IS NULL
25361
+ AND event_type IN (${TYPE_LIST})
25362
+ AND started_at >= :attachedAt`
25363
+ );
25364
+ this.releaseBoundaryStmt = db.prepare(
25365
+ `UPDATE history_sync SET backlog_before = NULL WHERE id = 1`
25366
+ );
25367
+ this.freezeBoundaryStmt = db.prepare(
25368
+ `UPDATE history_sync SET backlog_before = :backlogBefore WHERE id = 1`
25369
+ );
25370
+ this.leaseStmt = db.prepare(
25371
+ `SELECT owner_pid AS ownerPid, owner_host AS ownerHost,
25372
+ acquired_at AS acquiredAt, heartbeat_at AS heartbeatAt
25373
+ FROM history_sync WHERE id = 1`
25374
+ );
25375
+ this.inspectionsStmt = db.prepare(
25376
+ `SELECT d.rule_id AS ruleId,
25377
+ d.name AS ruleName,
25378
+ d.version AS ruleVersion,
25379
+ d.category AS category,
25380
+ d.severity AS severity,
25381
+ f.span_start AS spanStart,
25382
+ f.span_end AS spanEnd,
25383
+ f.masked_match AS maskedMatch,
25384
+ f.action_taken AS actionTaken,
25385
+ f.confidence AS confidence
25386
+ FROM inspection_findings f
25387
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
25388
+ WHERE f.audit_event_id = :auditEventId
25389
+ ORDER BY f.span_start, f.id`
25390
+ );
24900
25391
  }
24901
- if (legacyCount < SQLITE_MIGRATIONS.length) {
24902
- db.exec(`PRAGMA user_version = ${String(SQLITE_MIGRATIONS.length)}`);
25392
+ db;
25393
+ ensureRowStmt;
25394
+ sessionsStmt;
25395
+ rowsStmt;
25396
+ stampStmt;
25397
+ countsStmt;
25398
+ fingerprintStmt;
25399
+ setFingerprintStmt;
25400
+ rearmStmt;
25401
+ claimStmt;
25402
+ heartbeatStmt;
25403
+ releaseStmt;
25404
+ leaseStmt;
25405
+ inspectionsStmt;
25406
+ closeWindowStmt;
25407
+ releaseBoundaryStmt;
25408
+ freezeBoundaryStmt;
25409
+ captureRowsStmt;
25410
+ markOwedStmt;
25411
+ markCaptureBacklogOwedStmt;
25412
+ captureSkipCountStmt;
25413
+ disownCapturesStmt;
25414
+ partitionStmt;
25415
+ partitionByKindStmt;
25416
+ claimRowStmt;
25417
+ releaseRowStmt;
25418
+ releaseStaleClaimsStmt;
25419
+ /**
25420
+ * The masked detections recorded against one tool call.
25421
+ *
25422
+ * These travel with the event because a tool call's target is not
25423
+ * re-inspectable from the event alone — unlike a capture, where the text
25424
+ * itself is re-scannable. What crosses is the masked match and the rule that
25425
+ * produced it, never the value.
25426
+ */
25427
+ inspectionsFor(auditEventId) {
25428
+ return allRows(this.inspectionsStmt, { auditEventId });
24903
25429
  }
24904
- ensureSyncedAtColumn(db, "audit_events");
24905
- ensureScanLedgerTable(db);
24906
- ensureHistorySyncTable(db);
24907
- ensureBlockedDetectionsTable(db);
24908
- ensureRuleProbeCacheTable(db);
24909
- ensureWriteGateTrigger(db);
24910
- ensureTokenUsageColumns(db);
24911
- reconcileSourceProjectIds(db);
24912
- if (!applied.has(LEGACY_DROP_MIGRATION_TAG)) {
24913
- const drained = runLegacyHistoryBackfill(db);
24914
- if (drained) applyLegacyDropMigration(db, file2);
25430
+ /**
25431
+ * Sessions with structural rows still to send, oldest first.
25432
+ *
25433
+ * BOUNDED BY THE BACKLOG BOUNDARY, which is the whole correctness of this
25434
+ * read. Anything recorded after the machine attached is the live forward
25435
+ * path's to deliver; this drain exists for what was recorded before it, and a
25436
+ * row both paths send is at best a duplicate request and at worst — for a
25437
+ * session root — an overwrite of the inventory ids the live path resolved.
25438
+ */
25439
+ pendingSessions(limit, before) {
25440
+ return allRows(this.sessionsStmt, { limit, before }).map(
25441
+ (r) => r.sessionId
25442
+ );
24915
25443
  }
24916
- }
24917
- function readLegacyTables(db) {
24918
- let holdsRows = false;
24919
- const marks = [];
24920
- for (const table of ["events", "findings"]) {
24921
- try {
24922
- const row = db.prepare(`SELECT count(*) AS n, ifnull(max(rowid), -1) AS hi FROM ${table}`).get();
24923
- if (row === void 0) {
24924
- holdsRows = true;
24925
- marks.push(`${table}:unreadable`);
24926
- continue;
24927
- }
24928
- if (row.n > 0) holdsRows = true;
24929
- marks.push(`${table}:${String(row.n)}:${String(row.hi)}`);
24930
- } catch {
24931
- holdsRows = true;
24932
- marks.push(`${table}:unreadable`);
24933
- }
25444
+ /** One session's undelivered structural rows within the backlog, root first. */
25445
+ pendingRows(sessionId, limit, before) {
25446
+ return allRows(this.rowsStmt, { sessionId, limit, before });
24934
25447
  }
24935
- return { holdsRows, mark: marks.join("|") };
24936
- }
24937
- function applyLegacyDropMigration(db, file2) {
24938
- const migration = SQLITE_MIGRATIONS.find((m) => m.tag === LEGACY_DROP_MIGRATION_TAG);
24939
- if (!migration) return;
24940
- const before = file2 === void 0 ? void 0 : readLegacyTables(db);
24941
- if (file2 !== void 0 && before?.holdsRows === true) {
24942
- try {
24943
- backupBeforeLegacyDrop(db, file2);
24944
- } catch (error61) {
24945
- akaWarn(`legacy events/findings backup failed; deferring the drop: ${String(error61)}`);
24946
- return;
24947
- }
25448
+ /**
25449
+ * Captures this machine still owes the deployment, oldest first.
25450
+ *
25451
+ * Selected by the `outbox_owed` marker the attached forward path writes, not
25452
+ * by a time window — see captureRowsStmt for why a window could not express
25453
+ * this. `before` is the grace window that leaves a just-recorded capture to
25454
+ * the live path.
25455
+ */
25456
+ pendingCaptureRows(limit, before) {
25457
+ return allRows(this.captureRowsStmt, { limit, before });
24948
25458
  }
24949
- try {
25459
+ /**
25460
+ * Record that a capture is OWED to the deployment.
25461
+ *
25462
+ * Written by the attached forward path when a live send did not confirm
25463
+ * delivery, and read by the drain as the whole of its eligibility test. It is
25464
+ * a fact rather than an inference: the machine was attached, the send did not
25465
+ * land, so the row is owed — which no time window can state, because the same
25466
+ * window that holds the rows a past attachment left owed also holds every
25467
+ * capture recorded while the machine was DETACHED, and those were never
25468
+ * offered to anyone.
25469
+ *
25470
+ * Idempotent, and never un-set: `markSynced` settling the row is what takes it
25471
+ * out of the drain's read.
25472
+ */
25473
+ markCaptureOwed(id) {
25474
+ this.markOwedStmt.run({ id });
25475
+ }
25476
+ /**
25477
+ * Mark every capture already on disk as owed, as of `before`.
25478
+ *
25479
+ * The consent-time backfill, called once from `aka attach` when a human
25480
+ * grants existing-history consent — never from an ongoing drain pass, and
25481
+ * never inferred from a boundary that could later move. `before` is the
25482
+ * caller's own "now" at the moment consent was granted, so what this marks
25483
+ * is exactly the backlog the consent prompt already counted, not whatever a
25484
+ * later re-attach or key rotation might widen it to.
25485
+ *
25486
+ * Returns how many rows matched, for the caller to log or test against. Not a
25487
+ * count of NEWLY marked rows — a row still unsynced from an earlier call
25488
+ * matches again and is counted again, the same as `UPDATE`'s own `changes`.
25489
+ */
25490
+ markCaptureBacklogOwed(before) {
25491
+ return Number(this.markCaptureBacklogOwedStmt.run({ before }).changes);
25492
+ }
25493
+ /**
25494
+ * Record delivery. Called only AFTER the far side has accepted the rows.
25495
+ *
25496
+ * CLEARS any failure reason in the same statement. A row that failed against
25497
+ * one deployment and then landed is delivered, and leaving the reason behind
25498
+ * would leave the store holding two contradictory answers about one row —
25499
+ * with the surface free to render either.
25500
+ */
25501
+ markSynced(ids, atMs) {
25502
+ this.stampAll(ids, atMs, null);
25503
+ }
25504
+ /**
25505
+ * Record that THIS MACHINE cannot express the row on the wire.
25506
+ *
25507
+ * Reserved for a local defect — a row that cannot be rebuilt into a valid
25508
+ * payload, or a body the client itself refused to send. It fails identically
25509
+ * against every deployment, so it is terminal everywhere and the re-arm leaves
25510
+ * it alone. A row that merely failed to REACH the deployment stays NULL, so it
25511
+ * is retried; marking those would turn one outage into permanent data loss.
25512
+ */
25513
+ markSkipped(ids, atMs) {
25514
+ this.stampAll(ids, SKIPPED, "payload_invalid", atMs);
25515
+ }
25516
+ /**
25517
+ * Record that THIS DEPLOYMENT refused the row.
25518
+ *
25519
+ * The same sentinel as `markSkipped`, and deliberately so: both stop the row
25520
+ * being re-offered on this lane, and `synced_at` goes on answering whether a
25521
+ * row is outstanding rather than why. What separates them is the reason, and
25522
+ * what the reason buys is the re-arm — a refusal is one deployment's verdict
25523
+ * on one body, so it is terminal only for as long as this machine points at
25524
+ * that deployment, and `rearmFor` clears it when the deployment changes.
25525
+ *
25526
+ * Leaving such a row NULL instead would be worse than the loss it replaces:
25527
+ * these reads carry no cursor, so an unstamped row the deployment refuses is
25528
+ * the head of every subsequent page, and the lane stalls behind it for ever.
25529
+ */
25530
+ markRefused(ids, atMs) {
25531
+ this.stampAll(ids, SKIPPED, "deployment_refused", atMs);
25532
+ }
25533
+ eachInTransaction(ids, run) {
25534
+ if (ids.length === 0) return;
24950
25535
  withTransaction(
24951
- db,
25536
+ this.db,
24952
25537
  () => {
24953
- const alreadyDropped = db.prepare("SELECT 1 FROM migration_ledger WHERE tag = ?").get(migration.tag);
24954
- if (alreadyDropped) return;
24955
- if (before !== void 0 && readLegacyTables(db).mark !== before.mark) {
24956
- akaWarn(
24957
- "legacy events/findings rows changed after the pre-drop snapshot decision; deferring the drop so the next open can copy them first."
24958
- );
24959
- return;
24960
- }
24961
- for (const statement of splitStatements(migration.sql)) {
24962
- db.exec(statement);
24963
- }
24964
- db.prepare("INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)").run(
24965
- migration.tag,
24966
- Date.now()
24967
- );
25538
+ for (const id of ids) run(id);
24968
25539
  },
24969
25540
  "IMMEDIATE"
24970
25541
  );
24971
- } catch (error61) {
24972
- akaWarn(`legacy events/findings drop failed; deferring: ${String(error61)}`);
24973
25542
  }
24974
- }
24975
- function backupBeforeLegacyDrop(db, file2) {
24976
- reapStalePartials(file2);
24977
- const backup = backupPath(file2, "pre-drop");
24978
- snapshotStore(db, backup);
24979
- return backup;
24980
- }
24981
- var TOKEN_USAGE_COLUMNS = [
24982
- {
24983
- name: "input_tokens",
24984
- ddl: "ALTER TABLE audit_events ADD COLUMN input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.input_tokens')) VIRTUAL"
24985
- },
24986
- {
24987
- name: "output_tokens",
24988
- ddl: "ALTER TABLE audit_events ADD COLUMN output_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.output_tokens')) VIRTUAL"
24989
- },
24990
- {
24991
- name: "cache_creation_input_tokens",
24992
- ddl: "ALTER TABLE audit_events ADD COLUMN cache_creation_input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.cache_creation_input_tokens')) VIRTUAL"
24993
- },
24994
- {
24995
- name: "cache_read_input_tokens",
24996
- ddl: "ALTER TABLE audit_events ADD COLUMN cache_read_input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.cache_read_input_tokens')) VIRTUAL"
24997
- },
24998
- {
24999
- name: "model",
25000
- ddl: "ALTER TABLE audit_events ADD COLUMN model text GENERATED ALWAYS AS (json_extract(attributes, '$.model')) VIRTUAL"
25001
- },
25002
- {
25003
- name: "provider",
25543
+ stampAll(ids, value, failure, failedAtMs) {
25544
+ if (ids.length === 0) return;
25545
+ const failedAt = failure === null ? null : failedAtMs ?? null;
25546
+ withTransaction(
25547
+ this.db,
25548
+ () => {
25549
+ for (const id of ids) this.stampStmt.run({ at: value, failedAt, failure, id });
25550
+ },
25551
+ "IMMEDIATE"
25552
+ );
25553
+ }
25554
+ /**
25555
+ * Claim rows as in-flight.
25556
+ *
25557
+ * Advisory in exactly the sense the lease is: it records that a send is in
25558
+ * progress so a surface can say so, and a lost claim costs a row showing as
25559
+ * queued while it is actually being sent. It is not exclusion — the far side
25560
+ * settles a duplicate on the row id.
25561
+ */
25562
+ claimRows(ids, atMs) {
25563
+ this.eachInTransaction(ids, (id) => this.claimRowStmt.run({ at: atMs, id }));
25564
+ }
25565
+ /** Give back a claim without settling — the send failed, the row is queued again. */
25566
+ releaseRows(ids) {
25567
+ this.eachInTransaction(ids, (id) => this.releaseRowStmt.run({ id }));
25568
+ }
25569
+ /**
25570
+ * Clear claims older than `staleBefore`, and report how many were cleared.
25571
+ *
25572
+ * A process killed between claiming and settling leaves rows claimed with
25573
+ * nothing left to settle them. Without this they read as "sending" for ever.
25574
+ */
25575
+ releaseStaleClaims(staleBefore) {
25576
+ return Number(this.releaseStaleClaimsStmt.run({ staleBefore }).changes);
25577
+ }
25578
+ /**
25579
+ * Every tracked row in exactly one delivery state.
25580
+ *
25581
+ * Takes no boundary on purpose. The boundary answers "what should the drain
25582
+ * pick up now", which is a different question from "what state is this row
25583
+ * in" — and a machine that has never attached has no boundary to pass, so
25584
+ * requiring one would force a caller to invent one and report the whole store
25585
+ * as queued.
25586
+ */
25587
+ /**
25588
+ * The same partition, one row per kind that a lane carries.
25589
+ *
25590
+ * A kind with nothing to report is ABSENT rather than a row of zeros: the
25591
+ * scope decides which rows exist at all, so a kind that has never been
25592
+ * recorded — or whose captures nobody ever owed — produces no group. A caller
25593
+ * rendering a fixed list of kinds must therefore treat a missing one as "no
25594
+ * rows", never as "zero sent"; the two look identical in a bar and mean
25595
+ * different things.
25596
+ */
25597
+ partitionByKind() {
25598
+ return allRows(
25599
+ this.partitionByKindStmt,
25600
+ {}
25601
+ ).map((row) => ({
25602
+ kind: row.kind,
25603
+ queued: row.queued ?? 0,
25604
+ inProgress: row.inProgress ?? 0,
25605
+ synced: row.synced ?? 0,
25606
+ failed: row.failed ?? 0,
25607
+ refused: row.refused ?? 0,
25608
+ detached: row.detached ?? 0,
25609
+ total: row.total ?? 0
25610
+ }));
25611
+ }
25612
+ partition() {
25613
+ const row = getRow(this.partitionStmt, {});
25614
+ return {
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
+ /** `pending` counts only what is inside the backlog; sent and skipped are totals. */
25625
+ counts(before) {
25626
+ const row = getRow(this.countsStmt, { before });
25627
+ const captures = getRow(this.captureSkipCountStmt);
25628
+ return {
25629
+ pending: row?.pending ?? 0,
25630
+ sent: row?.sent ?? 0,
25631
+ skipped: row?.skipped ?? 0,
25632
+ refused: row?.refused ?? 0,
25633
+ detached: row?.detached ?? 0,
25634
+ capturesSkipped: captures?.skipped ?? 0
25635
+ };
25636
+ }
25637
+ /**
25638
+ * The deployment the current stamps were made against, and where its backlog
25639
+ * ends.
25640
+ *
25641
+ * READ-ONLY. An absent row reads as an absent deployment, which is what a
25642
+ * machine that has never drained is — and every writer below seeds the row
25643
+ * before it needs one, so nothing depends on this creating it. Keeping the
25644
+ * write off the gate path matters because the gate runs on every pass while a
25645
+ * write has to take the database's write lock.
25646
+ */
25647
+ deployment() {
25648
+ const row = getRow(
25649
+ this.fingerprintStmt
25650
+ );
25651
+ return {
25652
+ fingerprint: row?.fingerprint ?? void 0,
25653
+ backlogBefore: row?.backlogBefore ?? void 0
25654
+ };
25655
+ }
25656
+ /**
25657
+ * Point the ledger at a different deployment, discarding what it recorded
25658
+ * about the previous one.
25659
+ *
25660
+ * Delivery is a fact about ONE recipient: rows sent to the deployment a
25661
+ * machine has just left are undelivered as far as the new one is concerned.
25662
+ * All four in one transaction, so a crash between them cannot leave stamps
25663
+ * attributed to the wrong deployment, a boundary that belongs to another, or
25664
+ * a disown with no re-mark to follow it.
25665
+ *
25666
+ * The boundary is written HERE and only here, which is what freezes it: a
25667
+ * re-attach to the SAME deployment (a key rotation) leaves the fingerprint
25668
+ * unchanged, so this never runs and the backlog does not widen back over rows
25669
+ * the live path has since delivered.
25670
+ *
25671
+ * `backfillCapturesBefore` is the caller's OWN "now" at the instant a human
25672
+ * granted existing-history consent for the deployment this call is arming —
25673
+ * a DIFFERENT instant from `backlogBefore`: the re-mark boundary is the GRANT
25674
+ * instant, `backlogBefore` is the ATTACH instant, and the two can be far
25675
+ * apart. Passed only when that grant is valid, since this method has no way
25676
+ * to check consent itself and must not mark a row owed for a machine that
25677
+ * never agreed to it. Applied AFTER the disown above, in the SAME
25678
+ * transaction: what the disown clears is every marker below `backlogBefore`,
25679
+ * which includes this deployment's OWN pre-attach rows — `aka attach` calls
25680
+ * `seedCaptureBacklogOwed` at the attach instant, so every row it marks sits
25681
+ * on the cleared side of that bound — and the re-mark in the same
25682
+ * transaction is what puts those rows back. A crash between the two cannot
25683
+ * strand the ledger disowned with nothing re-marked — the transaction either
25684
+ * lands whole or not at all, and a fingerprint mismatch that has not yet
25685
+ * committed re-enters this method on the very next pass. Omit it (the
25686
+ * structural-only tests do) to exercise the disown in isolation.
25687
+ *
25688
+ * The disown is bounded by `backlogBefore`, which is what keeps it from
25689
+ * touching a marker the NEW deployment's OWN live path has already set: B's
25690
+ * live path can mark a capture owed from the moment `aka attach` writes the
25691
+ * descriptor, before the drain's first pass ever reaches this method, and
25692
+ * such a row sits at or after the bound rather than below it. What keeps the
25693
+ * disown from eating THIS SAME CALL's own re-mark is the order, not the
25694
+ * bound — disown runs first, re-mark second, both inside the one
25695
+ * transaction above.
25696
+ */
25697
+ rearmFor(fingerprint, backlogBefore, backfillCapturesBefore) {
25698
+ this.ensureRowStmt.run();
25699
+ withTransaction(
25700
+ this.db,
25701
+ () => {
25702
+ const previous = getRow(this.fingerprintStmt)?.fingerprint;
25703
+ this.rearmStmt.run();
25704
+ if (previous !== null && previous !== void 0 && previous !== fingerprint) {
25705
+ this.disownCapturesStmt.run({ attachedAt: backlogBefore });
25706
+ }
25707
+ if (backfillCapturesBefore !== void 0) {
25708
+ this.markCaptureBacklogOwedStmt.run({ before: backfillCapturesBefore });
25709
+ }
25710
+ this.setFingerprintStmt.run({ fingerprint, backlogBefore });
25711
+ },
25712
+ "IMMEDIATE"
25713
+ );
25714
+ }
25715
+ /**
25716
+ * End the attached period: hand its rows to the live path, and release the
25717
+ * boundary so the next attachment can freeze a new one.
25718
+ *
25719
+ * WITHOUT THIS, a detach and a re-attach to the same deployment leave a window
25720
+ * nothing delivers. The fingerprint is unchanged, so the boundary is never
25721
+ * re-frozen and stays at the FIRST attachment — while nothing forwards at all
25722
+ * during the detached period, because the machine is not attached. Rows
25723
+ * recorded in that window sit after the boundary and before the re-attach, so
25724
+ * neither path takes them, and the pending count reports none outstanding.
25725
+ *
25726
+ * WHAT IT RECORDS, and what it deliberately does not. These rows were the
25727
+ * closing attachment's to deliver and are no longer outstanding — that is what
25728
+ * lets the boundary move. It is NOT a claim that any of them arrived, and the
25729
+ * distinction is not academic: this used to write a delivery TIME, which every
25730
+ * read treats as delivery, so one detach turned a window of undelivered rows
25731
+ * into a window of delivered ones and no surface could tell. It writes the
25732
+ * skip sentinel and a reason of its own instead, so "no longer owed" and
25733
+ * "received" stop being the same fact.
25734
+ *
25735
+ * A change of deployment still frees them (see the re-arm), because the next
25736
+ * deployment has seen none of this machine's history — so the rows reach it
25737
+ * exactly as they did when this wrote a delivery time.
25738
+ *
25739
+ * ONE TRANSACTION, so a crash cannot release the boundary while leaving the
25740
+ * window unstamped — that half-state would re-send the whole attached period
25741
+ * on the next attach, which is the failure the boundary exists to prevent.
25742
+ */
25743
+ closeAttachedWindow(attachedAtMs, atMs) {
25744
+ this.ensureRowStmt.run();
25745
+ withTransaction(
25746
+ this.db,
25747
+ () => {
25748
+ const row = getRow(this.fingerprintStmt);
25749
+ const from = row?.backlogBefore ?? attachedAtMs;
25750
+ this.closeWindowStmt.run({ at: atMs, attachedAt: from });
25751
+ this.releaseBoundaryStmt.run();
25752
+ },
25753
+ "IMMEDIATE"
25754
+ );
25755
+ }
25756
+ /**
25757
+ * Freeze a boundary for the deployment already on file, KEEPING the stamps.
25758
+ *
25759
+ * The re-attach half of the above. Distinct from `rearmFor`, which is for a
25760
+ * different deployment and therefore discards what was delivered to the old
25761
+ * one: here the recipient is the same, so everything already sent to it stays
25762
+ * sent.
25763
+ */
25764
+ freezeBoundary(backlogBefore) {
25765
+ this.ensureRowStmt.run();
25766
+ this.freezeBoundaryStmt.run({ backlogBefore });
25767
+ }
25768
+ /** Take the claim, or report that someone live already holds it. */
25769
+ claim(pid, host, nowMs, staleAfterMs) {
25770
+ this.ensureRowStmt.run();
25771
+ let taken = false;
25772
+ withTransaction(
25773
+ this.db,
25774
+ () => {
25775
+ const result = this.claimStmt.run({
25776
+ pid,
25777
+ host,
25778
+ now: nowMs,
25779
+ staleBefore: nowMs - staleAfterMs
25780
+ });
25781
+ taken = result.changes === 1;
25782
+ },
25783
+ "IMMEDIATE"
25784
+ );
25785
+ return taken;
25786
+ }
25787
+ /** Say the holder is still alive. A no-op once the claim has moved on. */
25788
+ heartbeat(pid, nowMs) {
25789
+ this.heartbeatStmt.run({ now: nowMs, pid });
25790
+ }
25791
+ /** Give the claim up. Scoped to this holder, so a taken-over claim is left be. */
25792
+ release(pid) {
25793
+ this.releaseStmt.run({ pid });
25794
+ }
25795
+ /** Who holds the claim, if anyone. Read-only, for the same reason as above. */
25796
+ lease() {
25797
+ return getRow(this.leaseStmt);
25798
+ }
25799
+ };
25800
+
25801
+ // ../../packages/persistence/src/migrations.ts
25802
+ function describeObject(object2) {
25803
+ return object2.kind === "column" ? `column ${object2.table}.${object2.name}` : `table ${object2.name}`;
25804
+ }
25805
+ function splitStatements(sql) {
25806
+ return sql.split(/-->\s*statement-breakpoint/).map((s) => s.trim()).filter((s) => s.length > 0);
25807
+ }
25808
+ function createdIndexName(statement) {
25809
+ const body = statement.replace(/^(?:\s*--[^\n]*\n?)+/, "").trimStart();
25810
+ return /^CREATE (?:UNIQUE )?INDEX (?:IF NOT EXISTS )?`([^`]+)`/.exec(body)?.[1];
25811
+ }
25812
+ var LEGACY_DROP_MIGRATION_TAG = "0014_drop_legacy_events_findings";
25813
+ function applyMigrations(db, file2, options = {}) {
25814
+ const legacyCount = db.prepare("PRAGMA user_version").get().user_version;
25815
+ db.exec(
25816
+ "CREATE TABLE IF NOT EXISTS migration_ledger (tag TEXT PRIMARY KEY, applied_at INTEGER NOT NULL)"
25817
+ );
25818
+ const applied = new Set(
25819
+ db.prepare("SELECT tag FROM migration_ledger").all().map((r) => r.tag)
25820
+ );
25821
+ const preLedgerStore = applied.size === 0 && legacyCount > 0;
25822
+ const record2 = db.prepare(
25823
+ "INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)"
25824
+ );
25825
+ for (const [index, migration] of SQLITE_MIGRATIONS.entries()) {
25826
+ if (applied.has(migration.tag)) continue;
25827
+ if (options.skipTags?.has(migration.tag) === true) continue;
25828
+ if (migration.tag === LEGACY_DROP_MIGRATION_TAG) continue;
25829
+ const evidence = evidenceObjects(migration.sql);
25830
+ const present = evidence.filter((o) => evidenceExists(db, o));
25831
+ if (present.length > 0 && present.length < evidence.length) {
25832
+ const missing = evidence.filter((o) => !present.includes(o));
25833
+ const message = `sqlite migration ${migration.tag} has no ledger row, but the store already has ${present.map(describeObject).join(", ")} while missing ${missing.map(describeObject).join(", ")} \u2014 the schema diverged from the migration history; refusing to replay or skip.`;
25834
+ akaWarn(message);
25835
+ throw new Error(`[aka] ${message}`);
25836
+ }
25837
+ const alreadyApplied = evidence.length > 0 ? present.length === evidence.length : preLedgerStore && index < legacyCount;
25838
+ const wantsFkOff = /PRAGMA foreign_keys\s*=\s*OFF/i.test(migration.sql);
25839
+ const statements = splitStatements(migration.sql);
25840
+ if (wantsFkOff) db.exec("PRAGMA foreign_keys = OFF");
25841
+ try {
25842
+ withTransaction(
25843
+ db,
25844
+ () => {
25845
+ for (const statement of statements) {
25846
+ const indexName = createdIndexName(statement);
25847
+ if (indexName === void 0) {
25848
+ if (alreadyApplied) continue;
25849
+ } else if (indexExists(db, indexName)) {
25850
+ continue;
25851
+ }
25852
+ db.exec(statement);
25853
+ }
25854
+ if (wantsFkOff && !alreadyApplied) {
25855
+ const violations = db.prepare("PRAGMA foreign_key_check").all();
25856
+ if (violations.length > 0) {
25857
+ throw new Error(
25858
+ `[aka] sqlite migration ${migration.tag} left ${String(violations.length)} foreign-key violation(s); rolling back.`
25859
+ );
25860
+ }
25861
+ }
25862
+ record2.run(migration.tag, Date.now());
25863
+ },
25864
+ "IMMEDIATE"
25865
+ );
25866
+ } finally {
25867
+ if (wantsFkOff) db.exec("PRAGMA foreign_keys = ON");
25868
+ }
25869
+ }
25870
+ if (legacyCount < SQLITE_MIGRATIONS.length) {
25871
+ db.exec(`PRAGMA user_version = ${String(SQLITE_MIGRATIONS.length)}`);
25872
+ }
25873
+ ensureSyncedAtColumn(db, "audit_events");
25874
+ ensureScanLedgerTable(db);
25875
+ ensureHistorySyncTable(db);
25876
+ ensureBlockedDetectionsTable(db);
25877
+ ensureRuleProbeCacheTable(db);
25878
+ ensureWriteGateTrigger(db);
25879
+ ensureTokenUsageColumns(db);
25880
+ reconcileSourceProjectIds(db);
25881
+ if (!applied.has(LEGACY_DROP_MIGRATION_TAG)) {
25882
+ const drained = runLegacyHistoryBackfill(db);
25883
+ if (drained) applyLegacyDropMigration(db, file2);
25884
+ }
25885
+ }
25886
+ function readLegacyTables(db) {
25887
+ let holdsRows = false;
25888
+ const marks = [];
25889
+ for (const table of ["events", "findings"]) {
25890
+ try {
25891
+ const row = db.prepare(`SELECT count(*) AS n, ifnull(max(rowid), -1) AS hi FROM ${table}`).get();
25892
+ if (row === void 0) {
25893
+ holdsRows = true;
25894
+ marks.push(`${table}:unreadable`);
25895
+ continue;
25896
+ }
25897
+ if (row.n > 0) holdsRows = true;
25898
+ marks.push(`${table}:${String(row.n)}:${String(row.hi)}`);
25899
+ } catch {
25900
+ holdsRows = true;
25901
+ marks.push(`${table}:unreadable`);
25902
+ }
25903
+ }
25904
+ return { holdsRows, mark: marks.join("|") };
25905
+ }
25906
+ function applyLegacyDropMigration(db, file2) {
25907
+ const migration = SQLITE_MIGRATIONS.find((m) => m.tag === LEGACY_DROP_MIGRATION_TAG);
25908
+ if (!migration) return;
25909
+ const before = file2 === void 0 ? void 0 : readLegacyTables(db);
25910
+ if (file2 !== void 0 && before?.holdsRows === true) {
25911
+ try {
25912
+ backupBeforeLegacyDrop(db, file2);
25913
+ } catch (error61) {
25914
+ akaWarn(`legacy events/findings backup failed; deferring the drop: ${String(error61)}`);
25915
+ return;
25916
+ }
25917
+ }
25918
+ try {
25919
+ withTransaction(
25920
+ db,
25921
+ () => {
25922
+ const alreadyDropped = db.prepare("SELECT 1 FROM migration_ledger WHERE tag = ?").get(migration.tag);
25923
+ if (alreadyDropped) return;
25924
+ if (before !== void 0 && readLegacyTables(db).mark !== before.mark) {
25925
+ akaWarn(
25926
+ "legacy events/findings rows changed after the pre-drop snapshot decision; deferring the drop so the next open can copy them first."
25927
+ );
25928
+ return;
25929
+ }
25930
+ for (const statement of splitStatements(migration.sql)) {
25931
+ db.exec(statement);
25932
+ }
25933
+ db.prepare("INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)").run(
25934
+ migration.tag,
25935
+ Date.now()
25936
+ );
25937
+ },
25938
+ "IMMEDIATE"
25939
+ );
25940
+ } catch (error61) {
25941
+ akaWarn(`legacy events/findings drop failed; deferring: ${String(error61)}`);
25942
+ }
25943
+ }
25944
+ function backupBeforeLegacyDrop(db, file2) {
25945
+ reapStalePartials(file2);
25946
+ const backup = backupPath(file2, "pre-drop");
25947
+ snapshotStore(db, backup);
25948
+ return backup;
25949
+ }
25950
+ var TOKEN_USAGE_COLUMNS = [
25951
+ {
25952
+ name: "input_tokens",
25953
+ ddl: "ALTER TABLE audit_events ADD COLUMN input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.input_tokens')) VIRTUAL"
25954
+ },
25955
+ {
25956
+ name: "output_tokens",
25957
+ ddl: "ALTER TABLE audit_events ADD COLUMN output_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.output_tokens')) VIRTUAL"
25958
+ },
25959
+ {
25960
+ name: "cache_creation_input_tokens",
25961
+ ddl: "ALTER TABLE audit_events ADD COLUMN cache_creation_input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.cache_creation_input_tokens')) VIRTUAL"
25962
+ },
25963
+ {
25964
+ name: "cache_read_input_tokens",
25965
+ ddl: "ALTER TABLE audit_events ADD COLUMN cache_read_input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.cache_read_input_tokens')) VIRTUAL"
25966
+ },
25967
+ {
25968
+ name: "model",
25969
+ ddl: "ALTER TABLE audit_events ADD COLUMN model text GENERATED ALWAYS AS (json_extract(attributes, '$.model')) VIRTUAL"
25970
+ },
25971
+ {
25972
+ name: "provider",
25004
25973
  ddl: "ALTER TABLE audit_events ADD COLUMN provider text GENERATED ALWAYS AS (json_extract(attributes, '$.provider')) VIRTUAL"
25005
25974
  }
25006
25975
  ];
@@ -25262,10 +26231,62 @@ function ensureSyncedAtColumn(db, table) {
25262
26231
  if (!columns.includes("outbox_owed")) {
25263
26232
  db.exec(`ALTER TABLE ${table} ADD COLUMN outbox_owed integer`);
25264
26233
  }
26234
+ if (!columns.includes("sync_failed_at")) {
26235
+ db.exec(`ALTER TABLE ${table} ADD COLUMN sync_failed_at integer`);
26236
+ }
26237
+ if (!columns.includes("sync_failure")) {
26238
+ withTransaction(
26239
+ db,
26240
+ () => {
26241
+ db.exec(`ALTER TABLE ${table} ADD COLUMN sync_failure text`);
26242
+ db.exec(
26243
+ `UPDATE ${table} SET synced_at = NULL
26244
+ WHERE synced_at = -1
26245
+ AND event_type IN (${COUNTED_EVENT_TYPES.map((t) => `'${t}'`).join(", ")})`
26246
+ );
26247
+ },
26248
+ "IMMEDIATE"
26249
+ );
26250
+ }
25265
26251
  db.exec(
25266
- `CREATE INDEX IF NOT EXISTS idx_audit_events_sync
25267
- ON audit_events (event_type, synced_at, sync_claimed_at, started_at)`
26252
+ `CREATE TRIGGER IF NOT EXISTS aka_sync_failure_guard
26253
+ BEFORE UPDATE OF sync_failure ON ${table}
26254
+ WHEN ${syncFailureRejectCondition()}
26255
+ BEGIN SELECT RAISE(ABORT, 'sync_failure is not one of the recorded reasons'); END`
25268
26256
  );
26257
+ const syncIndexColumns = [
26258
+ "event_type",
26259
+ "synced_at",
26260
+ "sync_claimed_at",
26261
+ "started_at",
26262
+ // Appended LAST on purpose. The delivery-state read now projects it, so it
26263
+ // has to be in the index for the read to stay covered — but putting it
26264
+ // ahead of `started_at` would reorder the prefix the structural drain's
26265
+ // reads match on.
26266
+ "sync_failure"
26267
+ // `outbox_owed` is DELIBERATELY ABSENT, and it was measured both ways.
26268
+ //
26269
+ // The delivery-state read tests it — a capture's state depends on whether a
26270
+ // live forward marked it owed — so carrying it here makes that read covering
26271
+ // rather than a row fetch per row: 16 ms against 40 ms on a real 6 GB store.
26272
+ // But a sixth column changes what the planner charges for this index, and
26273
+ // with no ANALYZE statistics it plans from schema shape alone: measured, it
26274
+ // then stops choosing the per-session index for the token rollup and walks
26275
+ // every `llm_call` in the store through the event-type index instead. That
26276
+ // read grows with the store; this one does not.
26277
+ //
26278
+ // 40 ms on the largest store measured, once per render, is a cost worth
26279
+ // paying to leave every other read's plan where it was.
26280
+ ];
26281
+ const currentSyncIndex = indexColumns(db, "idx_audit_events_sync");
26282
+ const syncIndexMatches = currentSyncIndex.length === syncIndexColumns.length && currentSyncIndex.every((column, i) => column === syncIndexColumns[i]);
26283
+ if (!syncIndexMatches) {
26284
+ db.exec("DROP INDEX IF EXISTS idx_audit_events_sync");
26285
+ db.exec(
26286
+ `CREATE INDEX idx_audit_events_sync
26287
+ ON audit_events (${syncIndexColumns.join(", ")})`
26288
+ );
26289
+ }
25269
26290
  db.exec(
25270
26291
  `CREATE INDEX IF NOT EXISTS idx_audit_outbox_owed
25271
26292
  ON audit_events (event_type, synced_at, sync_claimed_at, started_at) WHERE outbox_owed = 1`
@@ -25487,7 +26508,11 @@ function buildAuditEvent(row) {
25487
26508
  link: linkParsed?.success ? linkParsed.data : null,
25488
26509
  targetId: row.target_id,
25489
26510
  internal: intToBool(row.internal),
25490
- flagged: intToBool(row.flagged)
26511
+ flagged: intToBool(row.flagged),
26512
+ // Only meaningful when the title came out empty — a row whose body was
26513
+ // expired but whose title fell back to `tool_name` still has something to
26514
+ // render, and flagging it would make the view apologise for nothing.
26515
+ bodyExpired: row.content_expired_at !== null && (row.title ?? "") === ""
25491
26516
  };
25492
26517
  }
25493
26518
  var TIMELINE_COLUMNS = `
@@ -25495,6 +26520,7 @@ var TIMELINE_COLUMNS = `
25495
26520
  event_type,
25496
26521
  started_at,
25497
26522
  coalesce(content, json_extract(attributes, '$.tool_name')) AS title,
26523
+ content_expired_at,
25498
26524
  coalesce(json_extract(attributes, '$.detail'), json_extract(attributes, '$.target')) AS detail,
25499
26525
  coalesce(json_extract(attributes, '$.tool_name'), json_extract(attributes, '$.tool')) AS tool,
25500
26526
  json_extract(attributes, '$.severity') AS severity,
@@ -26160,6 +27186,88 @@ var SqliteAuditEventsRepository = class {
26160
27186
  }
26161
27187
  };
26162
27188
 
27189
+ // ../../packages/persistence/src/repositories/body-retention.ts
27190
+ var DEFAULT_BATCH_SIZE = 500;
27191
+ var DEFAULT_MAX_ROWS = 5e4;
27192
+ var SYNC_LANE_TYPES_SQL = OUTBOX_CAPTURE_TYPE_LIST;
27193
+ var SqliteBodyRetentionRepository = class {
27194
+ constructor(db) {
27195
+ this.db = db;
27196
+ const select = (laneClause) => `
27197
+ SELECT id, LENGTH(CAST(content AS BLOB)) AS bytes
27198
+ FROM audit_events
27199
+ WHERE content IS NOT NULL
27200
+ AND started_at < :cutoff
27201
+ AND event_type IN (${CAPTURE_EVENT_TYPES_SQL})
27202
+ ${laneClause}
27203
+ ORDER BY started_at
27204
+ LIMIT :limit`;
27205
+ this.candidatesStmt = this.db.prepare(select(""));
27206
+ this.candidatesSyncSafeStmt = this.db.prepare(
27207
+ select(`AND (event_type NOT IN (${SYNC_LANE_TYPES_SQL}) OR synced_at IS NOT NULL)`)
27208
+ );
27209
+ this.heldBySyncStmt = this.db.prepare(`
27210
+ SELECT COUNT(*) AS n
27211
+ FROM audit_events
27212
+ WHERE content IS NOT NULL
27213
+ AND started_at < :cutoff
27214
+ AND event_type IN (${SYNC_LANE_TYPES_SQL})
27215
+ AND synced_at IS NULL`);
27216
+ this.expireStmt = this.db.prepare(
27217
+ `UPDATE audit_events SET content = NULL, content_expired_at = :now WHERE id = :id`
27218
+ );
27219
+ }
27220
+ db;
27221
+ candidatesStmt;
27222
+ candidatesSyncSafeStmt;
27223
+ heldBySyncStmt;
27224
+ expireStmt;
27225
+ /** How many bytes a pass with these options would free, changing nothing. */
27226
+ preview(opts) {
27227
+ const limit = opts.maxRows ?? DEFAULT_MAX_ROWS;
27228
+ const stmt = opts.sweepSyncLane ? this.candidatesStmt : this.candidatesSyncSafeStmt;
27229
+ const rows = stmt.all({ cutoff: opts.cutoff, limit });
27230
+ return {
27231
+ rowsExpired: rows.length,
27232
+ bytesFreed: rows.reduce((sum, r) => sum + r.bytes, 0),
27233
+ rowsHeldBySync: this.countHeldBySync(opts)
27234
+ };
27235
+ }
27236
+ /** Clear eligible bodies, in bounded batches. */
27237
+ expire(opts) {
27238
+ const batchSize = opts.batchSize ?? DEFAULT_BATCH_SIZE;
27239
+ const maxRows = opts.maxRows ?? DEFAULT_MAX_ROWS;
27240
+ const stmt = opts.sweepSyncLane ? this.candidatesStmt : this.candidatesSyncSafeStmt;
27241
+ let rowsExpired = 0;
27242
+ let bytesFreed = 0;
27243
+ let done = true;
27244
+ while (rowsExpired < maxRows) {
27245
+ const remaining = Math.min(batchSize, maxRows - rowsExpired);
27246
+ const batch = stmt.all({ cutoff: opts.cutoff, limit: remaining });
27247
+ if (batch.length === 0) break;
27248
+ withTransaction(
27249
+ this.db,
27250
+ () => {
27251
+ for (const row of batch) this.expireStmt.run({ id: row.id, now: opts.now });
27252
+ },
27253
+ "IMMEDIATE"
27254
+ );
27255
+ rowsExpired += batch.length;
27256
+ bytesFreed += batch.reduce((sum, r) => sum + r.bytes, 0);
27257
+ if (batch.length < remaining) break;
27258
+ if (rowsExpired >= maxRows) {
27259
+ done = stmt.all({ cutoff: opts.cutoff, limit: 1 }).length === 0;
27260
+ }
27261
+ }
27262
+ return { rowsExpired, bytesFreed, rowsHeldBySync: this.countHeldBySync(opts), done };
27263
+ }
27264
+ countHeldBySync(opts) {
27265
+ if (opts.sweepSyncLane) return 0;
27266
+ const row = this.heldBySyncStmt.get({ cutoff: opts.cutoff });
27267
+ return row.n;
27268
+ }
27269
+ };
27270
+
26163
27271
  // ../../packages/persistence/src/repositories/classified-data.ts
26164
27272
  var SqliteClassifiedDataRepository = class {
26165
27273
  constructor(db) {
@@ -26988,7 +28096,15 @@ function toFlatFindingRow(r) {
26988
28096
  ...r.tool_name === null ? {} : { toolName: r.tool_name },
26989
28097
  eventId: r.event_id,
26990
28098
  ...r.session_id === null ? {} : { sessionId: r.session_id },
26991
- status: deriveInstanceStatus(r)
28099
+ status: deriveInstanceStatus(r),
28100
+ delivery: deriveFindingDelivery({
28101
+ kind: r.kind,
28102
+ syncedAt: r.synced_at,
28103
+ syncClaimedAt: r.sync_claimed_at,
28104
+ syncFailedAt: r.sync_failed_at,
28105
+ syncFailure: r.sync_failure,
28106
+ outboxOwed: r.outbox_owed
28107
+ })
26992
28108
  };
26993
28109
  }
26994
28110
  function encodeGroupCursor(group) {
@@ -27052,7 +28168,10 @@ var FINDING_ROW_COLUMNS_SQL = `f.id AS id, d.rule_id AS rule_id, d.category AS c
27052
28168
  e.tool_name AS tool_name,
27053
28169
  f.audit_event_id AS event_id, e.root_session_id AS session_id,
27054
28170
  e.event_type AS kind, f.finding_key AS finding_key,
27055
- ${latestResolutionStatusSql("f")} AS latest_status`;
28171
+ ${latestResolutionStatusSql("f")} AS latest_status,
28172
+ e.synced_at AS synced_at, e.sync_claimed_at AS sync_claimed_at,
28173
+ e.sync_failed_at AS sync_failed_at, e.sync_failure AS sync_failure,
28174
+ e.outbox_owed AS outbox_owed`;
27056
28175
  var DAY_MS3 = 864e5;
27057
28176
  var SqliteFindingsRepository = class {
27058
28177
  constructor(db) {
@@ -27297,6 +28416,7 @@ var SqliteFindingsRepository = class {
27297
28416
  providers: query.provider,
27298
28417
  actions: query.action,
27299
28418
  statuses: query.status,
28419
+ deliveries: query.deployment,
27300
28420
  tools: query.tool,
27301
28421
  repo: query.repo,
27302
28422
  file: query.file,
@@ -27364,6 +28484,7 @@ var SqliteFindingsRepository = class {
27364
28484
  providers: query.provider,
27365
28485
  actions: query.action,
27366
28486
  statuses: query.status,
28487
+ deliveries: query.deployment,
27367
28488
  tools: query.tool,
27368
28489
  q: query.q
27369
28490
  };
@@ -27627,7 +28748,9 @@ var SqliteFindingsRepository = class {
27627
28748
  )
27628
28749
  );
27629
28750
  for (const row of grouped) {
27630
- if (row.action_taken in byAction) byAction[row.action_taken] = row.c;
28751
+ if (Object.hasOwn(byAction, row.action_taken)) {
28752
+ byAction[row.action_taken] = row.c;
28753
+ }
27631
28754
  }
27632
28755
  const bySeverity = { critical: 0, high: 0, medium: 0, low: 0 };
27633
28756
  const sevRows = allRows(
@@ -27644,7 +28767,9 @@ var SqliteFindingsRepository = class {
27644
28767
  )
27645
28768
  );
27646
28769
  for (const row of sevRows) {
27647
- if (row.severity in bySeverity) bySeverity[row.severity] = row.c;
28770
+ if (Object.hasOwn(bySeverity, row.severity)) {
28771
+ bySeverity[row.severity] = row.c;
28772
+ }
27648
28773
  }
27649
28774
  const categories = ENFORCEABLE_CATEGORIES;
27650
28775
  const enabledRows = allRows(
@@ -27693,525 +28818,6 @@ function isoDay(ms) {
27693
28818
  return new Date(ms).toISOString().slice(0, 10);
27694
28819
  }
27695
28820
 
27696
- // ../../packages/persistence/src/repositories/history-sync.ts
27697
- var STRUCTURAL_EVENT_TYPES = ["session", "llm_call", "tool_call"];
27698
- var TYPE_LIST = STRUCTURAL_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
27699
- var OUTBOX_CAPTURE_EVENT_TYPES = ["prompt", "response", "tool_use"];
27700
- var CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
27701
- var SKIPPED = -1;
27702
- var ROW_COLUMNS = `id,
27703
- parent_id AS parentId,
27704
- root_session_id AS rootSessionId,
27705
- event_type AS eventType,
27706
- host_id AS hostId,
27707
- harness_id AS harnessId,
27708
- source_project_id AS sourceProjectId,
27709
- started_at AS startedAt,
27710
- ended_at AS endedAt,
27711
- severity,
27712
- priority,
27713
- content,
27714
- content_hash AS contentHash,
27715
- attributes`;
27716
- var SqliteHistorySyncRepository = class {
27717
- constructor(db) {
27718
- this.db = db;
27719
- this.ensureRowStmt = db.prepare(`INSERT OR IGNORE INTO history_sync (id) VALUES (1)`);
27720
- this.sessionsStmt = db.prepare(
27721
- `SELECT COALESCE(root_session_id, id) AS sessionId, MIN(started_at) AS earliest
27722
- FROM audit_events
27723
- WHERE synced_at IS NULL
27724
- AND event_type IN (${TYPE_LIST})
27725
- AND started_at < :before
27726
- GROUP BY sessionId
27727
- ORDER BY earliest
27728
- LIMIT :limit`
27729
- );
27730
- this.rowsStmt = db.prepare(
27731
- `SELECT ${ROW_COLUMNS}
27732
- FROM audit_events
27733
- WHERE synced_at IS NULL
27734
- AND event_type IN (${TYPE_LIST})
27735
- AND started_at < :before
27736
- AND COALESCE(root_session_id, id) = :sessionId
27737
- ORDER BY (event_type = 'session') DESC, started_at
27738
- LIMIT :limit`
27739
- );
27740
- this.captureRowsStmt = db.prepare(
27741
- `SELECT ${ROW_COLUMNS}
27742
- FROM audit_events
27743
- WHERE synced_at IS NULL
27744
- AND sync_claimed_at IS NULL
27745
- AND outbox_owed = 1
27746
- AND event_type IN (${CAPTURE_TYPE_LIST})
27747
- AND started_at < :before
27748
- ORDER BY started_at
27749
- LIMIT :limit`
27750
- );
27751
- this.markOwedStmt = db.prepare(
27752
- `UPDATE audit_events SET outbox_owed = 1 WHERE id = :id AND synced_at IS NULL`
27753
- );
27754
- this.markCaptureBacklogOwedStmt = db.prepare(
27755
- `UPDATE audit_events SET outbox_owed = 1
27756
- WHERE synced_at IS NULL
27757
- AND event_type IN (${CAPTURE_TYPE_LIST})
27758
- AND started_at < :before`
27759
- );
27760
- this.stampStmt = db.prepare(
27761
- `UPDATE audit_events SET synced_at = :at, sync_claimed_at = NULL WHERE id = :id`
27762
- );
27763
- this.claimRowStmt = db.prepare(
27764
- `UPDATE audit_events SET sync_claimed_at = :at WHERE id = :id AND synced_at IS NULL`
27765
- );
27766
- this.releaseRowStmt = db.prepare(
27767
- `UPDATE audit_events SET sync_claimed_at = NULL WHERE id = :id`
27768
- );
27769
- this.releaseStaleClaimsStmt = db.prepare(
27770
- `UPDATE audit_events SET sync_claimed_at = NULL
27771
- WHERE sync_claimed_at IS NOT NULL AND sync_claimed_at < :staleBefore`
27772
- );
27773
- this.partitionStmt = db.prepare(
27774
- `SELECT
27775
- SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NULL THEN 1 ELSE 0 END) AS queued,
27776
- SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NOT NULL THEN 1 ELSE 0 END) AS inProgress,
27777
- SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS synced,
27778
- SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0 THEN 1 ELSE 0 END) AS failed,
27779
- COUNT(*) AS total
27780
- FROM audit_events
27781
- WHERE event_type IN (${TYPE_LIST})`
27782
- );
27783
- this.countsStmt = db.prepare(
27784
- `SELECT
27785
- SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
27786
- SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
27787
- SUM(CASE WHEN synced_at = ${String(SKIPPED)} THEN 1 ELSE 0 END) AS skipped
27788
- FROM audit_events
27789
- WHERE event_type IN (${TYPE_LIST})`
27790
- );
27791
- this.captureSkipCountStmt = db.prepare(
27792
- `SELECT COUNT(*) AS skipped
27793
- FROM audit_events
27794
- WHERE synced_at = ${String(SKIPPED)}
27795
- AND event_type IN (${CAPTURE_TYPE_LIST})`
27796
- );
27797
- this.fingerprintStmt = db.prepare(
27798
- `SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
27799
- FROM history_sync WHERE id = 1`
27800
- );
27801
- this.setFingerprintStmt = db.prepare(
27802
- `UPDATE history_sync
27803
- SET endpoint_fingerprint = :fingerprint, backlog_before = :backlogBefore
27804
- WHERE id = 1`
27805
- );
27806
- this.disownCapturesStmt = db.prepare(
27807
- `UPDATE audit_events SET outbox_owed = NULL
27808
- WHERE outbox_owed IS NOT NULL
27809
- AND event_type IN (${CAPTURE_TYPE_LIST})
27810
- AND started_at < :attachedAt`
27811
- );
27812
- this.rearmStmt = db.prepare(
27813
- `UPDATE audit_events SET synced_at = NULL
27814
- WHERE synced_at > 0 AND event_type IN (${TYPE_LIST})`
27815
- );
27816
- this.claimStmt = db.prepare(
27817
- `UPDATE history_sync
27818
- SET owner_pid = :pid, owner_host = :host, acquired_at = :now, heartbeat_at = :now
27819
- WHERE id = 1
27820
- AND (owner_pid IS NULL
27821
- OR heartbeat_at IS NULL
27822
- OR heartbeat_at < :staleBefore
27823
- OR heartbeat_at > :now)`
27824
- );
27825
- this.heartbeatStmt = db.prepare(
27826
- `UPDATE history_sync SET heartbeat_at = :now WHERE id = 1 AND owner_pid = :pid`
27827
- );
27828
- this.releaseStmt = db.prepare(
27829
- `UPDATE history_sync
27830
- SET owner_pid = NULL, owner_host = NULL, acquired_at = NULL, heartbeat_at = NULL
27831
- WHERE id = 1 AND owner_pid = :pid`
27832
- );
27833
- this.closeWindowStmt = db.prepare(
27834
- `UPDATE audit_events SET synced_at = :at
27835
- WHERE synced_at IS NULL
27836
- AND event_type IN (${TYPE_LIST})
27837
- AND started_at >= :attachedAt`
27838
- );
27839
- this.releaseBoundaryStmt = db.prepare(
27840
- `UPDATE history_sync SET backlog_before = NULL WHERE id = 1`
27841
- );
27842
- this.freezeBoundaryStmt = db.prepare(
27843
- `UPDATE history_sync SET backlog_before = :backlogBefore WHERE id = 1`
27844
- );
27845
- this.leaseStmt = db.prepare(
27846
- `SELECT owner_pid AS ownerPid, owner_host AS ownerHost,
27847
- acquired_at AS acquiredAt, heartbeat_at AS heartbeatAt
27848
- FROM history_sync WHERE id = 1`
27849
- );
27850
- this.inspectionsStmt = db.prepare(
27851
- `SELECT d.rule_id AS ruleId,
27852
- d.name AS ruleName,
27853
- d.version AS ruleVersion,
27854
- d.category AS category,
27855
- d.severity AS severity,
27856
- f.span_start AS spanStart,
27857
- f.span_end AS spanEnd,
27858
- f.masked_match AS maskedMatch,
27859
- f.action_taken AS actionTaken,
27860
- f.confidence AS confidence
27861
- FROM inspection_findings f
27862
- JOIN inspection_definitions d ON d.id = f.inspection_definition_id
27863
- WHERE f.audit_event_id = :auditEventId
27864
- ORDER BY f.span_start, f.id`
27865
- );
27866
- }
27867
- db;
27868
- ensureRowStmt;
27869
- sessionsStmt;
27870
- rowsStmt;
27871
- stampStmt;
27872
- countsStmt;
27873
- fingerprintStmt;
27874
- setFingerprintStmt;
27875
- rearmStmt;
27876
- claimStmt;
27877
- heartbeatStmt;
27878
- releaseStmt;
27879
- leaseStmt;
27880
- inspectionsStmt;
27881
- closeWindowStmt;
27882
- releaseBoundaryStmt;
27883
- freezeBoundaryStmt;
27884
- captureRowsStmt;
27885
- markOwedStmt;
27886
- markCaptureBacklogOwedStmt;
27887
- captureSkipCountStmt;
27888
- disownCapturesStmt;
27889
- partitionStmt;
27890
- claimRowStmt;
27891
- releaseRowStmt;
27892
- releaseStaleClaimsStmt;
27893
- /**
27894
- * The masked detections recorded against one tool call.
27895
- *
27896
- * These travel with the event because a tool call's target is not
27897
- * re-inspectable from the event alone — unlike a capture, where the text
27898
- * itself is re-scannable. What crosses is the masked match and the rule that
27899
- * produced it, never the value.
27900
- */
27901
- inspectionsFor(auditEventId) {
27902
- return allRows(this.inspectionsStmt, { auditEventId });
27903
- }
27904
- /**
27905
- * Sessions with structural rows still to send, oldest first.
27906
- *
27907
- * BOUNDED BY THE BACKLOG BOUNDARY, which is the whole correctness of this
27908
- * read. Anything recorded after the machine attached is the live forward
27909
- * path's to deliver; this drain exists for what was recorded before it, and a
27910
- * row both paths send is at best a duplicate request and at worst — for a
27911
- * session root — an overwrite of the inventory ids the live path resolved.
27912
- */
27913
- pendingSessions(limit, before) {
27914
- return allRows(this.sessionsStmt, { limit, before }).map(
27915
- (r) => r.sessionId
27916
- );
27917
- }
27918
- /** One session's undelivered structural rows within the backlog, root first. */
27919
- pendingRows(sessionId, limit, before) {
27920
- return allRows(this.rowsStmt, { sessionId, limit, before });
27921
- }
27922
- /**
27923
- * Captures this machine still owes the deployment, oldest first.
27924
- *
27925
- * Selected by the `outbox_owed` marker the attached forward path writes, not
27926
- * by a time window — see captureRowsStmt for why a window could not express
27927
- * this. `before` is the grace window that leaves a just-recorded capture to
27928
- * the live path.
27929
- */
27930
- pendingCaptureRows(limit, before) {
27931
- return allRows(this.captureRowsStmt, { limit, before });
27932
- }
27933
- /**
27934
- * Record that a capture is OWED to the deployment.
27935
- *
27936
- * Written by the attached forward path when a live send did not confirm
27937
- * delivery, and read by the drain as the whole of its eligibility test. It is
27938
- * a fact rather than an inference: the machine was attached, the send did not
27939
- * land, so the row is owed — which no time window can state, because the same
27940
- * window that holds the rows a past attachment left owed also holds every
27941
- * capture recorded while the machine was DETACHED, and those were never
27942
- * offered to anyone.
27943
- *
27944
- * Idempotent, and never un-set: `markSynced` settling the row is what takes it
27945
- * out of the drain's read.
27946
- */
27947
- markCaptureOwed(id) {
27948
- this.markOwedStmt.run({ id });
27949
- }
27950
- /**
27951
- * Mark every capture already on disk as owed, as of `before`.
27952
- *
27953
- * The consent-time backfill, called once from `aka attach` when a human
27954
- * grants existing-history consent — never from an ongoing drain pass, and
27955
- * never inferred from a boundary that could later move. `before` is the
27956
- * caller's own "now" at the moment consent was granted, so what this marks
27957
- * is exactly the backlog the consent prompt already counted, not whatever a
27958
- * later re-attach or key rotation might widen it to.
27959
- *
27960
- * Returns how many rows matched, for the caller to log or test against. Not a
27961
- * count of NEWLY marked rows — a row still unsynced from an earlier call
27962
- * matches again and is counted again, the same as `UPDATE`'s own `changes`.
27963
- */
27964
- markCaptureBacklogOwed(before) {
27965
- return Number(this.markCaptureBacklogOwedStmt.run({ before }).changes);
27966
- }
27967
- /** Record delivery. Called only AFTER the far side has accepted the rows. */
27968
- markSynced(ids, atMs) {
27969
- this.stampAll(ids, atMs);
27970
- }
27971
- /**
27972
- * Record that a row will never be sent.
27973
- *
27974
- * Reserved for a local defect — a row that cannot be rebuilt into a valid
27975
- * payload. A row that merely failed to reach the deployment stays NULL, so it
27976
- * is retried; marking those would turn one outage into permanent data loss.
27977
- */
27978
- markSkipped(ids) {
27979
- this.stampAll(ids, SKIPPED);
27980
- }
27981
- eachInTransaction(ids, run) {
27982
- if (ids.length === 0) return;
27983
- withTransaction(
27984
- this.db,
27985
- () => {
27986
- for (const id of ids) run(id);
27987
- },
27988
- "IMMEDIATE"
27989
- );
27990
- }
27991
- stampAll(ids, value) {
27992
- if (ids.length === 0) return;
27993
- withTransaction(
27994
- this.db,
27995
- () => {
27996
- for (const id of ids) this.stampStmt.run({ at: value, id });
27997
- },
27998
- "IMMEDIATE"
27999
- );
28000
- }
28001
- /**
28002
- * Claim rows as in-flight.
28003
- *
28004
- * Advisory in exactly the sense the lease is: it records that a send is in
28005
- * progress so a surface can say so, and a lost claim costs a row showing as
28006
- * queued while it is actually being sent. It is not exclusion — the far side
28007
- * settles a duplicate on the row id.
28008
- */
28009
- claimRows(ids, atMs) {
28010
- this.eachInTransaction(ids, (id) => this.claimRowStmt.run({ at: atMs, id }));
28011
- }
28012
- /** Give back a claim without settling — the send failed, the row is queued again. */
28013
- releaseRows(ids) {
28014
- this.eachInTransaction(ids, (id) => this.releaseRowStmt.run({ id }));
28015
- }
28016
- /**
28017
- * Clear claims older than `staleBefore`, and report how many were cleared.
28018
- *
28019
- * A process killed between claiming and settling leaves rows claimed with
28020
- * nothing left to settle them. Without this they read as "sending" for ever.
28021
- */
28022
- releaseStaleClaims(staleBefore) {
28023
- return Number(this.releaseStaleClaimsStmt.run({ staleBefore }).changes);
28024
- }
28025
- /**
28026
- * Every tracked row in exactly one delivery state.
28027
- *
28028
- * Takes no boundary on purpose. The boundary answers "what should the drain
28029
- * pick up now", which is a different question from "what state is this row
28030
- * in" — and a machine that has never attached has no boundary to pass, so
28031
- * requiring one would force a caller to invent one and report the whole store
28032
- * as queued.
28033
- */
28034
- partition() {
28035
- const row = getRow(this.partitionStmt, {});
28036
- return {
28037
- queued: row?.queued ?? 0,
28038
- inProgress: row?.inProgress ?? 0,
28039
- synced: row?.synced ?? 0,
28040
- failed: row?.failed ?? 0,
28041
- total: row?.total ?? 0
28042
- };
28043
- }
28044
- /** `pending` counts only what is inside the backlog; sent and skipped are totals. */
28045
- counts(before) {
28046
- const row = getRow(
28047
- this.countsStmt,
28048
- { before }
28049
- );
28050
- const captures = getRow(this.captureSkipCountStmt);
28051
- return {
28052
- pending: row?.pending ?? 0,
28053
- sent: row?.sent ?? 0,
28054
- skipped: row?.skipped ?? 0,
28055
- capturesSkipped: captures?.skipped ?? 0
28056
- };
28057
- }
28058
- /**
28059
- * The deployment the current stamps were made against, and where its backlog
28060
- * ends.
28061
- *
28062
- * READ-ONLY. An absent row reads as an absent deployment, which is what a
28063
- * machine that has never drained is — and every writer below seeds the row
28064
- * before it needs one, so nothing depends on this creating it. Keeping the
28065
- * write off the gate path matters because the gate runs on every pass while a
28066
- * write has to take the database's write lock.
28067
- */
28068
- deployment() {
28069
- const row = getRow(
28070
- this.fingerprintStmt
28071
- );
28072
- return {
28073
- fingerprint: row?.fingerprint ?? void 0,
28074
- backlogBefore: row?.backlogBefore ?? void 0
28075
- };
28076
- }
28077
- /**
28078
- * Point the ledger at a different deployment, discarding what it recorded
28079
- * about the previous one.
28080
- *
28081
- * Delivery is a fact about ONE recipient: rows sent to the deployment a
28082
- * machine has just left are undelivered as far as the new one is concerned.
28083
- * All four in one transaction, so a crash between them cannot leave stamps
28084
- * attributed to the wrong deployment, a boundary that belongs to another, or
28085
- * a disown with no re-mark to follow it.
28086
- *
28087
- * The boundary is written HERE and only here, which is what freezes it: a
28088
- * re-attach to the SAME deployment (a key rotation) leaves the fingerprint
28089
- * unchanged, so this never runs and the backlog does not widen back over rows
28090
- * the live path has since delivered.
28091
- *
28092
- * `backfillCapturesBefore` is the caller's OWN "now" at the instant a human
28093
- * granted existing-history consent for the deployment this call is arming —
28094
- * a DIFFERENT instant from `backlogBefore`: the re-mark boundary is the GRANT
28095
- * instant, `backlogBefore` is the ATTACH instant, and the two can be far
28096
- * apart. Passed only when that grant is valid, since this method has no way
28097
- * to check consent itself and must not mark a row owed for a machine that
28098
- * never agreed to it. Applied AFTER the disown above, in the SAME
28099
- * transaction: what the disown clears is every marker below `backlogBefore`,
28100
- * which includes this deployment's OWN pre-attach rows — `aka attach` calls
28101
- * `seedCaptureBacklogOwed` at the attach instant, so every row it marks sits
28102
- * on the cleared side of that bound — and the re-mark in the same
28103
- * transaction is what puts those rows back. A crash between the two cannot
28104
- * strand the ledger disowned with nothing re-marked — the transaction either
28105
- * lands whole or not at all, and a fingerprint mismatch that has not yet
28106
- * committed re-enters this method on the very next pass. Omit it (the
28107
- * structural-only tests do) to exercise the disown in isolation.
28108
- *
28109
- * The disown is bounded by `backlogBefore`, which is what keeps it from
28110
- * touching a marker the NEW deployment's OWN live path has already set: B's
28111
- * live path can mark a capture owed from the moment `aka attach` writes the
28112
- * descriptor, before the drain's first pass ever reaches this method, and
28113
- * such a row sits at or after the bound rather than below it. What keeps the
28114
- * disown from eating THIS SAME CALL's own re-mark is the order, not the
28115
- * bound — disown runs first, re-mark second, both inside the one
28116
- * transaction above.
28117
- */
28118
- rearmFor(fingerprint, backlogBefore, backfillCapturesBefore) {
28119
- this.ensureRowStmt.run();
28120
- withTransaction(
28121
- this.db,
28122
- () => {
28123
- const previous = getRow(this.fingerprintStmt)?.fingerprint;
28124
- this.rearmStmt.run();
28125
- if (previous !== null && previous !== void 0 && previous !== fingerprint) {
28126
- this.disownCapturesStmt.run({ attachedAt: backlogBefore });
28127
- }
28128
- if (backfillCapturesBefore !== void 0) {
28129
- this.markCaptureBacklogOwedStmt.run({ before: backfillCapturesBefore });
28130
- }
28131
- this.setFingerprintStmt.run({ fingerprint, backlogBefore });
28132
- },
28133
- "IMMEDIATE"
28134
- );
28135
- }
28136
- /**
28137
- * End the attached period: hand its rows to the live path, and release the
28138
- * boundary so the next attachment can freeze a new one.
28139
- *
28140
- * WITHOUT THIS, a detach and a re-attach to the same deployment leave a window
28141
- * nothing delivers. The fingerprint is unchanged, so the boundary is never
28142
- * re-frozen and stays at the FIRST attachment — while nothing forwards at all
28143
- * during the detached period, because the machine is not attached. Rows
28144
- * recorded in that window sit after the boundary and before the re-attach, so
28145
- * neither path takes them, and the pending count reports none outstanding.
28146
- *
28147
- * Stamping the attached window is not a claim that every one of those rows
28148
- * reached the deployment — the live path drops on failure and says so
28149
- * elsewhere. It records that they were ITS to deliver, which is exactly the
28150
- * status quo: they sit outside the frozen boundary today and are equally never
28151
- * re-sent. Making it explicit is what lets the boundary move.
28152
- *
28153
- * ONE TRANSACTION, so a crash cannot release the boundary while leaving the
28154
- * window unstamped — that half-state would re-send the whole attached period
28155
- * on the next attach, which is the failure the boundary exists to prevent.
28156
- */
28157
- closeAttachedWindow(attachedAtMs, atMs) {
28158
- this.ensureRowStmt.run();
28159
- withTransaction(
28160
- this.db,
28161
- () => {
28162
- const row = getRow(this.fingerprintStmt);
28163
- const from = row?.backlogBefore ?? attachedAtMs;
28164
- this.closeWindowStmt.run({ at: atMs, attachedAt: from });
28165
- this.releaseBoundaryStmt.run();
28166
- },
28167
- "IMMEDIATE"
28168
- );
28169
- }
28170
- /**
28171
- * Freeze a boundary for the deployment already on file, KEEPING the stamps.
28172
- *
28173
- * The re-attach half of the above. Distinct from `rearmFor`, which is for a
28174
- * different deployment and therefore discards what was delivered to the old
28175
- * one: here the recipient is the same, so everything already sent to it stays
28176
- * sent.
28177
- */
28178
- freezeBoundary(backlogBefore) {
28179
- this.ensureRowStmt.run();
28180
- this.freezeBoundaryStmt.run({ backlogBefore });
28181
- }
28182
- /** Take the claim, or report that someone live already holds it. */
28183
- claim(pid, host, nowMs, staleAfterMs) {
28184
- this.ensureRowStmt.run();
28185
- let taken = false;
28186
- withTransaction(
28187
- this.db,
28188
- () => {
28189
- const result = this.claimStmt.run({
28190
- pid,
28191
- host,
28192
- now: nowMs,
28193
- staleBefore: nowMs - staleAfterMs
28194
- });
28195
- taken = result.changes === 1;
28196
- },
28197
- "IMMEDIATE"
28198
- );
28199
- return taken;
28200
- }
28201
- /** Say the holder is still alive. A no-op once the claim has moved on. */
28202
- heartbeat(pid, nowMs) {
28203
- this.heartbeatStmt.run({ now: nowMs, pid });
28204
- }
28205
- /** Give the claim up. Scoped to this holder, so a taken-over claim is left be. */
28206
- release(pid) {
28207
- this.releaseStmt.run({ pid });
28208
- }
28209
- /** Who holds the claim, if anyone. Read-only, for the same reason as above. */
28210
- lease() {
28211
- return getRow(this.leaseStmt);
28212
- }
28213
- };
28214
-
28215
28821
  // ../../packages/persistence/src/repositories/inspection-definitions.ts
28216
28822
  var SqliteInspectionDefinitionsRepository = class {
28217
28823
  constructor(db) {
@@ -28442,6 +29048,7 @@ function overlayManagedSettings(settings, managed, now = () => /* @__PURE__ */ n
28442
29048
  if (values.vaultInlineReveal !== void 0) merged.vaultInlineReveal = values.vaultInlineReveal;
28443
29049
  if (values.dataSharesInPlace !== void 0) merged.dataSharesInPlace = values.dataSharesInPlace;
28444
29050
  if (values.redactFallback !== void 0) merged.redactFallback = values.redactFallback;
29051
+ if (values.bodyRetention !== void 0) merged.bodyRetention = values.bodyRetention;
28445
29052
  if (values.vaultConsent !== void 0) {
28446
29053
  merged.vaultConsent = values.vaultConsent ? (
28447
29054
  // Keep an existing valid grant so its acknowledgedAt survives; mint one
@@ -30949,7 +31556,7 @@ var SqliteSecurityRepository = class {
30949
31556
  ELSE 0
30950
31557
  END) AS open_at_rest
30951
31558
  FROM inspection_findings f
30952
- JOIN audit_events e ON e.id = f.audit_event_id
31559
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
30953
31560
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
30954
31561
  LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
30955
31562
  ON latest.finding_key = f.finding_key
@@ -31175,7 +31782,7 @@ var SqliteSecurityRepository = class {
31175
31782
  this.db.prepare(
31176
31783
  `SELECT e.repo AS repo, count(*) AS c
31177
31784
  FROM inspection_findings f
31178
- JOIN audit_events e ON e.id = f.audit_event_id
31785
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31179
31786
  WHERE e.started_at >= :from AND e.started_at < :to
31180
31787
  AND e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
31181
31788
  AND e.repo IS NOT NULL
@@ -31299,7 +31906,7 @@ var SqliteSecurityRepository = class {
31299
31906
  d.severity AS severity,
31300
31907
  COUNT(*) AS count
31301
31908
  FROM inspection_findings f
31302
- JOIN audit_events e ON e.id = f.audit_event_id
31909
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31303
31910
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
31304
31911
  LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
31305
31912
  ON latest.finding_key = f.finding_key
@@ -31334,7 +31941,7 @@ var SqliteSecurityRepository = class {
31334
31941
  `SELECT e.started_at AS occurred_at, d.severity AS severity, f.action_taken AS action_taken,
31335
31942
  d.rule_id AS rule_id, d.category AS category
31336
31943
  FROM inspection_findings f
31337
- JOIN audit_events e ON e.id = f.audit_event_id
31944
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31338
31945
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
31339
31946
  WHERE e.started_at >= :from AND e.started_at < :to
31340
31947
  AND e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
@@ -32175,6 +32782,7 @@ function openWithPragmas(file2) {
32175
32782
  db.exec("PRAGMA journal_mode = WAL");
32176
32783
  db.exec("PRAGMA busy_timeout = 2000");
32177
32784
  db.exec("PRAGMA foreign_keys = ON");
32785
+ registerSqlFunctions(db);
32178
32786
  } catch (err) {
32179
32787
  closeQuietly(db);
32180
32788
  throw err;
@@ -32204,7 +32812,7 @@ function backupLegacyStore(db, file2) {
32204
32812
  discardStore(file2, backup);
32205
32813
  return backup;
32206
32814
  }
32207
- function openAndInitialize(file2, base) {
32815
+ function openAndInitialize(file2, base, skipTags) {
32208
32816
  let db = openWithPragmas(file2);
32209
32817
  try {
32210
32818
  if (isForeignSqliteLineage(db)) {
@@ -32214,7 +32822,7 @@ function openAndInitialize(file2, base) {
32214
32822
  `Detected an older, incompatible (tenant-bearing) ${DB_FILENAME}; backed it up to ${backup} and created a fresh store.`
32215
32823
  );
32216
32824
  }
32217
- applyMigrations(db, file2);
32825
+ applyMigrations(db, file2, { skipTags });
32218
32826
  tightenPerms(file2);
32219
32827
  const policies = new SqlitePoliciesRepository(db);
32220
32828
  const installedPacks = new SqliteInstalledPacksRepository(db, base);
@@ -32229,6 +32837,7 @@ function openAndInitialize(file2, base) {
32229
32837
  exceptions: new SqliteExceptionsRepository(db),
32230
32838
  resolutions: new SqliteResolutionsRepository(db),
32231
32839
  ruleProbeCache: new SqliteRuleProbeCacheRepository(db),
32840
+ bodyRetention: new SqliteBodyRetentionRepository(db),
32232
32841
  security: new SqliteSecurityRepository(db),
32233
32842
  detections: new SqliteDetectionsRepository(db),
32234
32843
  shares: new SqliteSharesRepository(db),
@@ -32251,7 +32860,8 @@ function openAndInitialize(file2, base) {
32251
32860
  throw err;
32252
32861
  }
32253
32862
  }
32254
- function openLocalDatabase(dir) {
32863
+ var DEFERRED_TAGS = new Set(DEFERRED_MIGRATION_TAGS);
32864
+ function openLocalDatabase(dir, options = {}) {
32255
32865
  ensureDataDirSync(dir);
32256
32866
  const file2 = join7(dir, DB_FILENAME);
32257
32867
  reapStalePartials(file2);
@@ -32263,6 +32873,7 @@ function openLocalDatabase(dir) {
32263
32873
  installedPacks,
32264
32874
  scanLedger,
32265
32875
  historySync,
32876
+ bodyRetention,
32266
32877
  secretVault,
32267
32878
  exceptions,
32268
32879
  resolutions,
@@ -32286,7 +32897,8 @@ function openLocalDatabase(dir) {
32286
32897
  // `dir` is always `<base>/data` — every caller resolves it through
32287
32898
  // `dataDir()` — so its parent is the `~/.aka` base the layout splits into
32288
32899
  // settings/ and data/, and the pack-policy floor needs both halves.
32289
- dirname2(dir)
32900
+ dirname2(dir),
32901
+ options.applyDeferredMigrations === true ? void 0 : DEFERRED_TAGS
32290
32902
  );
32291
32903
  function captureRowId(event) {
32292
32904
  return captureId(
@@ -32479,6 +33091,7 @@ function openLocalDatabase(dir) {
32479
33091
  installedPacks,
32480
33092
  scanLedger,
32481
33093
  historySync,
33094
+ bodyRetention,
32482
33095
  secretVault,
32483
33096
  exceptions,
32484
33097
  resolutions,
@@ -32519,8 +33132,35 @@ function openLocalDatabase(dir) {
32519
33132
 
32520
33133
  // ../../packages/persistence/src/egress-wire.ts
32521
33134
  import { createHash as createHash3 } from "crypto";
33135
+ var PROJECT_KEY_DIGEST_VERSION = "v2";
33136
+ var SCP_FORM = /^(?:[^@/]+@)?([^/:]+):(.+)$/;
33137
+ var DOS_DRIVE = /^[A-Za-z]:[\\/]/;
33138
+ var FILE_URL = /^file:\/\//i;
33139
+ var SCHEME_FORM = /^[a-z][a-z0-9+.-]*:\/\/(?:[^@/]+@)?([^/:]+)(?::\d+)?(\/.*)?$/i;
33140
+ var SLASH = "/".charCodeAt(0);
33141
+ var GIT_SUFFIX = ".git";
33142
+ function trimSlashes(path) {
33143
+ let start = 0;
33144
+ let end = path.length;
33145
+ while (start < end && path.charCodeAt(start) === SLASH) start += 1;
33146
+ while (end > start && path.charCodeAt(end - 1) === SLASH) end -= 1;
33147
+ return path.slice(start, end);
33148
+ }
33149
+ function canonicalGitUrl(url2) {
33150
+ const trimmed = url2.trim();
33151
+ if (DOS_DRIVE.test(trimmed) || FILE_URL.test(trimmed)) return trimmed;
33152
+ const scheme = SCHEME_FORM.exec(trimmed);
33153
+ const scp = scheme === null ? SCP_FORM.exec(trimmed) : null;
33154
+ const host = (scheme?.[1] ?? scp?.[1])?.toLowerCase();
33155
+ if (host === void 0) return trimmed;
33156
+ const path = (scheme === null ? scp?.[2] : scheme[2]) ?? "";
33157
+ const bare = trimSlashes(path);
33158
+ const cleaned = bare.endsWith(GIT_SUFFIX) ? bare.slice(0, -GIT_SUFFIX.length) : bare;
33159
+ return cleaned === "" ? host : `${host}/${cleaned}`;
33160
+ }
32522
33161
  function hashProjectKey(projectKey) {
32523
- return createHash3("sha256").update(projectKey, "utf8").digest("hex");
33162
+ const canonical = projectKey.startsWith("git:") ? `git:${canonicalGitUrl(projectKey.slice("git:".length))}` : projectKey;
33163
+ return createHash3("sha256").update(`${PROJECT_KEY_DIGEST_VERSION}:${canonical}`, "utf8").digest("hex");
32524
33164
  }
32525
33165
  function toIngestHit(hit) {
32526
33166
  return {
@@ -32700,18 +33340,50 @@ function fingerprintValue(key, raw) {
32700
33340
  return createHmac("sha256", key.material).update(raw, "utf8").digest("hex");
32701
33341
  }
32702
33342
 
33343
+ // ../../packages/persistence/src/forward-health.ts
33344
+ import { readFileSync as readFileSync7 } from "fs";
33345
+ import { join as join9 } from "path";
33346
+ var FAILURES = /* @__PURE__ */ new Set([
33347
+ "unauthorized",
33348
+ "forbidden",
33349
+ "unreachable"
33350
+ ]);
33351
+ var BREAKER_COOLDOWN_MS = 3e4;
33352
+ function parseForwardHealth(raw, nowMs) {
33353
+ try {
33354
+ const parsed2 = JSON.parse(raw);
33355
+ if (typeof parsed2 !== "object" || parsed2 === null) return null;
33356
+ const record2 = parsed2;
33357
+ const failures = typeof record2.consecutiveFailures === "number" && record2.consecutiveFailures >= 0 ? record2.consecutiveFailures : 0;
33358
+ const openedAtMs = typeof record2.openedAtMs === "number" && Number.isFinite(record2.openedAtMs) && record2.openedAtMs <= nowMs ? record2.openedAtMs : null;
33359
+ const lastFailure = typeof record2.lastFailure === "string" && FAILURES.has(record2.lastFailure) ? record2.lastFailure : null;
33360
+ return { consecutiveFailures: failures, openedAtMs, lastFailure };
33361
+ } catch {
33362
+ return null;
33363
+ }
33364
+ }
33365
+ function isForwardPaused(health, nowMs) {
33366
+ const openedAtMs = health?.openedAtMs ?? null;
33367
+ if (openedAtMs === null) return false;
33368
+ return nowMs - openedAtMs < BREAKER_COOLDOWN_MS;
33369
+ }
33370
+
32703
33371
  // ../../packages/persistence/src/history-backfill.ts
32704
33372
  import { existsSync as existsSync4 } from "fs";
32705
- import { join as join9 } from "path";
33373
+ import { join as join10 } from "path";
32706
33374
 
32707
33375
  // ../../packages/persistence/src/history-preview.ts
32708
33376
  import { existsSync as existsSync5 } from "fs";
32709
- import { join as join10 } from "path";
33377
+ import { join as join11 } from "path";
32710
33378
  import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
32711
33379
 
33380
+ // ../../packages/persistence/src/history-sync-state.ts
33381
+ import { readFileSync as readFileSync8 } from "fs";
33382
+ import { join as join12 } from "path";
33383
+
32712
33384
  // ../../packages/persistence/src/store-symlinks.ts
32713
33385
  import { existsSync as existsSync6, lstatSync as lstatSync3, readlinkSync, realpathSync, statSync as statSync4 } from "fs";
32714
- import { dirname as dirname3, join as join11, resolve } from "path";
33386
+ import { dirname as dirname3, join as join13, resolve } from "path";
32715
33387
 
32716
33388
  // ../../packages/persistence/src/vault/crypto.ts
32717
33389
  import {
@@ -32824,8 +33496,8 @@ function formatPointer(category, keyVersion, pointerId, tag) {
32824
33496
  // ../../packages/persistence/src/vault/key-provider.ts
32825
33497
  import { execFileSync } from "child_process";
32826
33498
  import { randomBytes as randomBytes2 } from "crypto";
32827
- import { chmodSync as chmodSync3, readFileSync as readFileSync7, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
32828
- import { join as join12 } from "path";
33499
+ import { chmodSync as chmodSync3, readFileSync as readFileSync9, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
33500
+ import { join as join14 } from "path";
32829
33501
  var VAULT_OCCUPANT_REASON = {
32830
33502
  symlink: "the path is a symlink; remove it so a keyring can be created",
32831
33503
  gone: "the path was occupied but holds no keyring (removed while it was being created)",
@@ -32924,7 +33596,7 @@ function claimRotationLock(lock, owner) {
32924
33596
  throw asError(err);
32925
33597
  }
32926
33598
  try {
32927
- writeFileSync3(join12(lock, LOCK_OWNER_FILE), `${owner}
33599
+ writeFileSync3(join14(lock, LOCK_OWNER_FILE), `${owner}
32928
33600
  `, { mode: DATA_FILE_MODE });
32929
33601
  return true;
32930
33602
  } catch (err) {
@@ -32933,7 +33605,7 @@ function claimRotationLock(lock, owner) {
32933
33605
  }
32934
33606
  }
32935
33607
  function acquireRotationLock(keysDir2) {
32936
- const lock = join12(keysDir2, `${VAULT_KEY_FILENAME}.lock`);
33608
+ const lock = join14(keysDir2, `${VAULT_KEY_FILENAME}.lock`);
32937
33609
  const owner = randomBytes2(16).toString("hex");
32938
33610
  if (claimRotationLock(lock, owner)) return { lock, owner };
32939
33611
  let held;
@@ -32960,7 +33632,7 @@ function acquireRotationLock(keysDir2) {
32960
33632
  }
32961
33633
  function releaseRotationLock(lease) {
32962
33634
  try {
32963
- if (readFileSync7(join12(lease.lock, LOCK_OWNER_FILE), "utf8").trim() !== lease.owner) return;
33635
+ if (readFileSync9(join14(lease.lock, LOCK_OWNER_FILE), "utf8").trim() !== lease.owner) return;
32964
33636
  } catch {
32965
33637
  return;
32966
33638
  }
@@ -32981,7 +33653,7 @@ var FileKeyProvider = class {
32981
33653
  this.#keysDir = keysDir2;
32982
33654
  }
32983
33655
  get filePath() {
32984
- return join12(this.#keysDir, VAULT_KEY_FILENAME);
33656
+ return join14(this.#keysDir, VAULT_KEY_FILENAME);
32985
33657
  }
32986
33658
  loadOrCreate() {
32987
33659
  return asAsync(() => {
@@ -33011,7 +33683,7 @@ var FileKeyProvider = class {
33011
33683
  #read() {
33012
33684
  let raw;
33013
33685
  try {
33014
- raw = readFileSync7(this.filePath, "utf8");
33686
+ raw = readFileSync9(this.filePath, "utf8");
33015
33687
  } catch (err) {
33016
33688
  if (err.code === "ENOENT") return null;
33017
33689
  throw err instanceof Error ? err : new Error(String(err));
@@ -33647,11 +34319,11 @@ var SecretVault = class {
33647
34319
 
33648
34320
  // ../../packages/persistence/src/warn-era-cap.ts
33649
34321
  import { existsSync as existsSync7, writeFileSync as writeFileSync4 } from "fs";
33650
- import { join as join13 } from "path";
34322
+ import { join as join15 } from "path";
33651
34323
  var MARKER = "warn-era-capped";
33652
34324
  function capWarnEraEnforcementOnce(db, policyMode, dataDir2) {
33653
34325
  if (policyMode !== "warn") return { capped: 0, skipped: "not-warn" };
33654
- const marker = join13(dataDir2, MARKER);
34326
+ const marker = join15(dataDir2, MARKER);
33655
34327
  if (existsSync7(marker)) return { capped: 0, skipped: "already-run" };
33656
34328
  const capped = db.policies.capCategoryActions();
33657
34329
  writeFileSync4(marker, `${new Date(Date.now()).toISOString()}
@@ -33721,7 +34393,7 @@ function providerFromModelId(modelId) {
33721
34393
  function loadConfig(base = defaultDataDir(), resolveProviderFn = resolveProvider) {
33722
34394
  try {
33723
34395
  ensureLayoutDirSync(base);
33724
- const settingsFile = join14(settingsDir(base), "settings.json");
34396
+ const settingsFile = join16(settingsDir(base), "settings.json");
33725
34397
  if (existsSync8(settingsFile)) tightenFile(settingsFile);
33726
34398
  } catch {
33727
34399
  }
@@ -33745,9 +34417,9 @@ function resolveProviderSafe(resolveProviderFn) {
33745
34417
  }
33746
34418
 
33747
34419
  // ../../packages/plugin-sdk/src/config-inventory.ts
33748
- import { readdirSync as readdirSync2, readFileSync as readFileSync9, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
34420
+ import { readdirSync as readdirSync2, readFileSync as readFileSync11, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
33749
34421
  import { homedir as homedir2 } from "os";
33750
- import { basename as basename3, join as join16 } from "path";
34422
+ import { basename as basename3, join as join18 } from "path";
33751
34423
 
33752
34424
  // ../../packages/detections/src/egress/registry.ts
33753
34425
  var EXTRACTOR_VERSION = "1";
@@ -36791,8 +37463,8 @@ function scanText(text, ruleVersions) {
36791
37463
  }
36792
37464
 
36793
37465
  // ../../packages/plugin-sdk/src/repo.ts
36794
- import { existsSync as existsSync9, readFileSync as readFileSync8, statSync as statSync6 } from "fs";
36795
- import { basename as basename2, dirname as dirname4, isAbsolute, join as join15, sep as sep2 } from "path";
37466
+ import { existsSync as existsSync9, readFileSync as readFileSync10, statSync as statSync6 } from "fs";
37467
+ import { basename as basename2, dirname as dirname4, isAbsolute, join as join17, sep as sep2 } from "path";
36796
37468
  function resolveRepoIdentity(cwd) {
36797
37469
  try {
36798
37470
  const root = findGitRoot(cwd);
@@ -36825,36 +37497,36 @@ function resolveRepoNwo(cwd) {
36825
37497
  function findGitRoot(start) {
36826
37498
  let dir = start;
36827
37499
  for (; ; ) {
36828
- if (existsSync9(join15(dir, ".git"))) return dir;
37500
+ if (existsSync9(join17(dir, ".git"))) return dir;
36829
37501
  const parent = dirname4(dir);
36830
37502
  if (parent === dir) return void 0;
36831
37503
  dir = parent;
36832
37504
  }
36833
37505
  }
36834
37506
  function resolveGitContext(root) {
36835
- const dotGit = join15(root, ".git");
37507
+ const dotGit = join17(root, ".git");
36836
37508
  try {
36837
37509
  if (statSync6(dotGit).isDirectory()) {
36838
- return { configPath: join15(dotGit, "config"), headRoot: root };
37510
+ return { configPath: join17(dotGit, "config"), headRoot: root };
36839
37511
  }
36840
37512
  } catch {
36841
37513
  return void 0;
36842
37514
  }
36843
37515
  const target = /^gitdir:\s*(.+?)\s*$/m.exec(safeRead(dotGit) ?? "")?.[1];
36844
37516
  if (!target) return void 0;
36845
- const gitdir = isAbsolute(target) ? target : join15(root, target);
36846
- if (existsSync9(join15(gitdir, "config"))) {
36847
- return { configPath: join15(gitdir, "config"), headRoot: root };
37517
+ const gitdir = isAbsolute(target) ? target : join17(root, target);
37518
+ if (existsSync9(join17(gitdir, "config"))) {
37519
+ return { configPath: join17(gitdir, "config"), headRoot: root };
36848
37520
  }
36849
- const commonRaw = safeRead(join15(gitdir, "commondir"))?.trim();
37521
+ const commonRaw = safeRead(join17(gitdir, "commondir"))?.trim();
36850
37522
  if (!commonRaw) return void 0;
36851
- const commonGitDir = isAbsolute(commonRaw) ? commonRaw : join15(gitdir, commonRaw);
37523
+ const commonGitDir = isAbsolute(commonRaw) ? commonRaw : join17(gitdir, commonRaw);
36852
37524
  const headRoot = basename2(commonGitDir) === ".git" ? dirname4(commonGitDir) : root;
36853
- return { configPath: join15(commonGitDir, "config"), headRoot };
37525
+ return { configPath: join17(commonGitDir, "config"), headRoot };
36854
37526
  }
36855
37527
  function safeRead(path) {
36856
37528
  try {
36857
- return readFileSync8(path, "utf8");
37529
+ return readFileSync10(path, "utf8");
36858
37530
  } catch {
36859
37531
  return void 0;
36860
37532
  }
@@ -36913,8 +37585,8 @@ import { fileURLToPath } from "url";
36913
37585
  import { Worker } from "worker_threads";
36914
37586
 
36915
37587
  // ../../packages/plugin-sdk/src/host-floor.ts
36916
- import { readFileSync as readFileSync11 } from "fs";
36917
- import { join as join18 } from "path";
37588
+ import { readFileSync as readFileSync13 } from "fs";
37589
+ import { join as join20 } from "path";
36918
37590
 
36919
37591
  // ../../packages/plugin-sdk/src/model-governance.ts
36920
37592
  import {
@@ -36922,11 +37594,11 @@ import {
36922
37594
  fstatSync,
36923
37595
  mkdirSync as mkdirSync2,
36924
37596
  openSync as openSync2,
36925
- readFileSync as readFileSync10,
37597
+ readFileSync as readFileSync12,
36926
37598
  readSync,
36927
37599
  writeFileSync as writeFileSync5
36928
37600
  } from "fs";
36929
- import { join as join17 } from "path";
37601
+ import { join as join19 } from "path";
36930
37602
  var TAIL_BYTES = 256 * 1024;
36931
37603
 
36932
37604
  // ../../packages/plugin-sdk/src/host-floor.ts
@@ -36949,8 +37621,8 @@ var HOST_FLOORS = {
36949
37621
 
36950
37622
  // ../../packages/plugin-sdk/src/ignore-layers.ts
36951
37623
  var import_ignore = __toESM(require_ignore(), 1);
36952
- import { readFileSync as readFileSync12 } from "fs";
36953
- import { join as join19 } from "path";
37624
+ import { readFileSync as readFileSync14 } from "fs";
37625
+ import { join as join21 } from "path";
36954
37626
 
36955
37627
  // ../../packages/plugin-sdk/src/inventory-resolver.ts
36956
37628
  import { arch, hostname as hostname4, platform, release } from "os";
@@ -36982,8 +37654,8 @@ function resolveInventoryContext(input2) {
36982
37654
  }
36983
37655
 
36984
37656
  // ../../packages/plugin-sdk/src/nudge.ts
36985
- import { mkdirSync as mkdirSync3, readFileSync as readFileSync13, writeFileSync as writeFileSync6 } from "fs";
36986
- import { join as join20 } from "path";
37657
+ import { mkdirSync as mkdirSync3, readFileSync as readFileSync15, writeFileSync as writeFileSync6 } from "fs";
37658
+ import { join as join22 } from "path";
36987
37659
 
36988
37660
  // ../../packages/plugin-sdk/src/paths.ts
36989
37661
  import { readdirSync as readdirSync3, realpathSync as realpathSync3 } from "fs";
@@ -37026,7 +37698,7 @@ function createPolicyResolver(bundle) {
37026
37698
 
37027
37699
  // ../../packages/plugin-sdk/src/project-files.ts
37028
37700
  import { existsSync as existsSync11, readdirSync as readdirSync4 } from "fs";
37029
- import { basename as basename5, join as join21 } from "path";
37701
+ import { basename as basename5, join as join23 } from "path";
37030
37702
 
37031
37703
  // ../../packages/plugin-sdk/src/provider-env-antigravity.ts
37032
37704
  var optionalBaseUrl2 = external_exports.preprocess((v) => {
@@ -37062,7 +37734,7 @@ var THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1e3;
37062
37734
 
37063
37735
  // ../../packages/plugin-sdk/src/throttle.ts
37064
37736
  import { mkdirSync as mkdirSync4, statSync as statSync8, writeFileSync as writeFileSync7 } from "fs";
37065
- import { join as join22 } from "path";
37737
+ import { join as join24 } from "path";
37066
37738
 
37067
37739
  // ../../packages/plugin-sdk/src/tokenize.ts
37068
37740
  function redactedPlaceholder(category) {
@@ -37560,10 +38232,10 @@ function parsed(schema, body, route) {
37560
38232
  }
37561
38233
  function withoutTrailingSlashes(endpoint) {
37562
38234
  let end = endpoint.length;
37563
- while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH) end -= 1;
38235
+ while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH2) end -= 1;
37564
38236
  return endpoint.slice(0, end);
37565
38237
  }
37566
- var SLASH = "/".charCodeAt(0);
38238
+ var SLASH2 = "/".charCodeAt(0);
37567
38239
  function createRemoteClient(options) {
37568
38240
  const base = withoutTrailingSlashes(options.endpoint);
37569
38241
  const url2 = (route) => `${base}${route}`;
@@ -37745,11 +38417,11 @@ function withTimeout(promise2, ms) {
37745
38417
  }
37746
38418
 
37747
38419
  // ../../packages/plugin-runtime/src/attached/forward-drops.ts
37748
- import { readFileSync as readFileSync14 } from "fs";
37749
- import { join as join23 } from "path";
38420
+ import { readFileSync as readFileSync16 } from "fs";
38421
+ import { join as join25 } from "path";
37750
38422
  var FORWARD_DROPS_FILENAME = ATTACHED_FORWARD_DROPS_FILENAME;
37751
38423
  function forwardDropsPath(dataDir2) {
37752
- return join23(dataDir2, FORWARD_DROPS_FILENAME);
38424
+ return join25(dataDir2, FORWARD_DROPS_FILENAME);
37753
38425
  }
37754
38426
  function recordForwardDrops(dataDir2, count, nowMs) {
37755
38427
  if (count <= 0) return;
@@ -37767,7 +38439,7 @@ function recordForwardDrops(dataDir2, count, nowMs) {
37767
38439
  }
37768
38440
  function readForwardDrops(dataDir2) {
37769
38441
  try {
37770
- const parsed2 = JSON.parse(readFileSync14(forwardDropsPath(dataDir2), "utf8"));
38442
+ const parsed2 = JSON.parse(readFileSync16(forwardDropsPath(dataDir2), "utf8"));
37771
38443
  if (typeof parsed2 !== "object" || parsed2 === null) return null;
37772
38444
  const record2 = parsed2;
37773
38445
  if (typeof record2.droppedForwards !== "number" || !Number.isFinite(record2.droppedForwards)) {
@@ -37785,9 +38457,8 @@ function readForwardDrops(dataDir2) {
37785
38457
 
37786
38458
  // ../../packages/plugin-runtime/src/attached/forward-policy.ts
37787
38459
  import { randomUUID as randomUUID15 } from "crypto";
37788
- import { readFileSync as readFileSync15 } from "fs";
37789
38460
  import { readFile, rename, writeFile } from "fs/promises";
37790
- import { join as join24 } from "path";
38461
+ import { join as join26 } from "path";
37791
38462
  function isInvalidRequest(err) {
37792
38463
  return typeof err === "object" && err !== null && err.name === "RemoteRequestInvalid";
37793
38464
  }
@@ -37801,31 +38472,12 @@ function isServerRejection(err) {
37801
38472
  var FORWARD_BUDGET_MS = 1500;
37802
38473
  var DECISION_PATH_BUDGET_MS = 800;
37803
38474
  var BREAKER_FAILURE_THRESHOLD = 3;
37804
- var BREAKER_COOLDOWN_MS = 3e4;
37805
38475
  var CLOSED = { consecutiveFailures: 0, openedAtMs: null, lastFailure: null };
37806
- var FAILURES = /* @__PURE__ */ new Set([
37807
- "unauthorized",
37808
- "forbidden",
37809
- "unreachable"
37810
- ]);
37811
38476
  var FORWARD_STATE_FILENAME = ATTACHED_FORWARD_STATE_FILENAME;
37812
38477
  var STATE_FILENAME = FORWARD_STATE_FILENAME;
37813
- function parseBreakerState(raw, nowMs) {
37814
- try {
37815
- const parsed2 = JSON.parse(raw);
37816
- if (typeof parsed2 !== "object" || parsed2 === null) return null;
37817
- const record2 = parsed2;
37818
- const failures = typeof record2.consecutiveFailures === "number" && record2.consecutiveFailures >= 0 ? record2.consecutiveFailures : 0;
37819
- const openedAtMs = typeof record2.openedAtMs === "number" && Number.isFinite(record2.openedAtMs) && record2.openedAtMs <= nowMs ? record2.openedAtMs : null;
37820
- const lastFailure = typeof record2.lastFailure === "string" && FAILURES.has(record2.lastFailure) ? record2.lastFailure : null;
37821
- return { consecutiveFailures: failures, openedAtMs, lastFailure };
37822
- } catch {
37823
- return null;
37824
- }
37825
- }
37826
38478
  function createForwardPolicy(deps) {
37827
38479
  const now = deps.now ?? (() => Date.now());
37828
- const file2 = join24(deps.dir, STATE_FILENAME);
38480
+ const file2 = join26(deps.dir, STATE_FILENAME);
37829
38481
  let state = null;
37830
38482
  let loading = null;
37831
38483
  async function readState() {
@@ -37835,7 +38487,7 @@ function createForwardPolicy(deps) {
37835
38487
  } catch {
37836
38488
  return { ...CLOSED };
37837
38489
  }
37838
- return parseBreakerState(raw, now()) ?? { ...CLOSED };
38490
+ return parseForwardHealth(raw, now()) ?? { ...CLOSED };
37839
38491
  }
37840
38492
  async function load() {
37841
38493
  if (state !== null) return state;
@@ -37881,7 +38533,7 @@ function createForwardPolicy(deps) {
37881
38533
  };
37882
38534
  const at = now();
37883
38535
  if (current.openedAtMs !== null) {
37884
- if (at - current.openedAtMs < BREAKER_COOLDOWN_MS) {
38536
+ if (isForwardPaused(current, at)) {
37885
38537
  return { ok: false, reason: "breaker-open" };
37886
38538
  }
37887
38539
  await persist({
@@ -38418,7 +39070,18 @@ var AttachedDataGateway = class {
38418
39070
  // and the spread above would otherwise drop the field silently — which is
38419
39071
  // exactly what it did, leaving the whole control inert on every device
38420
39072
  // while every test around it stayed green.
38421
- prohibitedModels: cached2.prohibitedModels
39073
+ prohibitedModels: cached2.prohibitedModels,
39074
+ // NAMED for the same reason as the line above, and it is the same defect
39075
+ // if it is not: `...local` above spreads the DEVICE's bundle, so a field
39076
+ // only the cache carries is dropped in silence. That is what left
39077
+ // `prohibitedModels` inert on every attached device with every test
39078
+ // around it green.
39079
+ //
39080
+ // Taken from the cache rather than merged here, because merging it needs
39081
+ // the device's own SETTING — which is not a bundle field and is not in
39082
+ // scope at this seam. The runtime does that merge, raise-only, where both
39083
+ // values are in hand (createPluginRuntime's ensureInitialized).
39084
+ redactFallback: cached2.redactFallback
38422
39085
  // ALSO HONOURED FROM THE CACHE, and not a bundle field at all: each
38423
39086
  // merged policy's own `provenance`. `mergeRaiseOnly` spreads the policies
38424
39087
  // it emits, so an 'authored' policy arriving from the control plane
@@ -38546,10 +39209,6 @@ function toolAuditEvent(input2) {
38546
39209
  };
38547
39210
  }
38548
39211
 
38549
- // ../../packages/plugin-runtime/src/attached/history-state.ts
38550
- import { readFileSync as readFileSync16 } from "fs";
38551
- import { join as join25 } from "path";
38552
-
38553
39212
  // ../../packages/plugin-runtime/src/attached/history-sync.ts
38554
39213
  import { createHash as createHash6 } from "crypto";
38555
39214
  import { hostname as hostname5 } from "os";
@@ -38558,6 +39217,10 @@ import { hostname as hostname5 } from "os";
38558
39217
  var CORRELATION_ID = EventMetadata.shape.correlationId;
38559
39218
  var TRACE_ID = EventMetadata.shape.traceId;
38560
39219
  var EXCEPTION_ID = EventMetadata.shape.exceptionIds.unwrap().element;
39220
+ var REDACT_DEGRADED_TO = EventMetadata.shape.redactDegradedTo.unwrap();
39221
+
39222
+ // ../../packages/plugin-runtime/src/attached/history-sync.ts
39223
+ var CAPTURE_BATCH_BYTES = 1024 * 1024;
38561
39224
 
38562
39225
  // ../../packages/plugin-runtime/src/attached/history-sync-trigger.ts
38563
39226
  import { spawn } from "child_process";
@@ -38599,7 +39262,7 @@ function createPluginBlock(build, policyStore) {
38599
39262
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
38600
39263
  import { randomUUID as randomUUID16 } from "crypto";
38601
39264
  import { readFile as readFile2, rm, writeFile as writeFile2 } from "fs/promises";
38602
- import { join as join26 } from "path";
39265
+ import { join as join27 } from "path";
38603
39266
 
38604
39267
  // ../../packages/plugin-runtime/src/attached/atomic-publish.ts
38605
39268
  import { rename as rename2 } from "fs/promises";
@@ -38623,7 +39286,7 @@ async function publishByRename(tmp, file2, move = rename2) {
38623
39286
 
38624
39287
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
38625
39288
  function createPolicyStore(dir = dataDir()) {
38626
- const file2 = join26(dir, "policy-cache.json");
39289
+ const file2 = join27(dir, "policy-cache.json");
38627
39290
  async function read() {
38628
39291
  try {
38629
39292
  const raw = await readFile2(file2, "utf8");
@@ -38854,11 +39517,11 @@ function readStorePosture(dbPath2) {
38854
39517
  // ../../packages/plugin-runtime/src/attached/posture-store.ts
38855
39518
  import { randomUUID as randomUUID17 } from "crypto";
38856
39519
  import { readFile as readFile3, rm as rm2, writeFile as writeFile3 } from "fs/promises";
38857
- import { join as join27 } from "path";
39520
+ import { join as join28 } from "path";
38858
39521
  var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
38859
39522
  function createPostureStore(dir = settingsDir(), legacyDir) {
38860
- const file2 = join27(dir, "posture-state.json");
38861
- const legacyFile = legacyDir === void 0 ? null : join27(legacyDir, "posture-state.json");
39523
+ const file2 = join28(dir, "posture-state.json");
39524
+ const legacyFile = legacyDir === void 0 ? null : join28(legacyDir, "posture-state.json");
38862
39525
  async function persist(state) {
38863
39526
  await ensureDataDir(dir);
38864
39527
  const tmp = `${file2}.${randomUUID17()}.tmp`;
@@ -38927,7 +39590,7 @@ function createPostureStore(dir = settingsDir(), legacyDir) {
38927
39590
 
38928
39591
  // ../../packages/plugin-runtime/src/attached/sync-state.ts
38929
39592
  import { readFileSync as readFileSync18 } from "fs";
38930
- import { join as join28 } from "path";
39593
+ import { join as join29 } from "path";
38931
39594
 
38932
39595
  // ../../packages/plugin-runtime/src/attached/status.ts
38933
39596
  var REFUSAL_LINES = {
@@ -38948,6 +39611,14 @@ import { spawn as spawn2 } from "child_process";
38948
39611
  import { fileURLToPath as fileURLToPath3 } from "url";
38949
39612
  var SYNC_THROTTLE_MS = 15 * 60 * 1e3;
38950
39613
 
39614
+ // ../../packages/plugin-runtime/src/content-retention-pass.ts
39615
+ var MAX_ROWS_PER_SWEEP = 50 * 1e3;
39616
+
39617
+ // ../../packages/plugin-runtime/src/content-retention-trigger.ts
39618
+ import { spawn as spawn3 } from "child_process";
39619
+ import { fileURLToPath as fileURLToPath4 } from "url";
39620
+ var CONTENT_RETENTION_THROTTLE_MS = 60 * 60 * 1e3;
39621
+
38951
39622
  // ../../packages/plugin-runtime/src/attached/factory.ts
38952
39623
  import { hostname as hostname6 } from "os";
38953
39624
 
@@ -39415,14 +40086,14 @@ import {
39415
40086
  statSync as statSync10,
39416
40087
  writeFileSync as writeFileSync8
39417
40088
  } from "fs";
39418
- import { basename as basename6, dirname as dirname6, isAbsolute as isAbsolute2, join as join30, relative, resolve as resolve2 } from "path";
40089
+ import { basename as basename6, dirname as dirname6, isAbsolute as isAbsolute2, join as join31, relative, resolve as resolve2 } from "path";
39419
40090
 
39420
40091
  // src/history/transcripts.ts
39421
40092
  import { readdirSync as readdirSync5, readFileSync as readFileSync19 } from "fs";
39422
40093
  import { homedir as homedir3 } from "os";
39423
- import { join as join29 } from "path";
40094
+ import { join as join30 } from "path";
39424
40095
  function transcriptsDir(home) {
39425
- return join29(home ?? homedir3(), ".claude", "projects");
40096
+ return join30(home ?? homedir3(), ".claude", "projects");
39426
40097
  }
39427
40098
  function isRecord(value) {
39428
40099
  return typeof value === "object" && value !== null;
@@ -39659,9 +40330,9 @@ import {
39659
40330
  readSync as readSync2,
39660
40331
  writeFileSync as writeFileSync9
39661
40332
  } from "fs";
39662
- import { join as join31 } from "path";
40333
+ import { join as join32 } from "path";
39663
40334
  function offsetsDir(dataDir2) {
39664
- return join31(dataDir2, "usage-offsets");
40335
+ return join32(dataDir2, "usage-offsets");
39665
40336
  }
39666
40337
  var SAFE_SESSION_ID = /^[A-Za-z0-9._-]+$/;
39667
40338
  function safeSessionId(sessionId) {
@@ -39671,7 +40342,7 @@ function safeSessionId(sessionId) {
39671
40342
  return createHash7("sha256").update(sessionId).digest("hex");
39672
40343
  }
39673
40344
  function offsetPath(dataDir2, sessionId) {
39674
- return join31(offsetsDir(dataDir2), safeSessionId(sessionId));
40345
+ return join32(offsetsDir(dataDir2), safeSessionId(sessionId));
39675
40346
  }
39676
40347
  function readOffset(dataDir2, sessionId) {
39677
40348
  try {