@akasecurity/ai-tc-codex 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
@@ -505,6 +505,14 @@ var ATTACHED_FORWARD_DROPS_FILENAME = "attached-forward-drops.json";
505
505
  import { chmodSync as chmodSync2, lstatSync as lstatSync2, readFileSync, rmSync as rmSync3, statSync } from "fs";
506
506
  import { join as join2 } from "path";
507
507
 
508
+ // ../../packages/schema/src/drizzle/deferred-migrations.ts
509
+ var DEFERRED_MIGRATION_TAGS = [
510
+ "0031_audit_capture_by_time_index",
511
+ "0032_audit_capture_by_id_index",
512
+ "0033_audit_capture_location_index",
513
+ "0034_findings_read_indexes"
514
+ ];
515
+
508
516
  // ../../packages/schema/src/drizzle/sqlite-ddl.ts
509
517
  var SQLITE_MIGRATIONS = [
510
518
  {
@@ -622,6 +630,30 @@ var SQLITE_MIGRATIONS = [
622
630
  {
623
631
  tag: "0028_activity_session_probe_indexes",
624
632
  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"
633
+ },
634
+ {
635
+ tag: "0029_audit_capture_rollup_index",
636
+ 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');"
637
+ },
638
+ {
639
+ tag: "0030_audit_content_expiry",
640
+ 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;"
641
+ },
642
+ {
643
+ tag: "0031_audit_capture_by_time_index",
644
+ 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');"
645
+ },
646
+ {
647
+ tag: "0032_audit_capture_by_id_index",
648
+ 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');"
649
+ },
650
+ {
651
+ tag: "0033_audit_capture_location_index",
652
+ 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');"
653
+ },
654
+ {
655
+ tag: "0034_findings_read_indexes",
656
+ 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`);"
625
657
  }
626
658
  ];
627
659
 
@@ -20622,7 +20654,7 @@ var TOOL_TO_HARNESS = {
20622
20654
  [SOURCE_TOOL.ClaudeAi]: HARNESS.ClaudeAi
20623
20655
  };
20624
20656
  function harnessFromTool(tool) {
20625
- return TOOL_TO_HARNESS[tool] ?? tool;
20657
+ return (Object.hasOwn(TOOL_TO_HARNESS, tool) ? TOOL_TO_HARNESS[tool] : void 0) ?? tool;
20626
20658
  }
20627
20659
 
20628
20660
  // ../../packages/schema/src/zod/finding.ts
@@ -20672,6 +20704,15 @@ var FindingCategory = external_exports.enum([
20672
20704
  ]).meta({ id: "FindingCategory" });
20673
20705
  var FindingOrigin = external_exports.enum(["in-flight", "at-rest"]).meta({ id: "FindingOrigin" });
20674
20706
  var FindingStatus = external_exports.enum(["open", "handled", "resolved", "dismissed"]).meta({ id: "FindingStatus" });
20707
+ var SyncFailureReason = external_exports.enum(["deployment_refused", "payload_invalid", "detached_undelivered"]).meta({ id: "SyncFailureReason" });
20708
+ var FindingDeliveryState = external_exports.enum(["sent", "queued", "not_sent", "never_offered", "local_scan"]).meta({ id: "FindingDeliveryState" });
20709
+ var FindingDelivery = external_exports.object({
20710
+ state: FindingDeliveryState,
20711
+ // The delivery time for `sent`; the failure time for `not_sent` when recorded.
20712
+ at: external_exports.iso.datetime().optional(),
20713
+ // Only on `not_sent`, and only when a known reason was recorded.
20714
+ reason: SyncFailureReason.optional()
20715
+ }).meta({ id: "FindingDelivery" });
20675
20716
  var ResolutionMethod = external_exports.enum([
20676
20717
  "enforced-in-flight",
20677
20718
  "fixed-at-source",
@@ -20728,7 +20769,10 @@ var FindingInstance = external_exports.object({
20728
20769
  // The session that event belongs to, when it has one — the seam a
20729
20770
  // per-instance "view session" link needs. Absent for events captured
20730
20771
  // outside a session.
20731
- sessionId: external_exports.string().optional()
20772
+ sessionId: external_exports.string().optional(),
20773
+ // The delivery state of the event above (see FindingDelivery). Optional so
20774
+ // readers that do not project it stay valid.
20775
+ delivery: FindingDelivery.optional()
20732
20776
  }).meta({ id: "FindingInstance" });
20733
20777
  var FindingGroup = external_exports.object({
20734
20778
  id: external_exports.string(),
@@ -20780,7 +20824,10 @@ var FindingFacets = external_exports.object({
20780
20824
  // Host tool (attributes.tool_name). Present only on the instance-level
20781
20825
  // reads, which can filter by it; the type-level read omits the dimension
20782
20826
  // because a group spans tools.
20783
- tool: external_exports.array(FindingFacetItem).optional()
20827
+ tool: external_exports.array(FindingFacetItem).optional(),
20828
+ // Delivery states (FindingDeliveryState). Present only on the
20829
+ // instance-level reads, like `tool`.
20830
+ deployment: external_exports.array(FindingFacetItem).optional()
20784
20831
  }).meta({ id: "FindingFacets" });
20785
20832
  var FindingTypeSummary = FindingGroup.omit({ instances: true, match: true }).meta({
20786
20833
  id: "FindingTypeSummary"
@@ -20891,6 +20938,8 @@ var ListFindingInstancesQuery = external_exports.object({
20891
20938
  // Exact host-tool names (attributes.tool_name, e.g. 'Bash'). A real filter,
20892
20939
  // where the free-text `q` can only match the rendered "via Bash" label.
20893
20940
  tool: external_exports.array(external_exports.string()).optional(),
20941
+ // The delivery state of each finding's event (see FindingDelivery).
20942
+ deployment: external_exports.array(FindingDeliveryState).optional(),
20894
20943
  // Exact repository / file-path matches, for the drill-down out of the
20895
20944
  // locations view. A row whose event carries no repo/file matches neither.
20896
20945
  repo: external_exports.string().optional(),
@@ -20911,6 +20960,10 @@ var ListFindingInstancesResponse = external_exports.object({
20911
20960
  items: external_exports.array(FindingInstanceDetail),
20912
20961
  nextCursor: external_exports.string().nullable()
20913
20962
  }).meta({ id: "ListFindingInstancesResponse" });
20963
+ var ListFindingInstancesPage = external_exports.object({
20964
+ items: external_exports.array(FindingInstanceDetail),
20965
+ nextCursor: external_exports.string().nullable()
20966
+ }).meta({ id: "ListFindingInstancesPage" });
20914
20967
  var FindingLocationSummary = external_exports.object({
20915
20968
  // Opaque, stable, minted from the pair by encodeLocationId. It exists
20916
20969
  // because a location's identity is two values and a URL param carries one:
@@ -20953,6 +21006,8 @@ var ListFindingLocationsQuery = external_exports.object({
20953
21006
  // instances that match, and folds its status from those.
20954
21007
  status: external_exports.array(FindingStatus).optional(),
20955
21008
  tool: external_exports.array(external_exports.string()).optional(),
21009
+ // The delivery state of each finding's event (see FindingDelivery).
21010
+ deployment: external_exports.array(FindingDeliveryState).optional(),
20956
21011
  q: external_exports.string().optional(),
20957
21012
  sessionId: external_exports.string().optional(),
20958
21013
  from: external_exports.iso.datetime().optional(),
@@ -21155,6 +21210,10 @@ var CaptureAttributes = external_exports.object({
21155
21210
  // to 'allow' — the enforcement audit trail's link back to the grant that
21156
21211
  // authorized the bypass.
21157
21212
  exception_ids: external_exports.array(external_exports.guid()).optional(),
21213
+ // The persisted spellings of EventMetadata's messageId/conversationId — the
21214
+ // join back to the `llm_call` leaf for the same assistant turn.
21215
+ message_id: external_exports.string().optional(),
21216
+ conversation_id: external_exports.string().optional(),
21158
21217
  // Whole milliseconds this capture's inspection blocked its caller — the
21159
21218
  // plugin's own added latency (see EventMetadata.inspectionMs, whose value
21160
21219
  // this is). Promoted to the `inspection_ms` generated column so the facet is
@@ -21163,7 +21222,19 @@ var CaptureAttributes = external_exports.object({
21163
21222
  // inline json_extract and is not itself an optimization.
21164
21223
  // ABSENT on replayed captures (backfill / worktree scan) and on rows written
21165
21224
  // before the measurement shipped — never present as a placeholder 0.
21166
- inspection_ms: external_exports.number().int().nonnegative().optional()
21225
+ inspection_ms: external_exports.number().int().nonnegative().optional(),
21226
+ // What a `redact` this capture could not carry out became instead (see
21227
+ // EventMetadata.redactDegradedTo, whose value this is). Present only when a
21228
+ // degrade actually happened, so absence is the ordinary case rather than a
21229
+ // reader having to distinguish it from a zero.
21230
+ //
21231
+ // PER CAPTURE, while `inspection_findings.action_taken` is per finding —
21232
+ // so on a multi-finding row this does not say which finding degraded, and
21233
+ // its presence does not mean the fallback decided the capture's action. A
21234
+ // capture denied by another finding's own Block policy carries `block`
21235
+ // here too. The full statement is on EventMetadata.redactDegradedTo; it is
21236
+ // repeated rather than referenced because a store reader opens this file.
21237
+ redact_degraded_to: ActionTaken.optional()
21167
21238
  }).catchall(external_exports.unknown());
21168
21239
  var ToolCallInspection = external_exports.object({
21169
21240
  ruleId: external_exports.string().min(1),
@@ -21362,7 +21433,17 @@ var AuditEvent = external_exports.object({
21362
21433
  /** `share` to a first-party/internal destination. */
21363
21434
  internal: external_exports.boolean(),
21364
21435
  /** Event needs review (e.g. unverified egress). */
21365
- flagged: external_exports.boolean()
21436
+ flagged: external_exports.boolean(),
21437
+ /**
21438
+ * The body this event's `title` is drawn from was cleared by local body
21439
+ * expiry, so an EMPTY title here means "gone", not "never had one".
21440
+ *
21441
+ * A separate flag rather than a sentinel written into `title`: the title is
21442
+ * rendered text, and a store-layer module that invented display copy for it
21443
+ * would be choosing words the view is supposed to choose. Additive and
21444
+ * defaulted, so an older producer still validates.
21445
+ */
21446
+ bodyExpired: external_exports.boolean().default(false)
21366
21447
  }).meta({ id: "ActivityAuditEvent" });
21367
21448
  var ActivitySessionSummary = external_exports.object({
21368
21449
  id: external_exports.string(),
@@ -22817,6 +22898,12 @@ var EventMetadata = external_exports.object({
22817
22898
  // to 'allow' — the enforcement audit trail's link back to the grant that
22818
22899
  // authorized the bypass. Absent on captures where no exception applied.
22819
22900
  exceptionIds: external_exports.array(external_exports.guid()).optional(),
22901
+ // The assistant message this capture belongs to, and the conversation it sits
22902
+ // in — set by the browser extension's network capture so a stored `response`
22903
+ // row can be joined to the `llm_call` leaf describing the same turn. Absent
22904
+ // on every other capture path, which has no such id.
22905
+ messageId: external_exports.string().optional(),
22906
+ conversationId: external_exports.string().optional(),
22820
22907
  // How long THIS capture's inspection blocked its caller, in whole
22821
22908
  // milliseconds — the plugin's own added latency, NOT the LLM call it sat in
22822
22909
  // front of. Measured inside `capture()` (@akasecurity/plugin-sdk) across
@@ -22829,7 +22916,37 @@ var EventMetadata = external_exports.object({
22829
22916
  // Absent is also what every pre-measurement client writes, and what a
22830
22917
  // clock failure degrades to — a reader must treat absence as "not measured"
22831
22918
  // and never as a zero, which would read as "inspection is free".
22832
- inspectionMs: external_exports.number().int().nonnegative().optional()
22919
+ inspectionMs: external_exports.number().int().nonnegative().optional(),
22920
+ // What a `redact` this capture COULD NOT CARRY OUT became instead — the
22921
+ // workspace's `redactFallback`, applied because the field could not be
22922
+ // masked in place (a shell command, a URL, or any argument on a host whose
22923
+ // hook contract offers no rewrite channel).
22924
+ //
22925
+ // It exists because the action alone cannot say why. A finding recorded as
22926
+ // `warn` reads identically whether its detection was ASSIGNED Warn or was
22927
+ // assigned Redact on a field that could not take one — and those are
22928
+ // different facts about the same row: the first is a policy the user chose,
22929
+ // the second is a masking the host could not perform. Absent means no
22930
+ // degrade happened, which is every ordinary capture.
22931
+ //
22932
+ // TWO LIMITS a reader of a stored row has to know, because the grain here
22933
+ // is the CAPTURE while `actionTaken` is per FINDING:
22934
+ //
22935
+ // - It does not say WHICH finding degraded. A capture carrying a degraded
22936
+ // `redact` alongside a finding ASSIGNED the same action stores both
22937
+ // identically and one reason for the pair; attributing it to both
22938
+ // describes the assigned one wrongly, and to neither loses the degrade.
22939
+ // - PRESENCE IS NOT CAUSATION. The value is the action the lost redact
22940
+ // became, not the reason the capture ended as it did — a capture denied
22941
+ // by some other finding's own Block policy still carries `block` here,
22942
+ // and clearing the workspace's fallback would not have let it through.
22943
+ // Gate on the value against what a fallback can produce; never read the
22944
+ // field's presence as "this was the fallback's doing".
22945
+ //
22946
+ // Both are pinned as behaviour in @akasecurity/plugin-sdk's runtime suite.
22947
+ // Closing either means moving the reason onto the finding row, which
22948
+ // already carries its own action.
22949
+ redactDegradedTo: ActionTaken.optional()
22833
22950
  }).meta({ id: "EventMetadata" });
22834
22951
  var Event = external_exports.object({
22835
22952
  id: external_exports.guid(),
@@ -22939,7 +23056,32 @@ var RotateKeyInput = external_exports.object({
22939
23056
  confirmation: external_exports.string()
22940
23057
  });
22941
23058
 
23059
+ // ../../packages/schema/src/zod/finding-delivery.ts
23060
+ var KNOWN_REASONS = SyncFailureReason.options;
23061
+ function knownReason(value) {
23062
+ return value !== null && KNOWN_REASONS.includes(value) ? value : void 0;
23063
+ }
23064
+ function deriveFindingDelivery(row) {
23065
+ if (row.kind === "code_change") return { state: "local_scan" };
23066
+ if (row.syncedAt !== null && row.syncedAt > 0) {
23067
+ return { state: "sent", at: epochMillisToIso(row.syncedAt) };
23068
+ }
23069
+ if (row.syncedAt !== null) {
23070
+ const reason = knownReason(row.syncFailure);
23071
+ return {
23072
+ state: "not_sent",
23073
+ ...row.syncFailedAt === null ? {} : { at: epochMillisToIso(row.syncFailedAt) },
23074
+ ...reason === void 0 ? {} : { reason }
23075
+ };
23076
+ }
23077
+ if (row.outboxOwed === 1 || row.syncClaimedAt !== null) return { state: "queued" };
23078
+ return { state: "never_offered" };
23079
+ }
23080
+
22942
23081
  // ../../packages/schema/src/zod/findings-group-build.ts
23082
+ function lookupOwn(map2, key) {
23083
+ return Object.hasOwn(map2, key) ? map2[key] : void 0;
23084
+ }
22943
23085
  function toApiAction(dbVal) {
22944
23086
  const map2 = {
22945
23087
  log: "monitored",
@@ -22948,7 +23090,7 @@ function toApiAction(dbVal) {
22948
23090
  warn: "warned",
22949
23091
  allow: "allowed"
22950
23092
  };
22951
- return map2[dbVal] ?? "allowed";
23093
+ return lookupOwn(map2, dbVal) ?? "allowed";
22952
23094
  }
22953
23095
  function toApiCategory(dbVal) {
22954
23096
  if (dbVal === "code_context") return "source_code";
@@ -22956,13 +23098,18 @@ function toApiCategory(dbVal) {
22956
23098
  return parsed2.success ? parsed2.data : "custom";
22957
23099
  }
22958
23100
  function toApiProvider(sourceTool) {
22959
- return TOOL_TO_HARNESS[sourceTool] ?? HARNESS.Api;
23101
+ return lookupOwn(TOOL_TO_HARNESS, sourceTool) ?? HARNESS.Api;
22960
23102
  }
22961
- var STATUS_PRECEDENCE = ["open", "handled", "dismissed", "resolved"];
23103
+ var FINDING_STATUS_PRECEDENCE = [
23104
+ "open",
23105
+ "handled",
23106
+ "dismissed",
23107
+ "resolved"
23108
+ ];
22962
23109
  function foldGroupStatus(instanceStatuses) {
22963
23110
  const statuses = new Set(instanceStatuses.filter((s) => s !== void 0));
22964
23111
  if (statuses.size === 0) return void 0;
22965
- for (const candidate of STATUS_PRECEDENCE) {
23112
+ for (const candidate of FINDING_STATUS_PRECEDENCE) {
22966
23113
  if (statuses.has(candidate)) return candidate;
22967
23114
  }
22968
23115
  return void 0;
@@ -23069,11 +23216,16 @@ function applyFindingFilters(types, opts) {
23069
23216
  }
23070
23217
  return filtered;
23071
23218
  }
23072
- var SEVERITY_ORDER = { critical: 0, high: 1, medium: 2, low: 3 };
23073
- var SEVERITY_RANK = SEVERITY_ORDER;
23219
+ function rankByOrder(members2) {
23220
+ return Object.fromEntries(members2.map((member, index) => [member, index]));
23221
+ }
23222
+ var SEVERITY_RANK = rankByOrder(Severity.options);
23223
+ function severityRank(severity) {
23224
+ return lookupOwn(SEVERITY_RANK, severity);
23225
+ }
23074
23226
  function compareFindingGroupOrder(a, b) {
23075
- const rankA = SEVERITY_RANK[a.severity] ?? -1;
23076
- const rankB = SEVERITY_RANK[b.severity] ?? -1;
23227
+ const rankA = severityRank(a.severity) ?? -1;
23228
+ const rankB = severityRank(b.severity) ?? -1;
23077
23229
  const severityDiff = rankA - rankB;
23078
23230
  if (severityDiff !== 0) return severityDiff;
23079
23231
  const recencyDiff = b.latestDetectedAt.localeCompare(a.latestDetectedAt);
@@ -23148,6 +23300,20 @@ function computeFindingFacets(allTypes, opts) {
23148
23300
  }
23149
23301
 
23150
23302
  // ../../packages/schema/src/zod/findings-flat-build.ts
23303
+ function compareCodePoints(a, b) {
23304
+ const aIter = a[Symbol.iterator]();
23305
+ const bIter = b[Symbol.iterator]();
23306
+ for (; ; ) {
23307
+ const aNext = aIter.next();
23308
+ const bNext = bIter.next();
23309
+ if (aNext.done && bNext.done) return 0;
23310
+ if (aNext.done) return -1;
23311
+ if (bNext.done) return 1;
23312
+ const aPoint = aNext.value.codePointAt(0) ?? 0;
23313
+ const bPoint = bNext.value.codePointAt(0) ?? 0;
23314
+ if (aPoint !== bPoint) return aPoint - bPoint;
23315
+ }
23316
+ }
23151
23317
  function rowHaystack(row) {
23152
23318
  return [
23153
23319
  row.ruleId,
@@ -23172,6 +23338,8 @@ function matchesDimension(row, opts, dimension) {
23172
23338
  return !opts.actions?.length || opts.actions.includes(toApiAction(row.actionTaken));
23173
23339
  case "statuses":
23174
23340
  return !opts.statuses?.length || row.status !== void 0 && opts.statuses.includes(row.status);
23341
+ case "deliveries":
23342
+ return !opts.deliveries?.length || row.delivery !== void 0 && opts.deliveries.includes(row.delivery.state);
23175
23343
  case "tools":
23176
23344
  return !opts.tools?.length || row.toolName !== void 0 && opts.tools.includes(row.toolName);
23177
23345
  // An EMPTY value is a real filter here, not an absent one. The location
@@ -23198,6 +23366,7 @@ var DIMENSIONS = [
23198
23366
  "providers",
23199
23367
  "actions",
23200
23368
  "statuses",
23369
+ "deliveries",
23201
23370
  "tools",
23202
23371
  "repo",
23203
23372
  "file",
@@ -23211,10 +23380,19 @@ function matchesInstanceFilters(row, opts, except) {
23211
23380
  return true;
23212
23381
  }
23213
23382
  function toItems(counts) {
23214
- return [...counts.entries()].map(([value, count]) => ({ value, count })).sort((a, b) => b.count - a.count || a.value.localeCompare(b.value));
23383
+ return [...counts.entries()].map(([value, count]) => ({ value, count })).sort(
23384
+ (a, b) => b.count - a.count || a.value.localeCompare(b.value) || // localeCompare reports canonically-equivalent strings (an NFC and an
23385
+ // NFD spelling of the same text) as equal, so a count tie between
23386
+ // them would otherwise be ordered by whichever the Map iteration
23387
+ // produced. compareCodePoints breaks that tie deterministically, which
23388
+ // makes this a TOTAL order — not one that agrees with SQL collation,
23389
+ // which it need not: foldFacetTuples runs this same sort over grouped
23390
+ // tuples, so both paths order facets identically by construction.
23391
+ compareCodePoints(a.value, b.value)
23392
+ );
23215
23393
  }
23216
- function bump(counts, value) {
23217
- counts.set(value, (counts.get(value) ?? 0) + 1);
23394
+ function bump(counts, value, by = 1) {
23395
+ counts.set(value, (counts.get(value) ?? 0) + by);
23218
23396
  }
23219
23397
  function createInstanceFacetAccumulator(opts) {
23220
23398
  const severity = /* @__PURE__ */ new Map();
@@ -23223,6 +23401,7 @@ function createInstanceFacetAccumulator(opts) {
23223
23401
  const action = /* @__PURE__ */ new Map();
23224
23402
  const status = /* @__PURE__ */ new Map();
23225
23403
  const tool = /* @__PURE__ */ new Map();
23404
+ const deployment = /* @__PURE__ */ new Map();
23226
23405
  return {
23227
23406
  add(row) {
23228
23407
  if (matchesInstanceFilters(row, opts, "severity")) bump(severity, row.severity);
@@ -23237,6 +23416,9 @@ function createInstanceFacetAccumulator(opts) {
23237
23416
  if (row.toolName !== void 0 && matchesInstanceFilters(row, opts, "tools")) {
23238
23417
  bump(tool, row.toolName);
23239
23418
  }
23419
+ if (row.delivery !== void 0 && matchesInstanceFilters(row, opts, "deliveries")) {
23420
+ bump(deployment, row.delivery.state);
23421
+ }
23240
23422
  },
23241
23423
  facets: () => ({
23242
23424
  severity: toItems(severity),
@@ -23244,7 +23426,8 @@ function createInstanceFacetAccumulator(opts) {
23244
23426
  provider: toItems(provider),
23245
23427
  action: toItems(action),
23246
23428
  status: toItems(status),
23247
- tool: toItems(tool)
23429
+ tool: toItems(tool),
23430
+ deployment: toItems(deployment)
23248
23431
  })
23249
23432
  };
23250
23433
  }
@@ -23258,6 +23441,7 @@ function toInstanceDetail(row) {
23258
23441
  ...row.toolName === void 0 ? {} : { toolName: row.toolName },
23259
23442
  eventId: row.eventId,
23260
23443
  ...row.sessionId === void 0 ? {} : { sessionId: row.sessionId },
23444
+ ...row.delivery === void 0 ? {} : { delivery: row.delivery },
23261
23445
  ...row.user === void 0 ? {} : { user: row.user },
23262
23446
  action: toApiAction(row.actionTaken),
23263
23447
  detectedAt: row.occurredAt,
@@ -23272,12 +23456,6 @@ function toInstanceDetail(row) {
23272
23456
  policy: { id: `category:${category}`, name: category }
23273
23457
  };
23274
23458
  }
23275
- var SEVERITY_ORDER2 = {
23276
- critical: 0,
23277
- high: 1,
23278
- medium: 2,
23279
- low: 3
23280
- };
23281
23459
  function newLocationAccumulator() {
23282
23460
  return {
23283
23461
  instanceCount: 0,
@@ -23292,7 +23470,7 @@ function newLocationAccumulator() {
23292
23470
  }
23293
23471
  function addToLocation(acc, row) {
23294
23472
  acc.instanceCount += 1;
23295
- const rank = SEVERITY_ORDER2[row.severity] ?? Number.MAX_SAFE_INTEGER - 1;
23473
+ const rank = severityRank(row.severity) ?? Number.MAX_SAFE_INTEGER - 1;
23296
23474
  if (rank < acc.maxSeverityRank) {
23297
23475
  acc.maxSeverityRank = rank;
23298
23476
  acc.maxSeverity = row.severity;
@@ -23302,15 +23480,15 @@ function addToLocation(acc, row) {
23302
23480
  acc.ruleIds.add(row.ruleId);
23303
23481
  }
23304
23482
  function compareLocationOrder(a, b) {
23305
- const rankA = SEVERITY_ORDER2[a.maxSeverity] ?? -1;
23306
- const rankB = SEVERITY_ORDER2[b.maxSeverity] ?? -1;
23483
+ const rankA = severityRank(a.maxSeverity) ?? -1;
23484
+ const rankB = severityRank(b.maxSeverity) ?? -1;
23307
23485
  if (rankA !== rankB) return rankA - rankB;
23308
23486
  if (a.latestDetectedAt !== b.latestDetectedAt) {
23309
23487
  return a.latestDetectedAt < b.latestDetectedAt ? 1 : -1;
23310
23488
  }
23311
- if (a.repo !== b.repo) return a.repo < b.repo ? -1 : 1;
23312
- if (a.file !== b.file) return a.file < b.file ? -1 : 1;
23313
- return 0;
23489
+ const repoDiff = compareCodePoints(a.repo, b.repo);
23490
+ if (repoDiff !== 0) return repoDiff;
23491
+ return compareCodePoints(a.file, b.file);
23314
23492
  }
23315
23493
  function encodeLocationId(repo, file2) {
23316
23494
  return `${encodePart(repo)}/${encodePart(file2)}`;
@@ -23385,6 +23563,11 @@ var Policy = external_exports.object({
23385
23563
  // test `prohibitedModels` passes and `reversibleRuleIds` fails.
23386
23564
  provenance: PolicyProvenance.optional()
23387
23565
  }).meta({ id: "Policy" });
23566
+ var KNOWN_BUILTIN_IDS = ["monitor", "warn", "redact", "vault", "block"];
23567
+ var BuiltinPolicyId = external_exports.enum(KNOWN_BUILTIN_IDS).meta({ id: "BuiltinPolicyId" });
23568
+ var RedactFallback = BuiltinPolicyId.extract(["monitor", "warn", "block"]).meta({
23569
+ id: "RedactFallback"
23570
+ });
23388
23571
  var PolicyBundle = external_exports.object({
23389
23572
  version: external_exports.string(),
23390
23573
  policies: external_exports.array(Policy),
@@ -23432,6 +23615,16 @@ var PolicyBundle = external_exports.object({
23432
23615
  // control plane), so no name resolution stands between the decision and the
23433
23616
  // comparison.
23434
23617
  prohibitedModels: external_exports.array(external_exports.string()).optional(),
23618
+ // What a resolved `redact` becomes on a field the host cannot rewrite, as
23619
+ // the ORGANIZATION would have it. Merged raise-only against the device's own
23620
+ // `WorkspaceSettings.redactFallback` (see strongerRedactFallback below), so
23621
+ // a control plane can tighten a machine and never loosen one — the same
23622
+ // direction `mergeRaiseOnly` enforces for policies.
23623
+ //
23624
+ // Optional so an older backend, and an older on-disk cache, still parses;
23625
+ // absent leaves the device's own setting in force, which is the behaviour
23626
+ // that predates the field and the safe direction to default.
23627
+ redactFallback: RedactFallback.optional(),
23435
23628
  customKeywords: external_exports.array(external_exports.string()),
23436
23629
  fetchedAt: external_exports.iso.datetime()
23437
23630
  }).meta({ id: "PolicyBundle" });
@@ -23461,11 +23654,6 @@ function severityFloorPolicy(category) {
23461
23654
  const peak = CATEGORY_PEAK_SEVERITY[category];
23462
23655
  return peak === "critical" || peak === "high" ? "warn" : "monitor";
23463
23656
  }
23464
- var KNOWN_BUILTIN_IDS = ["monitor", "warn", "redact", "vault", "block"];
23465
- var BuiltinPolicyId = external_exports.enum(KNOWN_BUILTIN_IDS).meta({ id: "BuiltinPolicyId" });
23466
- var RedactFallback = BuiltinPolicyId.extract(["monitor", "warn", "block"]).meta({
23467
- id: "RedactFallback"
23468
- });
23469
23657
  var BUILTIN_ORDER = KNOWN_BUILTIN_IDS;
23470
23658
  var BUILTIN_POLICY_SPECS = {
23471
23659
  monitor: {
@@ -23761,7 +23949,7 @@ var VaultConsent = external_exports.object({
23761
23949
  });
23762
23950
 
23763
23951
  // ../../packages/schema/src/zod/local.ts
23764
- var WORKSPACE_SETTINGS_SPEC_VERSION = 7;
23952
+ var WORKSPACE_SETTINGS_SPEC_VERSION = 8;
23765
23953
  var MODEL_JUDGE_PAYLOAD_VERSION = 1;
23766
23954
  var HISTORY_SYNC_PAYLOAD_VERSION = 3;
23767
23955
  var RunMode = external_exports.enum(["standalone", "attached"]);
@@ -23786,6 +23974,15 @@ function isHistorySyncConsentValid(consent, endpoint) {
23786
23974
  if (consent === void 0 || endpoint === void 0) return false;
23787
23975
  return consent.payloadVersion === HISTORY_SYNC_PAYLOAD_VERSION && consent.endpoint === endpoint;
23788
23976
  }
23977
+ var BODY_RETENTION_DEFAULT_DAYS = 30;
23978
+ var BodyRetention = external_exports.object({
23979
+ enabled: external_exports.boolean().default(false),
23980
+ // Never 0, and the ceiling is a fat-finger guard rather than a policy
23981
+ // limit — `enabled` is the real gate. A low value cannot reach a row the
23982
+ // sync ledger still owes: the sweep's age filter only ever NARROWS a
23983
+ // candidate set that is already bounded by "delivered, or never owed".
23984
+ retainDays: external_exports.number().int().min(1).max(3650).default(BODY_RETENTION_DEFAULT_DAYS)
23985
+ }).meta({ id: "BodyRetention" });
23789
23986
  var WorkspaceSettings = external_exports.object({
23790
23987
  specVersion: external_exports.number().int().positive().default(WORKSPACE_SETTINGS_SPEC_VERSION),
23791
23988
  runMode: RunMode.default("standalone"),
@@ -23834,7 +24031,13 @@ var WorkspaceSettings = external_exports.object({
23834
24031
  // carry prompt/reply/tool-output text in `content`; the key name predates
23835
24032
  // both widenings. Absent until granted, and a grant for a different endpoint
23836
24033
  // or an older payload no longer counts.
23837
- historySyncConsent: HistorySyncConsent.optional()
24034
+ historySyncConsent: HistorySyncConsent.optional(),
24035
+ // Local body expiry (see BodyRetention). Off until switched on; expiring a
24036
+ // body never removes the row or its findings.
24037
+ bodyRetention: BodyRetention.default({
24038
+ enabled: false,
24039
+ retainDays: BODY_RETENTION_DEFAULT_DAYS
24040
+ })
23838
24041
  });
23839
24042
  function defaultWorkspaceSettings() {
23840
24043
  return WorkspaceSettings.parse({});
@@ -23929,12 +24132,15 @@ function toCaptureAttributes(event) {
23929
24132
  ...metadata?.traceId !== void 0 ? { trace_id: metadata.traceId } : {},
23930
24133
  ...metadata?.exceptionIds !== void 0 ? { exception_ids: metadata.exceptionIds } : {},
23931
24134
  ...metadata?.inspectionMs !== void 0 ? { inspection_ms: metadata.inspectionMs } : {},
24135
+ ...metadata?.redactDegradedTo !== void 0 ? { redact_degraded_to: metadata.redactDegradedTo } : {},
23932
24136
  // `model`/`turnIndex` have no dedicated CaptureAttributes field (no writer
23933
24137
  // has ever populated either), but every legacy metadata key still rides
23934
24138
  // the bag rather than being silently dropped — CaptureAttributes'
23935
24139
  // `.catchall(z.unknown())` carries the long tail.
23936
24140
  ...metadata?.model !== void 0 ? { model: metadata.model } : {},
23937
- ...metadata?.turnIndex !== void 0 ? { turn_index: metadata.turnIndex } : {}
24141
+ ...metadata?.turnIndex !== void 0 ? { turn_index: metadata.turnIndex } : {},
24142
+ ...metadata?.messageId !== void 0 ? { message_id: metadata.messageId } : {},
24143
+ ...metadata?.conversationId !== void 0 ? { conversation_id: metadata.conversationId } : {}
23938
24144
  };
23939
24145
  }
23940
24146
  function captureDefinitionVersion(finding2) {
@@ -23962,13 +24168,22 @@ var ManagedSettingKey = external_exports.enum([
23962
24168
  "vaultInlineReveal",
23963
24169
  "modelJudgeConsent",
23964
24170
  "dataSharesInPlace",
23965
- "redactFallback"
24171
+ "redactFallback",
24172
+ // Pins the toggle and the day count together — see BodyRetention on why the
24173
+ // two are one unit. An administrator mandating a window wants the count
24174
+ // enforced with it, not one a user can widen while the toggle stays on.
24175
+ "bodyRetention"
23966
24176
  ]).meta({ id: "ManagedSettingKey" });
23967
24177
  function isManagedSettingKey(value) {
23968
24178
  return ManagedSettingKey.safeParse(value).success;
23969
24179
  }
23970
24180
  var ManagedSettingsValues = external_exports.object({
23971
24181
  runMode: external_exports.enum(["standalone", "attached"]).optional(),
24182
+ // `controlPlane` and `bodyRetention` are the two nested values, and both are
24183
+ // plain, non-strict objects: a key under either that this build does not know
24184
+ // is stripped and nothing reports it. The unknown-value split in
24185
+ // ManagedSettings below classifies top-level names only, so it stops at
24186
+ // these boundaries.
23972
24187
  controlPlane: external_exports.object({
23973
24188
  endpoint: external_exports.string().min(1),
23974
24189
  label: external_exports.string().min(1).optional()
@@ -23979,7 +24194,8 @@ var ManagedSettingsValues = external_exports.object({
23979
24194
  vaultInlineReveal: external_exports.enum(["masked", "full", "off"]).optional(),
23980
24195
  modelJudgeConsent: external_exports.boolean().optional(),
23981
24196
  dataSharesInPlace: external_exports.boolean().optional(),
23982
- redactFallback: RedactFallback.optional()
24197
+ redactFallback: RedactFallback.optional(),
24198
+ bodyRetention: BodyRetention.optional()
23983
24199
  }).meta({ id: "ManagedSettingsValues" });
23984
24200
  var ManagedSettings = external_exports.object({
23985
24201
  specVersion: external_exports.number().int().positive().default(MANAGED_SETTINGS_SPEC_VERSION),
@@ -23987,7 +24203,21 @@ var ManagedSettings = external_exports.object({
23987
24203
  // decision from a bug. Absent renders as a generic "your organization".
23988
24204
  organization: external_exports.string().min(1).optional(),
23989
24205
  // What the administrator pinned.
23990
- values: ManagedSettingsValues.default({}),
24206
+ //
24207
+ // Parsed as a RECORD rather than as the nested schema, and split below for
24208
+ // the same reason `lockedFields` is parsed as names: a plain `z.object`
24209
+ // drops an unrecognised key and succeeds, so a pin this build does not know
24210
+ // vanished and nothing anywhere said so. A pin with no lock is a supported
24211
+ // shape — it is a DEFAULT the user may still change — so that silence hit
24212
+ // exactly the file an administrator is most likely to write while a fleet
24213
+ // is mid-upgrade.
24214
+ //
24215
+ // Splitting here rather than calling `.strict()`: strict would REFUSE the
24216
+ // file, which is the outcome the lock half already rejected — an older
24217
+ // build then runs entirely unmanaged, every pin and lock gone. A bad KNOWN
24218
+ // value still fails, because the nested schema is re-run over the known
24219
+ // subset and its issues are re-raised on this parse.
24220
+ values: external_exports.record(external_exports.string(), external_exports.unknown()).default({}),
23991
24221
  // Which of those the user may not change. A key here with no matching value
23992
24222
  // freezes whatever the user last chose; a value with no lock is a DEFAULT
23993
24223
  // the user may still override. The two are separable on purpose.
@@ -24000,17 +24230,31 @@ var ManagedSettings = external_exports.object({
24000
24230
  // the fleets most likely to carry a version skew. A name outside the enum
24001
24231
  // is still never HONOURED: the lockable set stays explicit above.
24002
24232
  lockedFields: external_exports.array(external_exports.string()).default([])
24003
- }).transform(({ lockedFields, ...rest }) => {
24233
+ }).transform(({ lockedFields, values, ...rest }, ctx) => {
24004
24234
  const known = [];
24005
24235
  const unknown2 = [];
24006
24236
  for (const name of lockedFields) {
24007
24237
  if (isManagedSettingKey(name)) known.push(name);
24008
24238
  else unknown2.push(name);
24009
24239
  }
24240
+ const knownValues = /* @__PURE__ */ Object.create(null);
24241
+ const unknownValues = [];
24242
+ for (const [name, value] of Object.entries(values)) {
24243
+ if (Object.hasOwn(ManagedSettingsValues.shape, name)) knownValues[name] = value;
24244
+ else unknownValues.push(name);
24245
+ }
24246
+ const pinned = ManagedSettingsValues.safeParse(knownValues);
24247
+ if (!pinned.success) {
24248
+ for (const issue2 of pinned.error.issues)
24249
+ ctx.addIssue({ ...issue2, path: ["values", ...issue2.path] });
24250
+ return external_exports.NEVER;
24251
+ }
24010
24252
  return {
24011
24253
  ...rest,
24254
+ values: pinned.data,
24012
24255
  lockedFields: known,
24013
- ...unknown2.length > 0 ? { unknownLockedFields: unknown2 } : {}
24256
+ ...unknown2.length > 0 ? { unknownLockedFields: unknown2 } : {},
24257
+ ...unknownValues.length > 0 ? { unknownValueFields: unknownValues } : {}
24014
24258
  };
24015
24259
  }).meta({ id: "ManagedSettings" });
24016
24260
 
@@ -24274,7 +24518,23 @@ var SaveSettingsInput = external_exports.object({
24274
24518
  modelJudgeConsent: ModelJudgeConsentChoice,
24275
24519
  historySyncConsent: HistorySyncConsentChoice,
24276
24520
  vaultConsent: external_exports.string(),
24277
- vaultInlineReveal: external_exports.string()
24521
+ vaultInlineReveal: external_exports.string(),
24522
+ // Widened to `string` like its neighbours rather than typed as
24523
+ // `RedactFallback`, on this module's own layering rule: shape here, VALUE at
24524
+ // the call site, so the domain check receives the type it was written for.
24525
+ //
24526
+ // NOT because a narrower schema would reject differently. `parseActionInput`
24527
+ // is a `safeParse` wrapper and throws for no field schema, so either spelling
24528
+ // reaches a recoverable `{ ok: false }` and there is no rejected promise to
24529
+ // trade against. The real cost runs the other way and is the part worth
24530
+ // knowing: a value this schema admits and the domain enum then rejects lands
24531
+ // on the action's shared refusal, which names NO field, where a shape
24532
+ // rejection reaches `malformedInput` and names the schema key.
24533
+ redactFallback: external_exports.string(),
24534
+ // Shape only, the way the enum fields above are strings only: the RANGE is
24535
+ // `BodyRetention`'s and the action checks it there, so there is one place
24536
+ // that decides what a legal horizon is rather than two that can drift.
24537
+ bodyRetention: external_exports.object({ enabled: external_exports.boolean(), retainDays: external_exports.number() })
24278
24538
  });
24279
24539
  var AttachInput = external_exports.object({
24280
24540
  endpoint: external_exports.string(),
@@ -24446,6 +24706,52 @@ function reviewSeverityRank(reasons) {
24446
24706
  return Math.min(...reasons.map((r) => REVIEW_SEVERITY_RANK[r]));
24447
24707
  }
24448
24708
 
24709
+ // ../../packages/schema/src/zod/web-capture.ts
24710
+ var WebUsageSource = external_exports.enum(["site", "estimated", "none"]);
24711
+ var WebUsage = external_exports.object({
24712
+ inputTokens: external_exports.number().int().nonnegative().optional(),
24713
+ outputTokens: external_exports.number().int().nonnegative().optional(),
24714
+ cacheReadInputTokens: external_exports.number().int().nonnegative().optional(),
24715
+ cacheCreationInputTokens: external_exports.number().int().nonnegative().optional()
24716
+ });
24717
+ var WebToolCall = external_exports.object({
24718
+ toolUseId: external_exports.string().min(1),
24719
+ toolName: external_exports.string().min(1),
24720
+ target: external_exports.string().optional(),
24721
+ isError: external_exports.boolean().optional(),
24722
+ inputSize: external_exports.number().int().nonnegative().optional(),
24723
+ outputSize: external_exports.number().int().nonnegative().optional()
24724
+ });
24725
+ var WebExchange = external_exports.object({
24726
+ messageId: external_exports.string().min(1),
24727
+ startedAt: external_exports.iso.datetime(),
24728
+ model: external_exports.string().optional(),
24729
+ usage: WebUsage.optional(),
24730
+ usageSource: WebUsageSource,
24731
+ stopReason: external_exports.string().optional(),
24732
+ conversationId: external_exports.string().optional(),
24733
+ turnIndex: external_exports.number().int().nonnegative().optional(),
24734
+ toolCalls: external_exports.array(WebToolCall).default([]),
24735
+ // Absent when the adapter recovered no text. Capped by the caller at
24736
+ // RESPONSE_TEXT_MAX_BYTES; `truncated` records that the cap was reached, so a
24737
+ // short capture is never mistaken for a short reply.
24738
+ responseText: external_exports.string().optional(),
24739
+ truncated: external_exports.boolean().default(false)
24740
+ });
24741
+ var RESPONSE_TEXT_MAX_BYTES = 2 * 1024 * 1024;
24742
+ var WebCaptureStatus = external_exports.object({
24743
+ patched: external_exports.boolean(),
24744
+ live: external_exports.boolean(),
24745
+ blind: external_exports.boolean(),
24746
+ sendsSeenDom: external_exports.number().int().nonnegative(),
24747
+ exchangesSeenNet: external_exports.number().int().nonnegative(),
24748
+ parseFailures: external_exports.number().int().nonnegative(),
24749
+ unparsedBodies: external_exports.number().int().nonnegative(),
24750
+ // The adapter-declared JSON key paths that were absent from a real payload —
24751
+ // the earliest signal that a site's contract moved.
24752
+ shapeMisses: external_exports.array(external_exports.string()).default([])
24753
+ });
24754
+
24449
24755
  // ../../packages/persistence/src/paths.ts
24450
24756
  import {
24451
24757
  chmodSync,
@@ -24780,6 +25086,22 @@ function discardStore(file2, backup) {
24780
25086
  }
24781
25087
  }
24782
25088
 
25089
+ // ../../packages/persistence/src/internal/sql-functions.ts
25090
+ var utf8 = new TextDecoder();
25091
+ function akaLower(value) {
25092
+ if (value === null) return null;
25093
+ if (typeof value === "string") return value.toLowerCase();
25094
+ if (typeof value === "number" || typeof value === "bigint") return String(value).toLowerCase();
25095
+ return utf8.decode(value).toLowerCase();
25096
+ }
25097
+ function registerSqlFunctions(db) {
25098
+ db.function(
25099
+ "aka_lower",
25100
+ { deterministic: true, directOnly: true, useBigIntArguments: true },
25101
+ akaLower
25102
+ );
25103
+ }
25104
+
24783
25105
  // ../../packages/persistence/src/internal/sql-text.ts
24784
25106
  function escapeLikePattern(s) {
24785
25107
  return s.replace(/\\/g, "\\\\").replace(/%/g, "\\%").replace(/_/g, "\\_");
@@ -24864,6 +25186,11 @@ function schemaObjectExists(db, kind, name) {
24864
25186
  function indexExists(db, name) {
24865
25187
  return schemaObjectExists(db, "index", name);
24866
25188
  }
25189
+ function indexColumns(db, name) {
25190
+ if (!indexExists(db, name)) return [];
25191
+ const columns = db.prepare(`PRAGMA index_info(${name})`).all();
25192
+ return columns.map((c) => c.name).filter((c) => c !== null);
25193
+ }
24867
25194
  function columnNames(db, table, opts) {
24868
25195
  const pragma = opts?.includeGenerated ? "table_xinfo" : "table_info";
24869
25196
  const columns = db.prepare(`PRAGMA ${pragma}(${table})`).all();
@@ -24925,178 +25252,820 @@ function mapRowsTolerant(rows, map2) {
24925
25252
  return out;
24926
25253
  }
24927
25254
 
24928
- // ../../packages/persistence/src/migrations.ts
24929
- function describeObject(object2) {
24930
- return object2.kind === "column" ? `column ${object2.table}.${object2.name}` : `table ${object2.name}`;
24931
- }
24932
- function splitStatements(sql) {
24933
- return sql.split(/-->\s*statement-breakpoint/).map((s) => s.trim()).filter((s) => s.length > 0);
24934
- }
24935
- function createdIndexName(statement) {
24936
- const body = statement.replace(/^(?:\s*--[^\n]*\n?)+/, "").trimStart();
24937
- return /^CREATE (?:UNIQUE )?INDEX (?:IF NOT EXISTS )?`([^`]+)`/.exec(body)?.[1];
25255
+ // ../../packages/persistence/src/internal/outbox-lane.ts
25256
+ var OUTBOX_CAPTURE_EVENT_TYPES = ["prompt", "response", "tool_use"];
25257
+ var OUTBOX_CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25258
+
25259
+ // ../../packages/persistence/src/sync-failure.ts
25260
+ var SYNC_FAILURE_REASONS = SyncFailureReason.options;
25261
+ function syncFailureRejectCondition(column = "sync_failure") {
25262
+ const members2 = SYNC_FAILURE_REASONS.map((r) => `'${r}'`).join(", ");
25263
+ return `NEW.${column} IS NOT NULL AND NEW.${column} NOT IN (${members2})`;
24938
25264
  }
24939
- var LEGACY_DROP_MIGRATION_TAG = "0014_drop_legacy_events_findings";
24940
- function applyMigrations(db, file2) {
24941
- const legacyCount = db.prepare("PRAGMA user_version").get().user_version;
24942
- db.exec(
24943
- "CREATE TABLE IF NOT EXISTS migration_ledger (tag TEXT PRIMARY KEY, applied_at INTEGER NOT NULL)"
24944
- );
24945
- const applied = new Set(
24946
- db.prepare("SELECT tag FROM migration_ledger").all().map((r) => r.tag)
24947
- );
24948
- const preLedgerStore = applied.size === 0 && legacyCount > 0;
24949
- const record2 = db.prepare(
24950
- "INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)"
24951
- );
24952
- for (const [index, migration] of SQLITE_MIGRATIONS.entries()) {
24953
- if (applied.has(migration.tag)) continue;
24954
- if (migration.tag === LEGACY_DROP_MIGRATION_TAG) continue;
24955
- const evidence = evidenceObjects(migration.sql);
24956
- const present = evidence.filter((o) => evidenceExists(db, o));
24957
- if (present.length > 0 && present.length < evidence.length) {
24958
- const missing = evidence.filter((o) => !present.includes(o));
24959
- const message2 = `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.`;
24960
- akaWarn(message2);
24961
- throw new Error(`[aka] ${message2}`);
24962
- }
24963
- const alreadyApplied = evidence.length > 0 ? present.length === evidence.length : preLedgerStore && index < legacyCount;
24964
- const wantsFkOff = /PRAGMA foreign_keys\s*=\s*OFF/i.test(migration.sql);
24965
- const statements = splitStatements(migration.sql);
24966
- if (wantsFkOff) db.exec("PRAGMA foreign_keys = OFF");
24967
- try {
24968
- withTransaction(
24969
- db,
24970
- () => {
24971
- for (const statement of statements) {
24972
- const indexName = createdIndexName(statement);
24973
- if (indexName === void 0) {
24974
- if (alreadyApplied) continue;
24975
- } else if (indexExists(db, indexName)) {
24976
- continue;
24977
- }
24978
- db.exec(statement);
24979
- }
24980
- if (wantsFkOff && !alreadyApplied) {
24981
- const violations = db.prepare("PRAGMA foreign_key_check").all();
24982
- if (violations.length > 0) {
24983
- throw new Error(
24984
- `[aka] sqlite migration ${migration.tag} left ${String(violations.length)} foreign-key violation(s); rolling back.`
24985
- );
24986
- }
24987
- }
24988
- record2.run(migration.tag, Date.now());
24989
- },
24990
- "IMMEDIATE"
24991
- );
24992
- } finally {
24993
- if (wantsFkOff) db.exec("PRAGMA foreign_keys = ON");
24994
- }
25265
+
25266
+ // ../../packages/persistence/src/repositories/history-sync.ts
25267
+ var STRUCTURAL_EVENT_TYPES = ["session", "llm_call", "tool_call"];
25268
+ var TYPE_LIST = STRUCTURAL_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25269
+ var CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_TYPE_LIST;
25270
+ var COUNTED_EVENT_TYPES = [
25271
+ ...STRUCTURAL_EVENT_TYPES,
25272
+ ...OUTBOX_CAPTURE_EVENT_TYPES
25273
+ ];
25274
+ var COUNTED_TYPE_LIST = COUNTED_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25275
+ var PARTITION_BUCKETS = `
25276
+ SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NULL THEN 1 ELSE 0 END) AS queued,
25277
+ SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NOT NULL THEN 1 ELSE 0 END) AS inProgress,
25278
+ SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS synced,
25279
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25280
+ AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
25281
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25282
+ AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached,
25283
+ -- Spelled as what it INCLUDES rather than what it excludes, so a reason
25284
+ -- added later lands in no bucket and fails the sum assertion, instead
25285
+ -- of silently joining this one.
25286
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25287
+ AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
25288
+ THEN 1 ELSE 0 END) AS failed,
25289
+ COUNT(*) AS total`;
25290
+ var COUNTED_SCOPE = `
25291
+ WHERE event_type IN (${COUNTED_TYPE_LIST})
25292
+ AND (
25293
+ event_type IN (${TYPE_LIST})
25294
+ OR synced_at IS NOT NULL
25295
+ OR outbox_owed = 1
25296
+ )`;
25297
+ var SKIPPED = -1;
25298
+ var ROW_COLUMNS = `id,
25299
+ parent_id AS parentId,
25300
+ root_session_id AS rootSessionId,
25301
+ event_type AS eventType,
25302
+ host_id AS hostId,
25303
+ harness_id AS harnessId,
25304
+ source_project_id AS sourceProjectId,
25305
+ started_at AS startedAt,
25306
+ ended_at AS endedAt,
25307
+ severity,
25308
+ priority,
25309
+ content,
25310
+ content_hash AS contentHash,
25311
+ attributes`;
25312
+ var SqliteHistorySyncRepository = class {
25313
+ constructor(db) {
25314
+ this.db = db;
25315
+ this.ensureRowStmt = db.prepare(`INSERT OR IGNORE INTO history_sync (id) VALUES (1)`);
25316
+ this.sessionsStmt = db.prepare(
25317
+ `SELECT COALESCE(root_session_id, id) AS sessionId, MIN(started_at) AS earliest
25318
+ FROM audit_events
25319
+ WHERE synced_at IS NULL
25320
+ AND event_type IN (${TYPE_LIST})
25321
+ AND started_at < :before
25322
+ GROUP BY sessionId
25323
+ ORDER BY earliest
25324
+ LIMIT :limit`
25325
+ );
25326
+ this.rowsStmt = db.prepare(
25327
+ `SELECT ${ROW_COLUMNS}
25328
+ FROM audit_events
25329
+ WHERE synced_at IS NULL
25330
+ AND event_type IN (${TYPE_LIST})
25331
+ AND started_at < :before
25332
+ AND COALESCE(root_session_id, id) = :sessionId
25333
+ ORDER BY (event_type = 'session') DESC, started_at
25334
+ LIMIT :limit`
25335
+ );
25336
+ this.captureRowsStmt = db.prepare(
25337
+ `SELECT ${ROW_COLUMNS}
25338
+ FROM audit_events
25339
+ WHERE synced_at IS NULL
25340
+ AND sync_claimed_at IS NULL
25341
+ AND outbox_owed = 1
25342
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25343
+ AND started_at < :before
25344
+ ORDER BY started_at
25345
+ LIMIT :limit`
25346
+ );
25347
+ this.markOwedStmt = db.prepare(
25348
+ `UPDATE audit_events SET outbox_owed = 1 WHERE id = :id AND synced_at IS NULL`
25349
+ );
25350
+ this.markCaptureBacklogOwedStmt = db.prepare(
25351
+ `UPDATE audit_events SET outbox_owed = 1
25352
+ WHERE synced_at IS NULL
25353
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25354
+ AND started_at < :before`
25355
+ );
25356
+ this.stampStmt = db.prepare(
25357
+ `UPDATE audit_events
25358
+ SET synced_at = :at,
25359
+ sync_claimed_at = NULL,
25360
+ sync_failed_at = :failedAt,
25361
+ sync_failure = :failure
25362
+ WHERE id = :id`
25363
+ );
25364
+ this.claimRowStmt = db.prepare(
25365
+ `UPDATE audit_events SET sync_claimed_at = :at WHERE id = :id AND synced_at IS NULL`
25366
+ );
25367
+ this.releaseRowStmt = db.prepare(
25368
+ `UPDATE audit_events SET sync_claimed_at = NULL WHERE id = :id`
25369
+ );
25370
+ this.releaseStaleClaimsStmt = db.prepare(
25371
+ `UPDATE audit_events SET sync_claimed_at = NULL
25372
+ WHERE sync_claimed_at IS NOT NULL AND sync_claimed_at < :staleBefore`
25373
+ );
25374
+ this.partitionStmt = db.prepare(`SELECT${PARTITION_BUCKETS}
25375
+ FROM audit_events${COUNTED_SCOPE}`);
25376
+ this.partitionByKindStmt = db.prepare(
25377
+ `SELECT event_type AS kind,${PARTITION_BUCKETS}
25378
+ FROM audit_events INDEXED BY idx_audit_events_sync${COUNTED_SCOPE}
25379
+ GROUP BY event_type`
25380
+ );
25381
+ this.countsStmt = db.prepare(
25382
+ `SELECT
25383
+ SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
25384
+ SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
25385
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25386
+ AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
25387
+ THEN 1 ELSE 0 END) AS skipped,
25388
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25389
+ AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
25390
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25391
+ AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached
25392
+ FROM audit_events
25393
+ WHERE event_type IN (${TYPE_LIST})`
25394
+ );
25395
+ this.captureSkipCountStmt = db.prepare(
25396
+ // EVERY sentinel capture, whatever the reason — deliberately NOT split the
25397
+ // way the structural totals are. The split exists because a refusal is
25398
+ // terminal only against the deployment that gave it, and the structural
25399
+ // re-arm frees it on a change of deployment. The capture lane has no such
25400
+ // escape: re-arming a capture would offer one deployment's undelivered
25401
+ // prompts, with their text, to a deployment that never saw them, which is
25402
+ // exactly what disownCapturesStmt exists to prevent. So on this lane both
25403
+ // reasons mean the same thing — this row will not be sent — and splitting
25404
+ // them would put refused captures in a bucket nothing reads and nothing
25405
+ // frees.
25406
+ `SELECT COUNT(*) AS skipped
25407
+ FROM audit_events
25408
+ WHERE synced_at = ${String(SKIPPED)}
25409
+ AND event_type IN (${CAPTURE_TYPE_LIST})`
25410
+ );
25411
+ this.fingerprintStmt = db.prepare(
25412
+ `SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
25413
+ FROM history_sync WHERE id = 1`
25414
+ );
25415
+ this.setFingerprintStmt = db.prepare(
25416
+ `UPDATE history_sync
25417
+ SET endpoint_fingerprint = :fingerprint, backlog_before = :backlogBefore
25418
+ WHERE id = 1`
25419
+ );
25420
+ this.disownCapturesStmt = db.prepare(
25421
+ `UPDATE audit_events SET outbox_owed = NULL
25422
+ WHERE outbox_owed IS NOT NULL
25423
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25424
+ AND started_at < :attachedAt`
25425
+ );
25426
+ this.rearmStmt = db.prepare(
25427
+ `UPDATE audit_events
25428
+ SET synced_at = NULL, sync_failed_at = NULL, sync_failure = NULL
25429
+ WHERE (synced_at > 0
25430
+ OR sync_failure IN ('deployment_refused', 'detached_undelivered'))
25431
+ AND event_type IN (${TYPE_LIST})`
25432
+ );
25433
+ this.claimStmt = db.prepare(
25434
+ `UPDATE history_sync
25435
+ SET owner_pid = :pid, owner_host = :host, acquired_at = :now, heartbeat_at = :now
25436
+ WHERE id = 1
25437
+ AND (owner_pid IS NULL
25438
+ OR heartbeat_at IS NULL
25439
+ OR heartbeat_at < :staleBefore
25440
+ OR heartbeat_at > :now)`
25441
+ );
25442
+ this.heartbeatStmt = db.prepare(
25443
+ `UPDATE history_sync SET heartbeat_at = :now WHERE id = 1 AND owner_pid = :pid`
25444
+ );
25445
+ this.releaseStmt = db.prepare(
25446
+ `UPDATE history_sync
25447
+ SET owner_pid = NULL, owner_host = NULL, acquired_at = NULL, heartbeat_at = NULL
25448
+ WHERE id = 1 AND owner_pid = :pid`
25449
+ );
25450
+ this.closeWindowStmt = db.prepare(
25451
+ `UPDATE audit_events
25452
+ SET synced_at = ${String(SKIPPED)},
25453
+ sync_failed_at = :at,
25454
+ sync_failure = 'detached_undelivered'
25455
+ WHERE synced_at IS NULL
25456
+ AND event_type IN (${TYPE_LIST})
25457
+ AND started_at >= :attachedAt`
25458
+ );
25459
+ this.releaseBoundaryStmt = db.prepare(
25460
+ `UPDATE history_sync SET backlog_before = NULL WHERE id = 1`
25461
+ );
25462
+ this.freezeBoundaryStmt = db.prepare(
25463
+ `UPDATE history_sync SET backlog_before = :backlogBefore WHERE id = 1`
25464
+ );
25465
+ this.leaseStmt = db.prepare(
25466
+ `SELECT owner_pid AS ownerPid, owner_host AS ownerHost,
25467
+ acquired_at AS acquiredAt, heartbeat_at AS heartbeatAt
25468
+ FROM history_sync WHERE id = 1`
25469
+ );
25470
+ this.inspectionsStmt = db.prepare(
25471
+ `SELECT d.rule_id AS ruleId,
25472
+ d.name AS ruleName,
25473
+ d.version AS ruleVersion,
25474
+ d.category AS category,
25475
+ d.severity AS severity,
25476
+ f.span_start AS spanStart,
25477
+ f.span_end AS spanEnd,
25478
+ f.masked_match AS maskedMatch,
25479
+ f.action_taken AS actionTaken,
25480
+ f.confidence AS confidence
25481
+ FROM inspection_findings f
25482
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
25483
+ WHERE f.audit_event_id = :auditEventId
25484
+ ORDER BY f.span_start, f.id`
25485
+ );
24995
25486
  }
24996
- if (legacyCount < SQLITE_MIGRATIONS.length) {
24997
- db.exec(`PRAGMA user_version = ${String(SQLITE_MIGRATIONS.length)}`);
25487
+ db;
25488
+ ensureRowStmt;
25489
+ sessionsStmt;
25490
+ rowsStmt;
25491
+ stampStmt;
25492
+ countsStmt;
25493
+ fingerprintStmt;
25494
+ setFingerprintStmt;
25495
+ rearmStmt;
25496
+ claimStmt;
25497
+ heartbeatStmt;
25498
+ releaseStmt;
25499
+ leaseStmt;
25500
+ inspectionsStmt;
25501
+ closeWindowStmt;
25502
+ releaseBoundaryStmt;
25503
+ freezeBoundaryStmt;
25504
+ captureRowsStmt;
25505
+ markOwedStmt;
25506
+ markCaptureBacklogOwedStmt;
25507
+ captureSkipCountStmt;
25508
+ disownCapturesStmt;
25509
+ partitionStmt;
25510
+ partitionByKindStmt;
25511
+ claimRowStmt;
25512
+ releaseRowStmt;
25513
+ releaseStaleClaimsStmt;
25514
+ /**
25515
+ * The masked detections recorded against one tool call.
25516
+ *
25517
+ * These travel with the event because a tool call's target is not
25518
+ * re-inspectable from the event alone — unlike a capture, where the text
25519
+ * itself is re-scannable. What crosses is the masked match and the rule that
25520
+ * produced it, never the value.
25521
+ */
25522
+ inspectionsFor(auditEventId) {
25523
+ return allRows(this.inspectionsStmt, { auditEventId });
24998
25524
  }
24999
- ensureSyncedAtColumn(db, "audit_events");
25000
- ensureScanLedgerTable(db);
25001
- ensureHistorySyncTable(db);
25002
- ensureBlockedDetectionsTable(db);
25003
- ensureRuleProbeCacheTable(db);
25004
- ensureWriteGateTrigger(db);
25005
- ensureTokenUsageColumns(db);
25006
- reconcileSourceProjectIds(db);
25007
- if (!applied.has(LEGACY_DROP_MIGRATION_TAG)) {
25008
- const drained = runLegacyHistoryBackfill(db);
25009
- if (drained) applyLegacyDropMigration(db, file2);
25525
+ /**
25526
+ * Sessions with structural rows still to send, oldest first.
25527
+ *
25528
+ * BOUNDED BY THE BACKLOG BOUNDARY, which is the whole correctness of this
25529
+ * read. Anything recorded after the machine attached is the live forward
25530
+ * path's to deliver; this drain exists for what was recorded before it, and a
25531
+ * row both paths send is at best a duplicate request and at worst — for a
25532
+ * session root — an overwrite of the inventory ids the live path resolved.
25533
+ */
25534
+ pendingSessions(limit, before) {
25535
+ return allRows(this.sessionsStmt, { limit, before }).map(
25536
+ (r) => r.sessionId
25537
+ );
25010
25538
  }
25011
- }
25012
- function readLegacyTables(db) {
25013
- let holdsRows = false;
25014
- const marks = [];
25015
- for (const table of ["events", "findings"]) {
25016
- try {
25017
- const row = db.prepare(`SELECT count(*) AS n, ifnull(max(rowid), -1) AS hi FROM ${table}`).get();
25018
- if (row === void 0) {
25019
- holdsRows = true;
25020
- marks.push(`${table}:unreadable`);
25021
- continue;
25022
- }
25023
- if (row.n > 0) holdsRows = true;
25024
- marks.push(`${table}:${String(row.n)}:${String(row.hi)}`);
25025
- } catch {
25026
- holdsRows = true;
25027
- marks.push(`${table}:unreadable`);
25028
- }
25539
+ /** One session's undelivered structural rows within the backlog, root first. */
25540
+ pendingRows(sessionId, limit, before) {
25541
+ return allRows(this.rowsStmt, { sessionId, limit, before });
25029
25542
  }
25030
- return { holdsRows, mark: marks.join("|") };
25031
- }
25032
- function applyLegacyDropMigration(db, file2) {
25033
- const migration = SQLITE_MIGRATIONS.find((m) => m.tag === LEGACY_DROP_MIGRATION_TAG);
25034
- if (!migration) return;
25035
- const before = file2 === void 0 ? void 0 : readLegacyTables(db);
25036
- if (file2 !== void 0 && before?.holdsRows === true) {
25037
- try {
25038
- backupBeforeLegacyDrop(db, file2);
25039
- } catch (error61) {
25040
- akaWarn(`legacy events/findings backup failed; deferring the drop: ${String(error61)}`);
25041
- return;
25042
- }
25543
+ /**
25544
+ * Captures this machine still owes the deployment, oldest first.
25545
+ *
25546
+ * Selected by the `outbox_owed` marker the attached forward path writes, not
25547
+ * by a time window — see captureRowsStmt for why a window could not express
25548
+ * this. `before` is the grace window that leaves a just-recorded capture to
25549
+ * the live path.
25550
+ */
25551
+ pendingCaptureRows(limit, before) {
25552
+ return allRows(this.captureRowsStmt, { limit, before });
25043
25553
  }
25044
- try {
25554
+ /**
25555
+ * Record that a capture is OWED to the deployment.
25556
+ *
25557
+ * Written by the attached forward path when a live send did not confirm
25558
+ * delivery, and read by the drain as the whole of its eligibility test. It is
25559
+ * a fact rather than an inference: the machine was attached, the send did not
25560
+ * land, so the row is owed — which no time window can state, because the same
25561
+ * window that holds the rows a past attachment left owed also holds every
25562
+ * capture recorded while the machine was DETACHED, and those were never
25563
+ * offered to anyone.
25564
+ *
25565
+ * Idempotent, and never un-set: `markSynced` settling the row is what takes it
25566
+ * out of the drain's read.
25567
+ */
25568
+ markCaptureOwed(id) {
25569
+ this.markOwedStmt.run({ id });
25570
+ }
25571
+ /**
25572
+ * Mark every capture already on disk as owed, as of `before`.
25573
+ *
25574
+ * The consent-time backfill, called once from `aka attach` when a human
25575
+ * grants existing-history consent — never from an ongoing drain pass, and
25576
+ * never inferred from a boundary that could later move. `before` is the
25577
+ * caller's own "now" at the moment consent was granted, so what this marks
25578
+ * is exactly the backlog the consent prompt already counted, not whatever a
25579
+ * later re-attach or key rotation might widen it to.
25580
+ *
25581
+ * Returns how many rows matched, for the caller to log or test against. Not a
25582
+ * count of NEWLY marked rows — a row still unsynced from an earlier call
25583
+ * matches again and is counted again, the same as `UPDATE`'s own `changes`.
25584
+ */
25585
+ markCaptureBacklogOwed(before) {
25586
+ return Number(this.markCaptureBacklogOwedStmt.run({ before }).changes);
25587
+ }
25588
+ /**
25589
+ * Record delivery. Called only AFTER the far side has accepted the rows.
25590
+ *
25591
+ * CLEARS any failure reason in the same statement. A row that failed against
25592
+ * one deployment and then landed is delivered, and leaving the reason behind
25593
+ * would leave the store holding two contradictory answers about one row —
25594
+ * with the surface free to render either.
25595
+ */
25596
+ markSynced(ids, atMs) {
25597
+ this.stampAll(ids, atMs, null);
25598
+ }
25599
+ /**
25600
+ * Record that THIS MACHINE cannot express the row on the wire.
25601
+ *
25602
+ * Reserved for a local defect — a row that cannot be rebuilt into a valid
25603
+ * payload, or a body the client itself refused to send. It fails identically
25604
+ * against every deployment, so it is terminal everywhere and the re-arm leaves
25605
+ * it alone. A row that merely failed to REACH the deployment stays NULL, so it
25606
+ * is retried; marking those would turn one outage into permanent data loss.
25607
+ */
25608
+ markSkipped(ids, atMs) {
25609
+ this.stampAll(ids, SKIPPED, "payload_invalid", atMs);
25610
+ }
25611
+ /**
25612
+ * Record that THIS DEPLOYMENT refused the row.
25613
+ *
25614
+ * The same sentinel as `markSkipped`, and deliberately so: both stop the row
25615
+ * being re-offered on this lane, and `synced_at` goes on answering whether a
25616
+ * row is outstanding rather than why. What separates them is the reason, and
25617
+ * what the reason buys is the re-arm — a refusal is one deployment's verdict
25618
+ * on one body, so it is terminal only for as long as this machine points at
25619
+ * that deployment, and `rearmFor` clears it when the deployment changes.
25620
+ *
25621
+ * Leaving such a row NULL instead would be worse than the loss it replaces:
25622
+ * these reads carry no cursor, so an unstamped row the deployment refuses is
25623
+ * the head of every subsequent page, and the lane stalls behind it for ever.
25624
+ */
25625
+ markRefused(ids, atMs) {
25626
+ this.stampAll(ids, SKIPPED, "deployment_refused", atMs);
25627
+ }
25628
+ eachInTransaction(ids, run) {
25629
+ if (ids.length === 0) return;
25045
25630
  withTransaction(
25046
- db,
25631
+ this.db,
25047
25632
  () => {
25048
- const alreadyDropped = db.prepare("SELECT 1 FROM migration_ledger WHERE tag = ?").get(migration.tag);
25049
- if (alreadyDropped) return;
25050
- if (before !== void 0 && readLegacyTables(db).mark !== before.mark) {
25051
- akaWarn(
25052
- "legacy events/findings rows changed after the pre-drop snapshot decision; deferring the drop so the next open can copy them first."
25053
- );
25054
- return;
25055
- }
25056
- for (const statement of splitStatements(migration.sql)) {
25057
- db.exec(statement);
25058
- }
25059
- db.prepare("INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)").run(
25060
- migration.tag,
25061
- Date.now()
25062
- );
25633
+ for (const id of ids) run(id);
25063
25634
  },
25064
25635
  "IMMEDIATE"
25065
25636
  );
25066
- } catch (error61) {
25067
- akaWarn(`legacy events/findings drop failed; deferring: ${String(error61)}`);
25068
25637
  }
25069
- }
25070
- function backupBeforeLegacyDrop(db, file2) {
25071
- reapStalePartials(file2);
25072
- const backup = backupPath(file2, "pre-drop");
25073
- snapshotStore(db, backup);
25074
- return backup;
25075
- }
25076
- var TOKEN_USAGE_COLUMNS = [
25077
- {
25078
- name: "input_tokens",
25079
- ddl: "ALTER TABLE audit_events ADD COLUMN input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.input_tokens')) VIRTUAL"
25080
- },
25081
- {
25082
- name: "output_tokens",
25083
- ddl: "ALTER TABLE audit_events ADD COLUMN output_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.output_tokens')) VIRTUAL"
25084
- },
25085
- {
25086
- name: "cache_creation_input_tokens",
25087
- ddl: "ALTER TABLE audit_events ADD COLUMN cache_creation_input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.cache_creation_input_tokens')) VIRTUAL"
25088
- },
25089
- {
25090
- name: "cache_read_input_tokens",
25091
- ddl: "ALTER TABLE audit_events ADD COLUMN cache_read_input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.cache_read_input_tokens')) VIRTUAL"
25092
- },
25093
- {
25094
- name: "model",
25095
- ddl: "ALTER TABLE audit_events ADD COLUMN model text GENERATED ALWAYS AS (json_extract(attributes, '$.model')) VIRTUAL"
25096
- },
25097
- {
25098
- name: "provider",
25099
- ddl: "ALTER TABLE audit_events ADD COLUMN provider text GENERATED ALWAYS AS (json_extract(attributes, '$.provider')) VIRTUAL"
25638
+ stampAll(ids, value, failure, failedAtMs) {
25639
+ if (ids.length === 0) return;
25640
+ const failedAt = failure === null ? null : failedAtMs ?? null;
25641
+ withTransaction(
25642
+ this.db,
25643
+ () => {
25644
+ for (const id of ids) this.stampStmt.run({ at: value, failedAt, failure, id });
25645
+ },
25646
+ "IMMEDIATE"
25647
+ );
25648
+ }
25649
+ /**
25650
+ * Claim rows as in-flight.
25651
+ *
25652
+ * Advisory in exactly the sense the lease is: it records that a send is in
25653
+ * progress so a surface can say so, and a lost claim costs a row showing as
25654
+ * queued while it is actually being sent. It is not exclusion — the far side
25655
+ * settles a duplicate on the row id.
25656
+ */
25657
+ claimRows(ids, atMs) {
25658
+ this.eachInTransaction(ids, (id) => this.claimRowStmt.run({ at: atMs, id }));
25659
+ }
25660
+ /** Give back a claim without settling — the send failed, the row is queued again. */
25661
+ releaseRows(ids) {
25662
+ this.eachInTransaction(ids, (id) => this.releaseRowStmt.run({ id }));
25663
+ }
25664
+ /**
25665
+ * Clear claims older than `staleBefore`, and report how many were cleared.
25666
+ *
25667
+ * A process killed between claiming and settling leaves rows claimed with
25668
+ * nothing left to settle them. Without this they read as "sending" for ever.
25669
+ */
25670
+ releaseStaleClaims(staleBefore) {
25671
+ return Number(this.releaseStaleClaimsStmt.run({ staleBefore }).changes);
25672
+ }
25673
+ /**
25674
+ * Every tracked row in exactly one delivery state.
25675
+ *
25676
+ * Takes no boundary on purpose. The boundary answers "what should the drain
25677
+ * pick up now", which is a different question from "what state is this row
25678
+ * in" — and a machine that has never attached has no boundary to pass, so
25679
+ * requiring one would force a caller to invent one and report the whole store
25680
+ * as queued.
25681
+ */
25682
+ /**
25683
+ * The same partition, one row per kind that a lane carries.
25684
+ *
25685
+ * A kind with nothing to report is ABSENT rather than a row of zeros: the
25686
+ * scope decides which rows exist at all, so a kind that has never been
25687
+ * recorded — or whose captures nobody ever owed — produces no group. A caller
25688
+ * rendering a fixed list of kinds must therefore treat a missing one as "no
25689
+ * rows", never as "zero sent"; the two look identical in a bar and mean
25690
+ * different things.
25691
+ */
25692
+ partitionByKind() {
25693
+ return allRows(
25694
+ this.partitionByKindStmt,
25695
+ {}
25696
+ ).map((row) => ({
25697
+ kind: row.kind,
25698
+ queued: row.queued ?? 0,
25699
+ inProgress: row.inProgress ?? 0,
25700
+ synced: row.synced ?? 0,
25701
+ failed: row.failed ?? 0,
25702
+ refused: row.refused ?? 0,
25703
+ detached: row.detached ?? 0,
25704
+ total: row.total ?? 0
25705
+ }));
25706
+ }
25707
+ partition() {
25708
+ const row = getRow(this.partitionStmt, {});
25709
+ return {
25710
+ queued: row?.queued ?? 0,
25711
+ inProgress: row?.inProgress ?? 0,
25712
+ synced: row?.synced ?? 0,
25713
+ failed: row?.failed ?? 0,
25714
+ refused: row?.refused ?? 0,
25715
+ detached: row?.detached ?? 0,
25716
+ total: row?.total ?? 0
25717
+ };
25718
+ }
25719
+ /** `pending` counts only what is inside the backlog; sent and skipped are totals. */
25720
+ counts(before) {
25721
+ const row = getRow(this.countsStmt, { before });
25722
+ const captures = getRow(this.captureSkipCountStmt);
25723
+ return {
25724
+ pending: row?.pending ?? 0,
25725
+ sent: row?.sent ?? 0,
25726
+ skipped: row?.skipped ?? 0,
25727
+ refused: row?.refused ?? 0,
25728
+ detached: row?.detached ?? 0,
25729
+ capturesSkipped: captures?.skipped ?? 0
25730
+ };
25731
+ }
25732
+ /**
25733
+ * The deployment the current stamps were made against, and where its backlog
25734
+ * ends.
25735
+ *
25736
+ * READ-ONLY. An absent row reads as an absent deployment, which is what a
25737
+ * machine that has never drained is — and every writer below seeds the row
25738
+ * before it needs one, so nothing depends on this creating it. Keeping the
25739
+ * write off the gate path matters because the gate runs on every pass while a
25740
+ * write has to take the database's write lock.
25741
+ */
25742
+ deployment() {
25743
+ const row = getRow(
25744
+ this.fingerprintStmt
25745
+ );
25746
+ return {
25747
+ fingerprint: row?.fingerprint ?? void 0,
25748
+ backlogBefore: row?.backlogBefore ?? void 0
25749
+ };
25750
+ }
25751
+ /**
25752
+ * Point the ledger at a different deployment, discarding what it recorded
25753
+ * about the previous one.
25754
+ *
25755
+ * Delivery is a fact about ONE recipient: rows sent to the deployment a
25756
+ * machine has just left are undelivered as far as the new one is concerned.
25757
+ * All four in one transaction, so a crash between them cannot leave stamps
25758
+ * attributed to the wrong deployment, a boundary that belongs to another, or
25759
+ * a disown with no re-mark to follow it.
25760
+ *
25761
+ * The boundary is written HERE and only here, which is what freezes it: a
25762
+ * re-attach to the SAME deployment (a key rotation) leaves the fingerprint
25763
+ * unchanged, so this never runs and the backlog does not widen back over rows
25764
+ * the live path has since delivered.
25765
+ *
25766
+ * `backfillCapturesBefore` is the caller's OWN "now" at the instant a human
25767
+ * granted existing-history consent for the deployment this call is arming —
25768
+ * a DIFFERENT instant from `backlogBefore`: the re-mark boundary is the GRANT
25769
+ * instant, `backlogBefore` is the ATTACH instant, and the two can be far
25770
+ * apart. Passed only when that grant is valid, since this method has no way
25771
+ * to check consent itself and must not mark a row owed for a machine that
25772
+ * never agreed to it. Applied AFTER the disown above, in the SAME
25773
+ * transaction: what the disown clears is every marker below `backlogBefore`,
25774
+ * which includes this deployment's OWN pre-attach rows — `aka attach` calls
25775
+ * `seedCaptureBacklogOwed` at the attach instant, so every row it marks sits
25776
+ * on the cleared side of that bound — and the re-mark in the same
25777
+ * transaction is what puts those rows back. A crash between the two cannot
25778
+ * strand the ledger disowned with nothing re-marked — the transaction either
25779
+ * lands whole or not at all, and a fingerprint mismatch that has not yet
25780
+ * committed re-enters this method on the very next pass. Omit it (the
25781
+ * structural-only tests do) to exercise the disown in isolation.
25782
+ *
25783
+ * The disown is bounded by `backlogBefore`, which is what keeps it from
25784
+ * touching a marker the NEW deployment's OWN live path has already set: B's
25785
+ * live path can mark a capture owed from the moment `aka attach` writes the
25786
+ * descriptor, before the drain's first pass ever reaches this method, and
25787
+ * such a row sits at or after the bound rather than below it. What keeps the
25788
+ * disown from eating THIS SAME CALL's own re-mark is the order, not the
25789
+ * bound — disown runs first, re-mark second, both inside the one
25790
+ * transaction above.
25791
+ */
25792
+ rearmFor(fingerprint, backlogBefore, backfillCapturesBefore) {
25793
+ this.ensureRowStmt.run();
25794
+ withTransaction(
25795
+ this.db,
25796
+ () => {
25797
+ const previous = getRow(this.fingerprintStmt)?.fingerprint;
25798
+ this.rearmStmt.run();
25799
+ if (previous !== null && previous !== void 0 && previous !== fingerprint) {
25800
+ this.disownCapturesStmt.run({ attachedAt: backlogBefore });
25801
+ }
25802
+ if (backfillCapturesBefore !== void 0) {
25803
+ this.markCaptureBacklogOwedStmt.run({ before: backfillCapturesBefore });
25804
+ }
25805
+ this.setFingerprintStmt.run({ fingerprint, backlogBefore });
25806
+ },
25807
+ "IMMEDIATE"
25808
+ );
25809
+ }
25810
+ /**
25811
+ * End the attached period: hand its rows to the live path, and release the
25812
+ * boundary so the next attachment can freeze a new one.
25813
+ *
25814
+ * WITHOUT THIS, a detach and a re-attach to the same deployment leave a window
25815
+ * nothing delivers. The fingerprint is unchanged, so the boundary is never
25816
+ * re-frozen and stays at the FIRST attachment — while nothing forwards at all
25817
+ * during the detached period, because the machine is not attached. Rows
25818
+ * recorded in that window sit after the boundary and before the re-attach, so
25819
+ * neither path takes them, and the pending count reports none outstanding.
25820
+ *
25821
+ * WHAT IT RECORDS, and what it deliberately does not. These rows were the
25822
+ * closing attachment's to deliver and are no longer outstanding — that is what
25823
+ * lets the boundary move. It is NOT a claim that any of them arrived, and the
25824
+ * distinction is not academic: this used to write a delivery TIME, which every
25825
+ * read treats as delivery, so one detach turned a window of undelivered rows
25826
+ * into a window of delivered ones and no surface could tell. It writes the
25827
+ * skip sentinel and a reason of its own instead, so "no longer owed" and
25828
+ * "received" stop being the same fact.
25829
+ *
25830
+ * A change of deployment still frees them (see the re-arm), because the next
25831
+ * deployment has seen none of this machine's history — so the rows reach it
25832
+ * exactly as they did when this wrote a delivery time.
25833
+ *
25834
+ * ONE TRANSACTION, so a crash cannot release the boundary while leaving the
25835
+ * window unstamped — that half-state would re-send the whole attached period
25836
+ * on the next attach, which is the failure the boundary exists to prevent.
25837
+ */
25838
+ closeAttachedWindow(attachedAtMs, atMs) {
25839
+ this.ensureRowStmt.run();
25840
+ withTransaction(
25841
+ this.db,
25842
+ () => {
25843
+ const row = getRow(this.fingerprintStmt);
25844
+ const from = row?.backlogBefore ?? attachedAtMs;
25845
+ this.closeWindowStmt.run({ at: atMs, attachedAt: from });
25846
+ this.releaseBoundaryStmt.run();
25847
+ },
25848
+ "IMMEDIATE"
25849
+ );
25850
+ }
25851
+ /**
25852
+ * Freeze a boundary for the deployment already on file, KEEPING the stamps.
25853
+ *
25854
+ * The re-attach half of the above. Distinct from `rearmFor`, which is for a
25855
+ * different deployment and therefore discards what was delivered to the old
25856
+ * one: here the recipient is the same, so everything already sent to it stays
25857
+ * sent.
25858
+ */
25859
+ freezeBoundary(backlogBefore) {
25860
+ this.ensureRowStmt.run();
25861
+ this.freezeBoundaryStmt.run({ backlogBefore });
25862
+ }
25863
+ /** Take the claim, or report that someone live already holds it. */
25864
+ claim(pid, host, nowMs, staleAfterMs) {
25865
+ this.ensureRowStmt.run();
25866
+ let taken = false;
25867
+ withTransaction(
25868
+ this.db,
25869
+ () => {
25870
+ const result = this.claimStmt.run({
25871
+ pid,
25872
+ host,
25873
+ now: nowMs,
25874
+ staleBefore: nowMs - staleAfterMs
25875
+ });
25876
+ taken = result.changes === 1;
25877
+ },
25878
+ "IMMEDIATE"
25879
+ );
25880
+ return taken;
25881
+ }
25882
+ /** Say the holder is still alive. A no-op once the claim has moved on. */
25883
+ heartbeat(pid, nowMs) {
25884
+ this.heartbeatStmt.run({ now: nowMs, pid });
25885
+ }
25886
+ /** Give the claim up. Scoped to this holder, so a taken-over claim is left be. */
25887
+ release(pid) {
25888
+ this.releaseStmt.run({ pid });
25889
+ }
25890
+ /** Who holds the claim, if anyone. Read-only, for the same reason as above. */
25891
+ lease() {
25892
+ return getRow(this.leaseStmt);
25893
+ }
25894
+ };
25895
+
25896
+ // ../../packages/persistence/src/migrations.ts
25897
+ function describeObject(object2) {
25898
+ return object2.kind === "column" ? `column ${object2.table}.${object2.name}` : `table ${object2.name}`;
25899
+ }
25900
+ function splitStatements(sql) {
25901
+ return sql.split(/-->\s*statement-breakpoint/).map((s) => s.trim()).filter((s) => s.length > 0);
25902
+ }
25903
+ function createdIndexName(statement) {
25904
+ const body = statement.replace(/^(?:\s*--[^\n]*\n?)+/, "").trimStart();
25905
+ return /^CREATE (?:UNIQUE )?INDEX (?:IF NOT EXISTS )?`([^`]+)`/.exec(body)?.[1];
25906
+ }
25907
+ var LEGACY_DROP_MIGRATION_TAG = "0014_drop_legacy_events_findings";
25908
+ function applyMigrations(db, file2, options = {}) {
25909
+ const legacyCount = db.prepare("PRAGMA user_version").get().user_version;
25910
+ db.exec(
25911
+ "CREATE TABLE IF NOT EXISTS migration_ledger (tag TEXT PRIMARY KEY, applied_at INTEGER NOT NULL)"
25912
+ );
25913
+ const applied = new Set(
25914
+ db.prepare("SELECT tag FROM migration_ledger").all().map((r) => r.tag)
25915
+ );
25916
+ const preLedgerStore = applied.size === 0 && legacyCount > 0;
25917
+ const record2 = db.prepare(
25918
+ "INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)"
25919
+ );
25920
+ for (const [index, migration] of SQLITE_MIGRATIONS.entries()) {
25921
+ if (applied.has(migration.tag)) continue;
25922
+ if (options.skipTags?.has(migration.tag) === true) continue;
25923
+ if (migration.tag === LEGACY_DROP_MIGRATION_TAG) continue;
25924
+ const evidence = evidenceObjects(migration.sql);
25925
+ const present = evidence.filter((o) => evidenceExists(db, o));
25926
+ if (present.length > 0 && present.length < evidence.length) {
25927
+ const missing = evidence.filter((o) => !present.includes(o));
25928
+ const message2 = `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.`;
25929
+ akaWarn(message2);
25930
+ throw new Error(`[aka] ${message2}`);
25931
+ }
25932
+ const alreadyApplied = evidence.length > 0 ? present.length === evidence.length : preLedgerStore && index < legacyCount;
25933
+ const wantsFkOff = /PRAGMA foreign_keys\s*=\s*OFF/i.test(migration.sql);
25934
+ const statements = splitStatements(migration.sql);
25935
+ if (wantsFkOff) db.exec("PRAGMA foreign_keys = OFF");
25936
+ try {
25937
+ withTransaction(
25938
+ db,
25939
+ () => {
25940
+ for (const statement of statements) {
25941
+ const indexName = createdIndexName(statement);
25942
+ if (indexName === void 0) {
25943
+ if (alreadyApplied) continue;
25944
+ } else if (indexExists(db, indexName)) {
25945
+ continue;
25946
+ }
25947
+ db.exec(statement);
25948
+ }
25949
+ if (wantsFkOff && !alreadyApplied) {
25950
+ const violations = db.prepare("PRAGMA foreign_key_check").all();
25951
+ if (violations.length > 0) {
25952
+ throw new Error(
25953
+ `[aka] sqlite migration ${migration.tag} left ${String(violations.length)} foreign-key violation(s); rolling back.`
25954
+ );
25955
+ }
25956
+ }
25957
+ record2.run(migration.tag, Date.now());
25958
+ },
25959
+ "IMMEDIATE"
25960
+ );
25961
+ } finally {
25962
+ if (wantsFkOff) db.exec("PRAGMA foreign_keys = ON");
25963
+ }
25964
+ }
25965
+ if (legacyCount < SQLITE_MIGRATIONS.length) {
25966
+ db.exec(`PRAGMA user_version = ${String(SQLITE_MIGRATIONS.length)}`);
25967
+ }
25968
+ ensureSyncedAtColumn(db, "audit_events");
25969
+ ensureScanLedgerTable(db);
25970
+ ensureHistorySyncTable(db);
25971
+ ensureBlockedDetectionsTable(db);
25972
+ ensureRuleProbeCacheTable(db);
25973
+ ensureWriteGateTrigger(db);
25974
+ ensureTokenUsageColumns(db);
25975
+ reconcileSourceProjectIds(db);
25976
+ if (!applied.has(LEGACY_DROP_MIGRATION_TAG)) {
25977
+ const drained = runLegacyHistoryBackfill(db);
25978
+ if (drained) applyLegacyDropMigration(db, file2);
25979
+ }
25980
+ }
25981
+ function readLegacyTables(db) {
25982
+ let holdsRows = false;
25983
+ const marks = [];
25984
+ for (const table of ["events", "findings"]) {
25985
+ try {
25986
+ const row = db.prepare(`SELECT count(*) AS n, ifnull(max(rowid), -1) AS hi FROM ${table}`).get();
25987
+ if (row === void 0) {
25988
+ holdsRows = true;
25989
+ marks.push(`${table}:unreadable`);
25990
+ continue;
25991
+ }
25992
+ if (row.n > 0) holdsRows = true;
25993
+ marks.push(`${table}:${String(row.n)}:${String(row.hi)}`);
25994
+ } catch {
25995
+ holdsRows = true;
25996
+ marks.push(`${table}:unreadable`);
25997
+ }
25998
+ }
25999
+ return { holdsRows, mark: marks.join("|") };
26000
+ }
26001
+ function applyLegacyDropMigration(db, file2) {
26002
+ const migration = SQLITE_MIGRATIONS.find((m) => m.tag === LEGACY_DROP_MIGRATION_TAG);
26003
+ if (!migration) return;
26004
+ const before = file2 === void 0 ? void 0 : readLegacyTables(db);
26005
+ if (file2 !== void 0 && before?.holdsRows === true) {
26006
+ try {
26007
+ backupBeforeLegacyDrop(db, file2);
26008
+ } catch (error61) {
26009
+ akaWarn(`legacy events/findings backup failed; deferring the drop: ${String(error61)}`);
26010
+ return;
26011
+ }
26012
+ }
26013
+ try {
26014
+ withTransaction(
26015
+ db,
26016
+ () => {
26017
+ const alreadyDropped = db.prepare("SELECT 1 FROM migration_ledger WHERE tag = ?").get(migration.tag);
26018
+ if (alreadyDropped) return;
26019
+ if (before !== void 0 && readLegacyTables(db).mark !== before.mark) {
26020
+ akaWarn(
26021
+ "legacy events/findings rows changed after the pre-drop snapshot decision; deferring the drop so the next open can copy them first."
26022
+ );
26023
+ return;
26024
+ }
26025
+ for (const statement of splitStatements(migration.sql)) {
26026
+ db.exec(statement);
26027
+ }
26028
+ db.prepare("INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)").run(
26029
+ migration.tag,
26030
+ Date.now()
26031
+ );
26032
+ },
26033
+ "IMMEDIATE"
26034
+ );
26035
+ } catch (error61) {
26036
+ akaWarn(`legacy events/findings drop failed; deferring: ${String(error61)}`);
26037
+ }
26038
+ }
26039
+ function backupBeforeLegacyDrop(db, file2) {
26040
+ reapStalePartials(file2);
26041
+ const backup = backupPath(file2, "pre-drop");
26042
+ snapshotStore(db, backup);
26043
+ return backup;
26044
+ }
26045
+ var TOKEN_USAGE_COLUMNS = [
26046
+ {
26047
+ name: "input_tokens",
26048
+ ddl: "ALTER TABLE audit_events ADD COLUMN input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.input_tokens')) VIRTUAL"
26049
+ },
26050
+ {
26051
+ name: "output_tokens",
26052
+ ddl: "ALTER TABLE audit_events ADD COLUMN output_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.output_tokens')) VIRTUAL"
26053
+ },
26054
+ {
26055
+ name: "cache_creation_input_tokens",
26056
+ ddl: "ALTER TABLE audit_events ADD COLUMN cache_creation_input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.cache_creation_input_tokens')) VIRTUAL"
26057
+ },
26058
+ {
26059
+ name: "cache_read_input_tokens",
26060
+ ddl: "ALTER TABLE audit_events ADD COLUMN cache_read_input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.cache_read_input_tokens')) VIRTUAL"
26061
+ },
26062
+ {
26063
+ name: "model",
26064
+ ddl: "ALTER TABLE audit_events ADD COLUMN model text GENERATED ALWAYS AS (json_extract(attributes, '$.model')) VIRTUAL"
26065
+ },
26066
+ {
26067
+ name: "provider",
26068
+ ddl: "ALTER TABLE audit_events ADD COLUMN provider text GENERATED ALWAYS AS (json_extract(attributes, '$.provider')) VIRTUAL"
25100
26069
  }
25101
26070
  ];
25102
26071
  function ensureTokenUsageColumns(db) {
@@ -25357,10 +26326,62 @@ function ensureSyncedAtColumn(db, table) {
25357
26326
  if (!columns.includes("outbox_owed")) {
25358
26327
  db.exec(`ALTER TABLE ${table} ADD COLUMN outbox_owed integer`);
25359
26328
  }
26329
+ if (!columns.includes("sync_failed_at")) {
26330
+ db.exec(`ALTER TABLE ${table} ADD COLUMN sync_failed_at integer`);
26331
+ }
26332
+ if (!columns.includes("sync_failure")) {
26333
+ withTransaction(
26334
+ db,
26335
+ () => {
26336
+ db.exec(`ALTER TABLE ${table} ADD COLUMN sync_failure text`);
26337
+ db.exec(
26338
+ `UPDATE ${table} SET synced_at = NULL
26339
+ WHERE synced_at = -1
26340
+ AND event_type IN (${COUNTED_EVENT_TYPES.map((t) => `'${t}'`).join(", ")})`
26341
+ );
26342
+ },
26343
+ "IMMEDIATE"
26344
+ );
26345
+ }
25360
26346
  db.exec(
25361
- `CREATE INDEX IF NOT EXISTS idx_audit_events_sync
25362
- ON audit_events (event_type, synced_at, sync_claimed_at, started_at)`
26347
+ `CREATE TRIGGER IF NOT EXISTS aka_sync_failure_guard
26348
+ BEFORE UPDATE OF sync_failure ON ${table}
26349
+ WHEN ${syncFailureRejectCondition()}
26350
+ BEGIN SELECT RAISE(ABORT, 'sync_failure is not one of the recorded reasons'); END`
25363
26351
  );
26352
+ const syncIndexColumns = [
26353
+ "event_type",
26354
+ "synced_at",
26355
+ "sync_claimed_at",
26356
+ "started_at",
26357
+ // Appended LAST on purpose. The delivery-state read now projects it, so it
26358
+ // has to be in the index for the read to stay covered — but putting it
26359
+ // ahead of `started_at` would reorder the prefix the structural drain's
26360
+ // reads match on.
26361
+ "sync_failure"
26362
+ // `outbox_owed` is DELIBERATELY ABSENT, and it was measured both ways.
26363
+ //
26364
+ // The delivery-state read tests it — a capture's state depends on whether a
26365
+ // live forward marked it owed — so carrying it here makes that read covering
26366
+ // rather than a row fetch per row: 16 ms against 40 ms on a real 6 GB store.
26367
+ // But a sixth column changes what the planner charges for this index, and
26368
+ // with no ANALYZE statistics it plans from schema shape alone: measured, it
26369
+ // then stops choosing the per-session index for the token rollup and walks
26370
+ // every `llm_call` in the store through the event-type index instead. That
26371
+ // read grows with the store; this one does not.
26372
+ //
26373
+ // 40 ms on the largest store measured, once per render, is a cost worth
26374
+ // paying to leave every other read's plan where it was.
26375
+ ];
26376
+ const currentSyncIndex = indexColumns(db, "idx_audit_events_sync");
26377
+ const syncIndexMatches = currentSyncIndex.length === syncIndexColumns.length && currentSyncIndex.every((column, i) => column === syncIndexColumns[i]);
26378
+ if (!syncIndexMatches) {
26379
+ db.exec("DROP INDEX IF EXISTS idx_audit_events_sync");
26380
+ db.exec(
26381
+ `CREATE INDEX idx_audit_events_sync
26382
+ ON audit_events (${syncIndexColumns.join(", ")})`
26383
+ );
26384
+ }
25364
26385
  db.exec(
25365
26386
  `CREATE INDEX IF NOT EXISTS idx_audit_outbox_owed
25366
26387
  ON audit_events (event_type, synced_at, sync_claimed_at, started_at) WHERE outbox_owed = 1`
@@ -25582,7 +26603,11 @@ function buildAuditEvent(row) {
25582
26603
  link: linkParsed?.success ? linkParsed.data : null,
25583
26604
  targetId: row.target_id,
25584
26605
  internal: intToBool(row.internal),
25585
- flagged: intToBool(row.flagged)
26606
+ flagged: intToBool(row.flagged),
26607
+ // Only meaningful when the title came out empty — a row whose body was
26608
+ // expired but whose title fell back to `tool_name` still has something to
26609
+ // render, and flagging it would make the view apologise for nothing.
26610
+ bodyExpired: row.content_expired_at !== null && (row.title ?? "") === ""
25586
26611
  };
25587
26612
  }
25588
26613
  var TIMELINE_COLUMNS = `
@@ -25590,6 +26615,7 @@ var TIMELINE_COLUMNS = `
25590
26615
  event_type,
25591
26616
  started_at,
25592
26617
  coalesce(content, json_extract(attributes, '$.tool_name')) AS title,
26618
+ content_expired_at,
25593
26619
  coalesce(json_extract(attributes, '$.detail'), json_extract(attributes, '$.target')) AS detail,
25594
26620
  coalesce(json_extract(attributes, '$.tool_name'), json_extract(attributes, '$.tool')) AS tool,
25595
26621
  json_extract(attributes, '$.severity') AS severity,
@@ -26255,6 +27281,88 @@ var SqliteAuditEventsRepository = class {
26255
27281
  }
26256
27282
  };
26257
27283
 
27284
+ // ../../packages/persistence/src/repositories/body-retention.ts
27285
+ var DEFAULT_BATCH_SIZE = 500;
27286
+ var DEFAULT_MAX_ROWS = 5e4;
27287
+ var SYNC_LANE_TYPES_SQL = OUTBOX_CAPTURE_TYPE_LIST;
27288
+ var SqliteBodyRetentionRepository = class {
27289
+ constructor(db) {
27290
+ this.db = db;
27291
+ const select = (laneClause) => `
27292
+ SELECT id, LENGTH(CAST(content AS BLOB)) AS bytes
27293
+ FROM audit_events
27294
+ WHERE content IS NOT NULL
27295
+ AND started_at < :cutoff
27296
+ AND event_type IN (${CAPTURE_EVENT_TYPES_SQL})
27297
+ ${laneClause}
27298
+ ORDER BY started_at
27299
+ LIMIT :limit`;
27300
+ this.candidatesStmt = this.db.prepare(select(""));
27301
+ this.candidatesSyncSafeStmt = this.db.prepare(
27302
+ select(`AND (event_type NOT IN (${SYNC_LANE_TYPES_SQL}) OR synced_at IS NOT NULL)`)
27303
+ );
27304
+ this.heldBySyncStmt = this.db.prepare(`
27305
+ SELECT COUNT(*) AS n
27306
+ FROM audit_events
27307
+ WHERE content IS NOT NULL
27308
+ AND started_at < :cutoff
27309
+ AND event_type IN (${SYNC_LANE_TYPES_SQL})
27310
+ AND synced_at IS NULL`);
27311
+ this.expireStmt = this.db.prepare(
27312
+ `UPDATE audit_events SET content = NULL, content_expired_at = :now WHERE id = :id`
27313
+ );
27314
+ }
27315
+ db;
27316
+ candidatesStmt;
27317
+ candidatesSyncSafeStmt;
27318
+ heldBySyncStmt;
27319
+ expireStmt;
27320
+ /** How many bytes a pass with these options would free, changing nothing. */
27321
+ preview(opts) {
27322
+ const limit = opts.maxRows ?? DEFAULT_MAX_ROWS;
27323
+ const stmt = opts.sweepSyncLane ? this.candidatesStmt : this.candidatesSyncSafeStmt;
27324
+ const rows = stmt.all({ cutoff: opts.cutoff, limit });
27325
+ return {
27326
+ rowsExpired: rows.length,
27327
+ bytesFreed: rows.reduce((sum, r) => sum + r.bytes, 0),
27328
+ rowsHeldBySync: this.countHeldBySync(opts)
27329
+ };
27330
+ }
27331
+ /** Clear eligible bodies, in bounded batches. */
27332
+ expire(opts) {
27333
+ const batchSize = opts.batchSize ?? DEFAULT_BATCH_SIZE;
27334
+ const maxRows = opts.maxRows ?? DEFAULT_MAX_ROWS;
27335
+ const stmt = opts.sweepSyncLane ? this.candidatesStmt : this.candidatesSyncSafeStmt;
27336
+ let rowsExpired = 0;
27337
+ let bytesFreed = 0;
27338
+ let done = true;
27339
+ while (rowsExpired < maxRows) {
27340
+ const remaining = Math.min(batchSize, maxRows - rowsExpired);
27341
+ const batch = stmt.all({ cutoff: opts.cutoff, limit: remaining });
27342
+ if (batch.length === 0) break;
27343
+ withTransaction(
27344
+ this.db,
27345
+ () => {
27346
+ for (const row of batch) this.expireStmt.run({ id: row.id, now: opts.now });
27347
+ },
27348
+ "IMMEDIATE"
27349
+ );
27350
+ rowsExpired += batch.length;
27351
+ bytesFreed += batch.reduce((sum, r) => sum + r.bytes, 0);
27352
+ if (batch.length < remaining) break;
27353
+ if (rowsExpired >= maxRows) {
27354
+ done = stmt.all({ cutoff: opts.cutoff, limit: 1 }).length === 0;
27355
+ }
27356
+ }
27357
+ return { rowsExpired, bytesFreed, rowsHeldBySync: this.countHeldBySync(opts), done };
27358
+ }
27359
+ countHeldBySync(opts) {
27360
+ if (opts.sweepSyncLane) return 0;
27361
+ const row = this.heldBySyncStmt.get({ cutoff: opts.cutoff });
27362
+ return row.n;
27363
+ }
27364
+ };
27365
+
26258
27366
  // ../../packages/persistence/src/repositories/classified-data.ts
26259
27367
  var SqliteClassifiedDataRepository = class {
26260
27368
  constructor(db) {
@@ -27083,7 +28191,15 @@ function toFlatFindingRow(r) {
27083
28191
  ...r.tool_name === null ? {} : { toolName: r.tool_name },
27084
28192
  eventId: r.event_id,
27085
28193
  ...r.session_id === null ? {} : { sessionId: r.session_id },
27086
- status: deriveInstanceStatus(r)
28194
+ status: deriveInstanceStatus(r),
28195
+ delivery: deriveFindingDelivery({
28196
+ kind: r.kind,
28197
+ syncedAt: r.synced_at,
28198
+ syncClaimedAt: r.sync_claimed_at,
28199
+ syncFailedAt: r.sync_failed_at,
28200
+ syncFailure: r.sync_failure,
28201
+ outboxOwed: r.outbox_owed
28202
+ })
27087
28203
  };
27088
28204
  }
27089
28205
  function encodeGroupCursor(group) {
@@ -27147,7 +28263,10 @@ var FINDING_ROW_COLUMNS_SQL = `f.id AS id, d.rule_id AS rule_id, d.category AS c
27147
28263
  e.tool_name AS tool_name,
27148
28264
  f.audit_event_id AS event_id, e.root_session_id AS session_id,
27149
28265
  e.event_type AS kind, f.finding_key AS finding_key,
27150
- ${latestResolutionStatusSql("f")} AS latest_status`;
28266
+ ${latestResolutionStatusSql("f")} AS latest_status,
28267
+ e.synced_at AS synced_at, e.sync_claimed_at AS sync_claimed_at,
28268
+ e.sync_failed_at AS sync_failed_at, e.sync_failure AS sync_failure,
28269
+ e.outbox_owed AS outbox_owed`;
27151
28270
  var DAY_MS3 = 864e5;
27152
28271
  var SqliteFindingsRepository = class {
27153
28272
  constructor(db) {
@@ -27392,6 +28511,7 @@ var SqliteFindingsRepository = class {
27392
28511
  providers: query.provider,
27393
28512
  actions: query.action,
27394
28513
  statuses: query.status,
28514
+ deliveries: query.deployment,
27395
28515
  tools: query.tool,
27396
28516
  repo: query.repo,
27397
28517
  file: query.file,
@@ -27459,6 +28579,7 @@ var SqliteFindingsRepository = class {
27459
28579
  providers: query.provider,
27460
28580
  actions: query.action,
27461
28581
  statuses: query.status,
28582
+ deliveries: query.deployment,
27462
28583
  tools: query.tool,
27463
28584
  q: query.q
27464
28585
  };
@@ -27722,7 +28843,9 @@ var SqliteFindingsRepository = class {
27722
28843
  )
27723
28844
  );
27724
28845
  for (const row of grouped) {
27725
- if (row.action_taken in byAction) byAction[row.action_taken] = row.c;
28846
+ if (Object.hasOwn(byAction, row.action_taken)) {
28847
+ byAction[row.action_taken] = row.c;
28848
+ }
27726
28849
  }
27727
28850
  const bySeverity = { critical: 0, high: 0, medium: 0, low: 0 };
27728
28851
  const sevRows = allRows(
@@ -27739,7 +28862,9 @@ var SqliteFindingsRepository = class {
27739
28862
  )
27740
28863
  );
27741
28864
  for (const row of sevRows) {
27742
- if (row.severity in bySeverity) bySeverity[row.severity] = row.c;
28865
+ if (Object.hasOwn(bySeverity, row.severity)) {
28866
+ bySeverity[row.severity] = row.c;
28867
+ }
27743
28868
  }
27744
28869
  const categories = ENFORCEABLE_CATEGORIES;
27745
28870
  const enabledRows = allRows(
@@ -27788,525 +28913,6 @@ function isoDay(ms) {
27788
28913
  return new Date(ms).toISOString().slice(0, 10);
27789
28914
  }
27790
28915
 
27791
- // ../../packages/persistence/src/repositories/history-sync.ts
27792
- var STRUCTURAL_EVENT_TYPES = ["session", "llm_call", "tool_call"];
27793
- var TYPE_LIST = STRUCTURAL_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
27794
- var OUTBOX_CAPTURE_EVENT_TYPES = ["prompt", "response", "tool_use"];
27795
- var CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
27796
- var SKIPPED = -1;
27797
- var ROW_COLUMNS = `id,
27798
- parent_id AS parentId,
27799
- root_session_id AS rootSessionId,
27800
- event_type AS eventType,
27801
- host_id AS hostId,
27802
- harness_id AS harnessId,
27803
- source_project_id AS sourceProjectId,
27804
- started_at AS startedAt,
27805
- ended_at AS endedAt,
27806
- severity,
27807
- priority,
27808
- content,
27809
- content_hash AS contentHash,
27810
- attributes`;
27811
- var SqliteHistorySyncRepository = class {
27812
- constructor(db) {
27813
- this.db = db;
27814
- this.ensureRowStmt = db.prepare(`INSERT OR IGNORE INTO history_sync (id) VALUES (1)`);
27815
- this.sessionsStmt = db.prepare(
27816
- `SELECT COALESCE(root_session_id, id) AS sessionId, MIN(started_at) AS earliest
27817
- FROM audit_events
27818
- WHERE synced_at IS NULL
27819
- AND event_type IN (${TYPE_LIST})
27820
- AND started_at < :before
27821
- GROUP BY sessionId
27822
- ORDER BY earliest
27823
- LIMIT :limit`
27824
- );
27825
- this.rowsStmt = db.prepare(
27826
- `SELECT ${ROW_COLUMNS}
27827
- FROM audit_events
27828
- WHERE synced_at IS NULL
27829
- AND event_type IN (${TYPE_LIST})
27830
- AND started_at < :before
27831
- AND COALESCE(root_session_id, id) = :sessionId
27832
- ORDER BY (event_type = 'session') DESC, started_at
27833
- LIMIT :limit`
27834
- );
27835
- this.captureRowsStmt = db.prepare(
27836
- `SELECT ${ROW_COLUMNS}
27837
- FROM audit_events
27838
- WHERE synced_at IS NULL
27839
- AND sync_claimed_at IS NULL
27840
- AND outbox_owed = 1
27841
- AND event_type IN (${CAPTURE_TYPE_LIST})
27842
- AND started_at < :before
27843
- ORDER BY started_at
27844
- LIMIT :limit`
27845
- );
27846
- this.markOwedStmt = db.prepare(
27847
- `UPDATE audit_events SET outbox_owed = 1 WHERE id = :id AND synced_at IS NULL`
27848
- );
27849
- this.markCaptureBacklogOwedStmt = db.prepare(
27850
- `UPDATE audit_events SET outbox_owed = 1
27851
- WHERE synced_at IS NULL
27852
- AND event_type IN (${CAPTURE_TYPE_LIST})
27853
- AND started_at < :before`
27854
- );
27855
- this.stampStmt = db.prepare(
27856
- `UPDATE audit_events SET synced_at = :at, sync_claimed_at = NULL WHERE id = :id`
27857
- );
27858
- this.claimRowStmt = db.prepare(
27859
- `UPDATE audit_events SET sync_claimed_at = :at WHERE id = :id AND synced_at IS NULL`
27860
- );
27861
- this.releaseRowStmt = db.prepare(
27862
- `UPDATE audit_events SET sync_claimed_at = NULL WHERE id = :id`
27863
- );
27864
- this.releaseStaleClaimsStmt = db.prepare(
27865
- `UPDATE audit_events SET sync_claimed_at = NULL
27866
- WHERE sync_claimed_at IS NOT NULL AND sync_claimed_at < :staleBefore`
27867
- );
27868
- this.partitionStmt = db.prepare(
27869
- `SELECT
27870
- SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NULL THEN 1 ELSE 0 END) AS queued,
27871
- SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NOT NULL THEN 1 ELSE 0 END) AS inProgress,
27872
- SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS synced,
27873
- SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0 THEN 1 ELSE 0 END) AS failed,
27874
- COUNT(*) AS total
27875
- FROM audit_events
27876
- WHERE event_type IN (${TYPE_LIST})`
27877
- );
27878
- this.countsStmt = db.prepare(
27879
- `SELECT
27880
- SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
27881
- SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
27882
- SUM(CASE WHEN synced_at = ${String(SKIPPED)} THEN 1 ELSE 0 END) AS skipped
27883
- FROM audit_events
27884
- WHERE event_type IN (${TYPE_LIST})`
27885
- );
27886
- this.captureSkipCountStmt = db.prepare(
27887
- `SELECT COUNT(*) AS skipped
27888
- FROM audit_events
27889
- WHERE synced_at = ${String(SKIPPED)}
27890
- AND event_type IN (${CAPTURE_TYPE_LIST})`
27891
- );
27892
- this.fingerprintStmt = db.prepare(
27893
- `SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
27894
- FROM history_sync WHERE id = 1`
27895
- );
27896
- this.setFingerprintStmt = db.prepare(
27897
- `UPDATE history_sync
27898
- SET endpoint_fingerprint = :fingerprint, backlog_before = :backlogBefore
27899
- WHERE id = 1`
27900
- );
27901
- this.disownCapturesStmt = db.prepare(
27902
- `UPDATE audit_events SET outbox_owed = NULL
27903
- WHERE outbox_owed IS NOT NULL
27904
- AND event_type IN (${CAPTURE_TYPE_LIST})
27905
- AND started_at < :attachedAt`
27906
- );
27907
- this.rearmStmt = db.prepare(
27908
- `UPDATE audit_events SET synced_at = NULL
27909
- WHERE synced_at > 0 AND event_type IN (${TYPE_LIST})`
27910
- );
27911
- this.claimStmt = db.prepare(
27912
- `UPDATE history_sync
27913
- SET owner_pid = :pid, owner_host = :host, acquired_at = :now, heartbeat_at = :now
27914
- WHERE id = 1
27915
- AND (owner_pid IS NULL
27916
- OR heartbeat_at IS NULL
27917
- OR heartbeat_at < :staleBefore
27918
- OR heartbeat_at > :now)`
27919
- );
27920
- this.heartbeatStmt = db.prepare(
27921
- `UPDATE history_sync SET heartbeat_at = :now WHERE id = 1 AND owner_pid = :pid`
27922
- );
27923
- this.releaseStmt = db.prepare(
27924
- `UPDATE history_sync
27925
- SET owner_pid = NULL, owner_host = NULL, acquired_at = NULL, heartbeat_at = NULL
27926
- WHERE id = 1 AND owner_pid = :pid`
27927
- );
27928
- this.closeWindowStmt = db.prepare(
27929
- `UPDATE audit_events SET synced_at = :at
27930
- WHERE synced_at IS NULL
27931
- AND event_type IN (${TYPE_LIST})
27932
- AND started_at >= :attachedAt`
27933
- );
27934
- this.releaseBoundaryStmt = db.prepare(
27935
- `UPDATE history_sync SET backlog_before = NULL WHERE id = 1`
27936
- );
27937
- this.freezeBoundaryStmt = db.prepare(
27938
- `UPDATE history_sync SET backlog_before = :backlogBefore WHERE id = 1`
27939
- );
27940
- this.leaseStmt = db.prepare(
27941
- `SELECT owner_pid AS ownerPid, owner_host AS ownerHost,
27942
- acquired_at AS acquiredAt, heartbeat_at AS heartbeatAt
27943
- FROM history_sync WHERE id = 1`
27944
- );
27945
- this.inspectionsStmt = db.prepare(
27946
- `SELECT d.rule_id AS ruleId,
27947
- d.name AS ruleName,
27948
- d.version AS ruleVersion,
27949
- d.category AS category,
27950
- d.severity AS severity,
27951
- f.span_start AS spanStart,
27952
- f.span_end AS spanEnd,
27953
- f.masked_match AS maskedMatch,
27954
- f.action_taken AS actionTaken,
27955
- f.confidence AS confidence
27956
- FROM inspection_findings f
27957
- JOIN inspection_definitions d ON d.id = f.inspection_definition_id
27958
- WHERE f.audit_event_id = :auditEventId
27959
- ORDER BY f.span_start, f.id`
27960
- );
27961
- }
27962
- db;
27963
- ensureRowStmt;
27964
- sessionsStmt;
27965
- rowsStmt;
27966
- stampStmt;
27967
- countsStmt;
27968
- fingerprintStmt;
27969
- setFingerprintStmt;
27970
- rearmStmt;
27971
- claimStmt;
27972
- heartbeatStmt;
27973
- releaseStmt;
27974
- leaseStmt;
27975
- inspectionsStmt;
27976
- closeWindowStmt;
27977
- releaseBoundaryStmt;
27978
- freezeBoundaryStmt;
27979
- captureRowsStmt;
27980
- markOwedStmt;
27981
- markCaptureBacklogOwedStmt;
27982
- captureSkipCountStmt;
27983
- disownCapturesStmt;
27984
- partitionStmt;
27985
- claimRowStmt;
27986
- releaseRowStmt;
27987
- releaseStaleClaimsStmt;
27988
- /**
27989
- * The masked detections recorded against one tool call.
27990
- *
27991
- * These travel with the event because a tool call's target is not
27992
- * re-inspectable from the event alone — unlike a capture, where the text
27993
- * itself is re-scannable. What crosses is the masked match and the rule that
27994
- * produced it, never the value.
27995
- */
27996
- inspectionsFor(auditEventId) {
27997
- return allRows(this.inspectionsStmt, { auditEventId });
27998
- }
27999
- /**
28000
- * Sessions with structural rows still to send, oldest first.
28001
- *
28002
- * BOUNDED BY THE BACKLOG BOUNDARY, which is the whole correctness of this
28003
- * read. Anything recorded after the machine attached is the live forward
28004
- * path's to deliver; this drain exists for what was recorded before it, and a
28005
- * row both paths send is at best a duplicate request and at worst — for a
28006
- * session root — an overwrite of the inventory ids the live path resolved.
28007
- */
28008
- pendingSessions(limit, before) {
28009
- return allRows(this.sessionsStmt, { limit, before }).map(
28010
- (r) => r.sessionId
28011
- );
28012
- }
28013
- /** One session's undelivered structural rows within the backlog, root first. */
28014
- pendingRows(sessionId, limit, before) {
28015
- return allRows(this.rowsStmt, { sessionId, limit, before });
28016
- }
28017
- /**
28018
- * Captures this machine still owes the deployment, oldest first.
28019
- *
28020
- * Selected by the `outbox_owed` marker the attached forward path writes, not
28021
- * by a time window — see captureRowsStmt for why a window could not express
28022
- * this. `before` is the grace window that leaves a just-recorded capture to
28023
- * the live path.
28024
- */
28025
- pendingCaptureRows(limit, before) {
28026
- return allRows(this.captureRowsStmt, { limit, before });
28027
- }
28028
- /**
28029
- * Record that a capture is OWED to the deployment.
28030
- *
28031
- * Written by the attached forward path when a live send did not confirm
28032
- * delivery, and read by the drain as the whole of its eligibility test. It is
28033
- * a fact rather than an inference: the machine was attached, the send did not
28034
- * land, so the row is owed — which no time window can state, because the same
28035
- * window that holds the rows a past attachment left owed also holds every
28036
- * capture recorded while the machine was DETACHED, and those were never
28037
- * offered to anyone.
28038
- *
28039
- * Idempotent, and never un-set: `markSynced` settling the row is what takes it
28040
- * out of the drain's read.
28041
- */
28042
- markCaptureOwed(id) {
28043
- this.markOwedStmt.run({ id });
28044
- }
28045
- /**
28046
- * Mark every capture already on disk as owed, as of `before`.
28047
- *
28048
- * The consent-time backfill, called once from `aka attach` when a human
28049
- * grants existing-history consent — never from an ongoing drain pass, and
28050
- * never inferred from a boundary that could later move. `before` is the
28051
- * caller's own "now" at the moment consent was granted, so what this marks
28052
- * is exactly the backlog the consent prompt already counted, not whatever a
28053
- * later re-attach or key rotation might widen it to.
28054
- *
28055
- * Returns how many rows matched, for the caller to log or test against. Not a
28056
- * count of NEWLY marked rows — a row still unsynced from an earlier call
28057
- * matches again and is counted again, the same as `UPDATE`'s own `changes`.
28058
- */
28059
- markCaptureBacklogOwed(before) {
28060
- return Number(this.markCaptureBacklogOwedStmt.run({ before }).changes);
28061
- }
28062
- /** Record delivery. Called only AFTER the far side has accepted the rows. */
28063
- markSynced(ids, atMs) {
28064
- this.stampAll(ids, atMs);
28065
- }
28066
- /**
28067
- * Record that a row will never be sent.
28068
- *
28069
- * Reserved for a local defect — a row that cannot be rebuilt into a valid
28070
- * payload. A row that merely failed to reach the deployment stays NULL, so it
28071
- * is retried; marking those would turn one outage into permanent data loss.
28072
- */
28073
- markSkipped(ids) {
28074
- this.stampAll(ids, SKIPPED);
28075
- }
28076
- eachInTransaction(ids, run) {
28077
- if (ids.length === 0) return;
28078
- withTransaction(
28079
- this.db,
28080
- () => {
28081
- for (const id of ids) run(id);
28082
- },
28083
- "IMMEDIATE"
28084
- );
28085
- }
28086
- stampAll(ids, value) {
28087
- if (ids.length === 0) return;
28088
- withTransaction(
28089
- this.db,
28090
- () => {
28091
- for (const id of ids) this.stampStmt.run({ at: value, id });
28092
- },
28093
- "IMMEDIATE"
28094
- );
28095
- }
28096
- /**
28097
- * Claim rows as in-flight.
28098
- *
28099
- * Advisory in exactly the sense the lease is: it records that a send is in
28100
- * progress so a surface can say so, and a lost claim costs a row showing as
28101
- * queued while it is actually being sent. It is not exclusion — the far side
28102
- * settles a duplicate on the row id.
28103
- */
28104
- claimRows(ids, atMs) {
28105
- this.eachInTransaction(ids, (id) => this.claimRowStmt.run({ at: atMs, id }));
28106
- }
28107
- /** Give back a claim without settling — the send failed, the row is queued again. */
28108
- releaseRows(ids) {
28109
- this.eachInTransaction(ids, (id) => this.releaseRowStmt.run({ id }));
28110
- }
28111
- /**
28112
- * Clear claims older than `staleBefore`, and report how many were cleared.
28113
- *
28114
- * A process killed between claiming and settling leaves rows claimed with
28115
- * nothing left to settle them. Without this they read as "sending" for ever.
28116
- */
28117
- releaseStaleClaims(staleBefore) {
28118
- return Number(this.releaseStaleClaimsStmt.run({ staleBefore }).changes);
28119
- }
28120
- /**
28121
- * Every tracked row in exactly one delivery state.
28122
- *
28123
- * Takes no boundary on purpose. The boundary answers "what should the drain
28124
- * pick up now", which is a different question from "what state is this row
28125
- * in" — and a machine that has never attached has no boundary to pass, so
28126
- * requiring one would force a caller to invent one and report the whole store
28127
- * as queued.
28128
- */
28129
- partition() {
28130
- const row = getRow(this.partitionStmt, {});
28131
- return {
28132
- queued: row?.queued ?? 0,
28133
- inProgress: row?.inProgress ?? 0,
28134
- synced: row?.synced ?? 0,
28135
- failed: row?.failed ?? 0,
28136
- total: row?.total ?? 0
28137
- };
28138
- }
28139
- /** `pending` counts only what is inside the backlog; sent and skipped are totals. */
28140
- counts(before) {
28141
- const row = getRow(
28142
- this.countsStmt,
28143
- { before }
28144
- );
28145
- const captures = getRow(this.captureSkipCountStmt);
28146
- return {
28147
- pending: row?.pending ?? 0,
28148
- sent: row?.sent ?? 0,
28149
- skipped: row?.skipped ?? 0,
28150
- capturesSkipped: captures?.skipped ?? 0
28151
- };
28152
- }
28153
- /**
28154
- * The deployment the current stamps were made against, and where its backlog
28155
- * ends.
28156
- *
28157
- * READ-ONLY. An absent row reads as an absent deployment, which is what a
28158
- * machine that has never drained is — and every writer below seeds the row
28159
- * before it needs one, so nothing depends on this creating it. Keeping the
28160
- * write off the gate path matters because the gate runs on every pass while a
28161
- * write has to take the database's write lock.
28162
- */
28163
- deployment() {
28164
- const row = getRow(
28165
- this.fingerprintStmt
28166
- );
28167
- return {
28168
- fingerprint: row?.fingerprint ?? void 0,
28169
- backlogBefore: row?.backlogBefore ?? void 0
28170
- };
28171
- }
28172
- /**
28173
- * Point the ledger at a different deployment, discarding what it recorded
28174
- * about the previous one.
28175
- *
28176
- * Delivery is a fact about ONE recipient: rows sent to the deployment a
28177
- * machine has just left are undelivered as far as the new one is concerned.
28178
- * All four in one transaction, so a crash between them cannot leave stamps
28179
- * attributed to the wrong deployment, a boundary that belongs to another, or
28180
- * a disown with no re-mark to follow it.
28181
- *
28182
- * The boundary is written HERE and only here, which is what freezes it: a
28183
- * re-attach to the SAME deployment (a key rotation) leaves the fingerprint
28184
- * unchanged, so this never runs and the backlog does not widen back over rows
28185
- * the live path has since delivered.
28186
- *
28187
- * `backfillCapturesBefore` is the caller's OWN "now" at the instant a human
28188
- * granted existing-history consent for the deployment this call is arming —
28189
- * a DIFFERENT instant from `backlogBefore`: the re-mark boundary is the GRANT
28190
- * instant, `backlogBefore` is the ATTACH instant, and the two can be far
28191
- * apart. Passed only when that grant is valid, since this method has no way
28192
- * to check consent itself and must not mark a row owed for a machine that
28193
- * never agreed to it. Applied AFTER the disown above, in the SAME
28194
- * transaction: what the disown clears is every marker below `backlogBefore`,
28195
- * which includes this deployment's OWN pre-attach rows — `aka attach` calls
28196
- * `seedCaptureBacklogOwed` at the attach instant, so every row it marks sits
28197
- * on the cleared side of that bound — and the re-mark in the same
28198
- * transaction is what puts those rows back. A crash between the two cannot
28199
- * strand the ledger disowned with nothing re-marked — the transaction either
28200
- * lands whole or not at all, and a fingerprint mismatch that has not yet
28201
- * committed re-enters this method on the very next pass. Omit it (the
28202
- * structural-only tests do) to exercise the disown in isolation.
28203
- *
28204
- * The disown is bounded by `backlogBefore`, which is what keeps it from
28205
- * touching a marker the NEW deployment's OWN live path has already set: B's
28206
- * live path can mark a capture owed from the moment `aka attach` writes the
28207
- * descriptor, before the drain's first pass ever reaches this method, and
28208
- * such a row sits at or after the bound rather than below it. What keeps the
28209
- * disown from eating THIS SAME CALL's own re-mark is the order, not the
28210
- * bound — disown runs first, re-mark second, both inside the one
28211
- * transaction above.
28212
- */
28213
- rearmFor(fingerprint, backlogBefore, backfillCapturesBefore) {
28214
- this.ensureRowStmt.run();
28215
- withTransaction(
28216
- this.db,
28217
- () => {
28218
- const previous = getRow(this.fingerprintStmt)?.fingerprint;
28219
- this.rearmStmt.run();
28220
- if (previous !== null && previous !== void 0 && previous !== fingerprint) {
28221
- this.disownCapturesStmt.run({ attachedAt: backlogBefore });
28222
- }
28223
- if (backfillCapturesBefore !== void 0) {
28224
- this.markCaptureBacklogOwedStmt.run({ before: backfillCapturesBefore });
28225
- }
28226
- this.setFingerprintStmt.run({ fingerprint, backlogBefore });
28227
- },
28228
- "IMMEDIATE"
28229
- );
28230
- }
28231
- /**
28232
- * End the attached period: hand its rows to the live path, and release the
28233
- * boundary so the next attachment can freeze a new one.
28234
- *
28235
- * WITHOUT THIS, a detach and a re-attach to the same deployment leave a window
28236
- * nothing delivers. The fingerprint is unchanged, so the boundary is never
28237
- * re-frozen and stays at the FIRST attachment — while nothing forwards at all
28238
- * during the detached period, because the machine is not attached. Rows
28239
- * recorded in that window sit after the boundary and before the re-attach, so
28240
- * neither path takes them, and the pending count reports none outstanding.
28241
- *
28242
- * Stamping the attached window is not a claim that every one of those rows
28243
- * reached the deployment — the live path drops on failure and says so
28244
- * elsewhere. It records that they were ITS to deliver, which is exactly the
28245
- * status quo: they sit outside the frozen boundary today and are equally never
28246
- * re-sent. Making it explicit is what lets the boundary move.
28247
- *
28248
- * ONE TRANSACTION, so a crash cannot release the boundary while leaving the
28249
- * window unstamped — that half-state would re-send the whole attached period
28250
- * on the next attach, which is the failure the boundary exists to prevent.
28251
- */
28252
- closeAttachedWindow(attachedAtMs, atMs) {
28253
- this.ensureRowStmt.run();
28254
- withTransaction(
28255
- this.db,
28256
- () => {
28257
- const row = getRow(this.fingerprintStmt);
28258
- const from = row?.backlogBefore ?? attachedAtMs;
28259
- this.closeWindowStmt.run({ at: atMs, attachedAt: from });
28260
- this.releaseBoundaryStmt.run();
28261
- },
28262
- "IMMEDIATE"
28263
- );
28264
- }
28265
- /**
28266
- * Freeze a boundary for the deployment already on file, KEEPING the stamps.
28267
- *
28268
- * The re-attach half of the above. Distinct from `rearmFor`, which is for a
28269
- * different deployment and therefore discards what was delivered to the old
28270
- * one: here the recipient is the same, so everything already sent to it stays
28271
- * sent.
28272
- */
28273
- freezeBoundary(backlogBefore) {
28274
- this.ensureRowStmt.run();
28275
- this.freezeBoundaryStmt.run({ backlogBefore });
28276
- }
28277
- /** Take the claim, or report that someone live already holds it. */
28278
- claim(pid, host, nowMs, staleAfterMs) {
28279
- this.ensureRowStmt.run();
28280
- let taken = false;
28281
- withTransaction(
28282
- this.db,
28283
- () => {
28284
- const result = this.claimStmt.run({
28285
- pid,
28286
- host,
28287
- now: nowMs,
28288
- staleBefore: nowMs - staleAfterMs
28289
- });
28290
- taken = result.changes === 1;
28291
- },
28292
- "IMMEDIATE"
28293
- );
28294
- return taken;
28295
- }
28296
- /** Say the holder is still alive. A no-op once the claim has moved on. */
28297
- heartbeat(pid, nowMs) {
28298
- this.heartbeatStmt.run({ now: nowMs, pid });
28299
- }
28300
- /** Give the claim up. Scoped to this holder, so a taken-over claim is left be. */
28301
- release(pid) {
28302
- this.releaseStmt.run({ pid });
28303
- }
28304
- /** Who holds the claim, if anyone. Read-only, for the same reason as above. */
28305
- lease() {
28306
- return getRow(this.leaseStmt);
28307
- }
28308
- };
28309
-
28310
28916
  // ../../packages/persistence/src/repositories/inspection-definitions.ts
28311
28917
  var SqliteInspectionDefinitionsRepository = class {
28312
28918
  constructor(db) {
@@ -28537,6 +29143,7 @@ function overlayManagedSettings(settings, managed, now = () => /* @__PURE__ */ n
28537
29143
  if (values.vaultInlineReveal !== void 0) merged.vaultInlineReveal = values.vaultInlineReveal;
28538
29144
  if (values.dataSharesInPlace !== void 0) merged.dataSharesInPlace = values.dataSharesInPlace;
28539
29145
  if (values.redactFallback !== void 0) merged.redactFallback = values.redactFallback;
29146
+ if (values.bodyRetention !== void 0) merged.bodyRetention = values.bodyRetention;
28540
29147
  if (values.vaultConsent !== void 0) {
28541
29148
  merged.vaultConsent = values.vaultConsent ? (
28542
29149
  // Keep an existing valid grant so its acknowledgedAt survives; mint one
@@ -31044,7 +31651,7 @@ var SqliteSecurityRepository = class {
31044
31651
  ELSE 0
31045
31652
  END) AS open_at_rest
31046
31653
  FROM inspection_findings f
31047
- JOIN audit_events e ON e.id = f.audit_event_id
31654
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31048
31655
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
31049
31656
  LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
31050
31657
  ON latest.finding_key = f.finding_key
@@ -31270,7 +31877,7 @@ var SqliteSecurityRepository = class {
31270
31877
  this.db.prepare(
31271
31878
  `SELECT e.repo AS repo, count(*) AS c
31272
31879
  FROM inspection_findings f
31273
- JOIN audit_events e ON e.id = f.audit_event_id
31880
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31274
31881
  WHERE e.started_at >= :from AND e.started_at < :to
31275
31882
  AND e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
31276
31883
  AND e.repo IS NOT NULL
@@ -31394,7 +32001,7 @@ var SqliteSecurityRepository = class {
31394
32001
  d.severity AS severity,
31395
32002
  COUNT(*) AS count
31396
32003
  FROM inspection_findings f
31397
- JOIN audit_events e ON e.id = f.audit_event_id
32004
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31398
32005
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
31399
32006
  LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
31400
32007
  ON latest.finding_key = f.finding_key
@@ -31429,7 +32036,7 @@ var SqliteSecurityRepository = class {
31429
32036
  `SELECT e.started_at AS occurred_at, d.severity AS severity, f.action_taken AS action_taken,
31430
32037
  d.rule_id AS rule_id, d.category AS category
31431
32038
  FROM inspection_findings f
31432
- JOIN audit_events e ON e.id = f.audit_event_id
32039
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31433
32040
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
31434
32041
  WHERE e.started_at >= :from AND e.started_at < :to
31435
32042
  AND e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
@@ -32270,6 +32877,7 @@ function openWithPragmas(file2) {
32270
32877
  db.exec("PRAGMA journal_mode = WAL");
32271
32878
  db.exec("PRAGMA busy_timeout = 2000");
32272
32879
  db.exec("PRAGMA foreign_keys = ON");
32880
+ registerSqlFunctions(db);
32273
32881
  } catch (err) {
32274
32882
  closeQuietly(db);
32275
32883
  throw err;
@@ -32299,7 +32907,7 @@ function backupLegacyStore(db, file2) {
32299
32907
  discardStore(file2, backup);
32300
32908
  return backup;
32301
32909
  }
32302
- function openAndInitialize(file2, base) {
32910
+ function openAndInitialize(file2, base, skipTags) {
32303
32911
  let db = openWithPragmas(file2);
32304
32912
  try {
32305
32913
  if (isForeignSqliteLineage(db)) {
@@ -32309,7 +32917,7 @@ function openAndInitialize(file2, base) {
32309
32917
  `Detected an older, incompatible (tenant-bearing) ${DB_FILENAME}; backed it up to ${backup} and created a fresh store.`
32310
32918
  );
32311
32919
  }
32312
- applyMigrations(db, file2);
32920
+ applyMigrations(db, file2, { skipTags });
32313
32921
  tightenPerms(file2);
32314
32922
  const policies = new SqlitePoliciesRepository(db);
32315
32923
  const installedPacks = new SqliteInstalledPacksRepository(db, base);
@@ -32324,6 +32932,7 @@ function openAndInitialize(file2, base) {
32324
32932
  exceptions: new SqliteExceptionsRepository(db),
32325
32933
  resolutions: new SqliteResolutionsRepository(db),
32326
32934
  ruleProbeCache: new SqliteRuleProbeCacheRepository(db),
32935
+ bodyRetention: new SqliteBodyRetentionRepository(db),
32327
32936
  security: new SqliteSecurityRepository(db),
32328
32937
  detections: new SqliteDetectionsRepository(db),
32329
32938
  shares: new SqliteSharesRepository(db),
@@ -32346,7 +32955,8 @@ function openAndInitialize(file2, base) {
32346
32955
  throw err;
32347
32956
  }
32348
32957
  }
32349
- function openLocalDatabase(dir) {
32958
+ var DEFERRED_TAGS = new Set(DEFERRED_MIGRATION_TAGS);
32959
+ function openLocalDatabase(dir, options = {}) {
32350
32960
  ensureDataDirSync(dir);
32351
32961
  const file2 = join7(dir, DB_FILENAME);
32352
32962
  reapStalePartials(file2);
@@ -32358,6 +32968,7 @@ function openLocalDatabase(dir) {
32358
32968
  installedPacks,
32359
32969
  scanLedger,
32360
32970
  historySync,
32971
+ bodyRetention,
32361
32972
  secretVault,
32362
32973
  exceptions,
32363
32974
  resolutions,
@@ -32381,7 +32992,8 @@ function openLocalDatabase(dir) {
32381
32992
  // `dir` is always `<base>/data` — every caller resolves it through
32382
32993
  // `dataDir()` — so its parent is the `~/.aka` base the layout splits into
32383
32994
  // settings/ and data/, and the pack-policy floor needs both halves.
32384
- dirname2(dir)
32995
+ dirname2(dir),
32996
+ options.applyDeferredMigrations === true ? void 0 : DEFERRED_TAGS
32385
32997
  );
32386
32998
  function captureRowId(event) {
32387
32999
  return captureId(
@@ -32574,6 +33186,7 @@ function openLocalDatabase(dir) {
32574
33186
  installedPacks,
32575
33187
  scanLedger,
32576
33188
  historySync,
33189
+ bodyRetention,
32577
33190
  secretVault,
32578
33191
  exceptions,
32579
33192
  resolutions,
@@ -32614,8 +33227,35 @@ function openLocalDatabase(dir) {
32614
33227
 
32615
33228
  // ../../packages/persistence/src/egress-wire.ts
32616
33229
  import { createHash as createHash3 } from "crypto";
33230
+ var PROJECT_KEY_DIGEST_VERSION = "v2";
33231
+ var SCP_FORM = /^(?:[^@/]+@)?([^/:]+):(.+)$/;
33232
+ var DOS_DRIVE = /^[A-Za-z]:[\\/]/;
33233
+ var FILE_URL = /^file:\/\//i;
33234
+ var SCHEME_FORM = /^[a-z][a-z0-9+.-]*:\/\/(?:[^@/]+@)?([^/:]+)(?::\d+)?(\/.*)?$/i;
33235
+ var SLASH = "/".charCodeAt(0);
33236
+ var GIT_SUFFIX = ".git";
33237
+ function trimSlashes(path) {
33238
+ let start = 0;
33239
+ let end = path.length;
33240
+ while (start < end && path.charCodeAt(start) === SLASH) start += 1;
33241
+ while (end > start && path.charCodeAt(end - 1) === SLASH) end -= 1;
33242
+ return path.slice(start, end);
33243
+ }
33244
+ function canonicalGitUrl(url2) {
33245
+ const trimmed = url2.trim();
33246
+ if (DOS_DRIVE.test(trimmed) || FILE_URL.test(trimmed)) return trimmed;
33247
+ const scheme = SCHEME_FORM.exec(trimmed);
33248
+ const scp = scheme === null ? SCP_FORM.exec(trimmed) : null;
33249
+ const host = (scheme?.[1] ?? scp?.[1])?.toLowerCase();
33250
+ if (host === void 0) return trimmed;
33251
+ const path = (scheme === null ? scp?.[2] : scheme[2]) ?? "";
33252
+ const bare = trimSlashes(path);
33253
+ const cleaned = bare.endsWith(GIT_SUFFIX) ? bare.slice(0, -GIT_SUFFIX.length) : bare;
33254
+ return cleaned === "" ? host : `${host}/${cleaned}`;
33255
+ }
32617
33256
  function hashProjectKey(projectKey) {
32618
- return createHash3("sha256").update(projectKey, "utf8").digest("hex");
33257
+ const canonical = projectKey.startsWith("git:") ? `git:${canonicalGitUrl(projectKey.slice("git:".length))}` : projectKey;
33258
+ return createHash3("sha256").update(`${PROJECT_KEY_DIGEST_VERSION}:${canonical}`, "utf8").digest("hex");
32619
33259
  }
32620
33260
  function toIngestHit(hit) {
32621
33261
  return {
@@ -32691,18 +33331,50 @@ function readFingerprintKey(dataDir2) {
32691
33331
  return parseKeyFile(raw);
32692
33332
  }
32693
33333
 
33334
+ // ../../packages/persistence/src/forward-health.ts
33335
+ import { readFileSync as readFileSync7 } from "fs";
33336
+ import { join as join9 } from "path";
33337
+ var FAILURES = /* @__PURE__ */ new Set([
33338
+ "unauthorized",
33339
+ "forbidden",
33340
+ "unreachable"
33341
+ ]);
33342
+ var BREAKER_COOLDOWN_MS = 3e4;
33343
+ function parseForwardHealth(raw, nowMs) {
33344
+ try {
33345
+ const parsed2 = JSON.parse(raw);
33346
+ if (typeof parsed2 !== "object" || parsed2 === null) return null;
33347
+ const record2 = parsed2;
33348
+ const failures = typeof record2.consecutiveFailures === "number" && record2.consecutiveFailures >= 0 ? record2.consecutiveFailures : 0;
33349
+ const openedAtMs = typeof record2.openedAtMs === "number" && Number.isFinite(record2.openedAtMs) && record2.openedAtMs <= nowMs ? record2.openedAtMs : null;
33350
+ const lastFailure = typeof record2.lastFailure === "string" && FAILURES.has(record2.lastFailure) ? record2.lastFailure : null;
33351
+ return { consecutiveFailures: failures, openedAtMs, lastFailure };
33352
+ } catch {
33353
+ return null;
33354
+ }
33355
+ }
33356
+ function isForwardPaused(health, nowMs) {
33357
+ const openedAtMs = health?.openedAtMs ?? null;
33358
+ if (openedAtMs === null) return false;
33359
+ return nowMs - openedAtMs < BREAKER_COOLDOWN_MS;
33360
+ }
33361
+
32694
33362
  // ../../packages/persistence/src/history-backfill.ts
32695
33363
  import { existsSync as existsSync4 } from "fs";
32696
- import { join as join9 } from "path";
33364
+ import { join as join10 } from "path";
32697
33365
 
32698
33366
  // ../../packages/persistence/src/history-preview.ts
32699
33367
  import { existsSync as existsSync5 } from "fs";
32700
- import { join as join10 } from "path";
33368
+ import { join as join11 } from "path";
32701
33369
  import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
32702
33370
 
33371
+ // ../../packages/persistence/src/history-sync-state.ts
33372
+ import { readFileSync as readFileSync8 } from "fs";
33373
+ import { join as join12 } from "path";
33374
+
32703
33375
  // ../../packages/persistence/src/store-symlinks.ts
32704
33376
  import { existsSync as existsSync6, lstatSync as lstatSync3, readlinkSync, realpathSync, statSync as statSync4 } from "fs";
32705
- import { dirname as dirname3, join as join11, resolve } from "path";
33377
+ import { dirname as dirname3, join as join13, resolve } from "path";
32706
33378
  var STORE_DB = "the store database (including the prompt corpus)";
32707
33379
  var STORE_SETTINGS = "your settings file";
32708
33380
  function storeContents(home) {
@@ -32711,7 +33383,7 @@ function storeContents(home) {
32711
33383
  [settingsDir(home), STORE_SETTINGS],
32712
33384
  [dataDir(home), STORE_DB],
32713
33385
  [keysDir(home), "the vault key"],
32714
- [join11(settingsDir(home), "settings.json"), STORE_SETTINGS],
33386
+ [join13(settingsDir(home), "settings.json"), STORE_SETTINGS],
32715
33387
  [dbPath(home), STORE_DB]
32716
33388
  ]);
32717
33389
  }
@@ -32763,19 +33435,19 @@ import {
32763
33435
  // ../../packages/persistence/src/vault/key-provider.ts
32764
33436
  import { execFileSync } from "child_process";
32765
33437
  import { randomBytes as randomBytes2 } from "crypto";
32766
- import { chmodSync as chmodSync3, readFileSync as readFileSync7, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
32767
- import { join as join12 } from "path";
33438
+ import { chmodSync as chmodSync3, readFileSync as readFileSync9, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
33439
+ import { join as join14 } from "path";
32768
33440
 
32769
33441
  // ../../packages/persistence/src/vault/vault.ts
32770
33442
  import { randomBytes as randomBytes3, randomUUID as randomUUID12 } from "crypto";
32771
33443
 
32772
33444
  // ../../packages/persistence/src/warn-era-cap.ts
32773
33445
  import { existsSync as existsSync7, writeFileSync as writeFileSync4 } from "fs";
32774
- import { join as join13 } from "path";
33446
+ import { join as join15 } from "path";
32775
33447
  var MARKER = "warn-era-capped";
32776
33448
  function capWarnEraEnforcementOnce(db, policyMode, dataDir2) {
32777
33449
  if (policyMode !== "warn") return { capped: 0, skipped: "not-warn" };
32778
- const marker = join13(dataDir2, MARKER);
33450
+ const marker = join15(dataDir2, MARKER);
32779
33451
  if (existsSync7(marker)) return { capped: 0, skipped: "already-run" };
32780
33452
  const capped = db.policies.capCategoryActions();
32781
33453
  writeFileSync4(marker, `${new Date(Date.now()).toISOString()}
@@ -32966,10 +33638,10 @@ function parsed(schema, body, route) {
32966
33638
  }
32967
33639
  function withoutTrailingSlashes(endpoint) {
32968
33640
  let end = endpoint.length;
32969
- while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH) end -= 1;
33641
+ while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH2) end -= 1;
32970
33642
  return endpoint.slice(0, end);
32971
33643
  }
32972
- var SLASH = "/".charCodeAt(0);
33644
+ var SLASH2 = "/".charCodeAt(0);
32973
33645
  function createRemoteClient(options) {
32974
33646
  const base = withoutTrailingSlashes(options.endpoint);
32975
33647
  const url2 = (route) => `${base}${route}`;
@@ -33151,11 +33823,11 @@ function withTimeout(promise2, ms) {
33151
33823
  }
33152
33824
 
33153
33825
  // ../../packages/plugin-runtime/src/attached/forward-drops.ts
33154
- import { readFileSync as readFileSync8 } from "fs";
33155
- import { join as join14 } from "path";
33826
+ import { readFileSync as readFileSync10 } from "fs";
33827
+ import { join as join16 } from "path";
33156
33828
  var FORWARD_DROPS_FILENAME = ATTACHED_FORWARD_DROPS_FILENAME;
33157
33829
  function forwardDropsPath(dataDir2) {
33158
- return join14(dataDir2, FORWARD_DROPS_FILENAME);
33830
+ return join16(dataDir2, FORWARD_DROPS_FILENAME);
33159
33831
  }
33160
33832
  function recordForwardDrops(dataDir2, count, nowMs) {
33161
33833
  if (count <= 0) return;
@@ -33173,7 +33845,7 @@ function recordForwardDrops(dataDir2, count, nowMs) {
33173
33845
  }
33174
33846
  function readForwardDrops(dataDir2) {
33175
33847
  try {
33176
- const parsed2 = JSON.parse(readFileSync8(forwardDropsPath(dataDir2), "utf8"));
33848
+ const parsed2 = JSON.parse(readFileSync10(forwardDropsPath(dataDir2), "utf8"));
33177
33849
  if (typeof parsed2 !== "object" || parsed2 === null) return null;
33178
33850
  const record2 = parsed2;
33179
33851
  if (typeof record2.droppedForwards !== "number" || !Number.isFinite(record2.droppedForwards)) {
@@ -33191,13 +33863,12 @@ function readForwardDrops(dataDir2) {
33191
33863
 
33192
33864
  // ../../packages/plugin-runtime/src/attached/forward-policy.ts
33193
33865
  import { randomUUID as randomUUID15 } from "crypto";
33194
- import { readFileSync as readFileSync15 } from "fs";
33195
33866
  import { readFile, rename, writeFile } from "fs/promises";
33196
- import { join as join24 } from "path";
33867
+ import { join as join26 } from "path";
33197
33868
 
33198
33869
  // ../../packages/plugin-sdk/src/config.ts
33199
33870
  import { existsSync as existsSync8 } from "fs";
33200
- import { join as join15 } from "path";
33871
+ import { join as join17 } from "path";
33201
33872
 
33202
33873
  // ../../packages/plugin-sdk/src/provider-env.ts
33203
33874
  var DEFAULT_ANTHROPIC_HOST = "api.anthropic.com";
@@ -33251,7 +33922,7 @@ function resolveProvider() {
33251
33922
  function loadConfig(base = defaultDataDir(), resolveProviderFn = resolveProvider) {
33252
33923
  try {
33253
33924
  ensureLayoutDirSync(base);
33254
- const settingsFile = join15(settingsDir(base), "settings.json");
33925
+ const settingsFile = join17(settingsDir(base), "settings.json");
33255
33926
  if (existsSync8(settingsFile)) tightenFile(settingsFile);
33256
33927
  } catch {
33257
33928
  }
@@ -33275,9 +33946,9 @@ function resolveProviderSafe(resolveProviderFn) {
33275
33946
  }
33276
33947
 
33277
33948
  // ../../packages/plugin-sdk/src/config-inventory.ts
33278
- import { readdirSync as readdirSync2, readFileSync as readFileSync10, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
33949
+ import { readdirSync as readdirSync2, readFileSync as readFileSync12, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
33279
33950
  import { homedir as homedir2 } from "os";
33280
- import { basename as basename4, join as join17 } from "path";
33951
+ import { basename as basename4, join as join19 } from "path";
33281
33952
 
33282
33953
  // ../../packages/detections/src/egress/registry.ts
33283
33954
  var EXTRACTOR_VERSION = "1";
@@ -36406,8 +37077,8 @@ function maskText(text) {
36406
37077
  }
36407
37078
 
36408
37079
  // ../../packages/plugin-sdk/src/repo.ts
36409
- import { existsSync as existsSync9, readFileSync as readFileSync9, statSync as statSync6 } from "fs";
36410
- import { basename as basename3, dirname as dirname4, isAbsolute, join as join16, sep as sep2 } from "path";
37080
+ import { existsSync as existsSync9, readFileSync as readFileSync11, statSync as statSync6 } from "fs";
37081
+ import { basename as basename3, dirname as dirname4, isAbsolute, join as join18, sep as sep2 } from "path";
36411
37082
  function resolveRepoIdentity(cwd) {
36412
37083
  try {
36413
37084
  const root = findGitRoot(cwd);
@@ -36457,7 +37128,7 @@ function resolveGitBranch(cwd) {
36457
37128
  try {
36458
37129
  const root = findGitRoot(cwd);
36459
37130
  if (!root) return void 0;
36460
- const dotGit = join16(root, ".git");
37131
+ const dotGit = join18(root, ".git");
36461
37132
  let gitdir;
36462
37133
  try {
36463
37134
  gitdir = statSync6(dotGit).isDirectory() ? dotGit : resolveWorktreeGitdir(root, dotGit);
@@ -36465,7 +37136,7 @@ function resolveGitBranch(cwd) {
36465
37136
  return void 0;
36466
37137
  }
36467
37138
  if (gitdir === void 0) return void 0;
36468
- const head = safeRead(join16(gitdir, "HEAD"));
37139
+ const head = safeRead(join18(gitdir, "HEAD"));
36469
37140
  if (!head) return void 0;
36470
37141
  return /^ref:\s*refs\/heads\/(.+?)\s*$/m.exec(head)?.[1];
36471
37142
  } catch {
@@ -36475,41 +37146,41 @@ function resolveGitBranch(cwd) {
36475
37146
  function resolveWorktreeGitdir(root, dotGitFile) {
36476
37147
  const target = /^gitdir:\s*(.+?)\s*$/m.exec(safeRead(dotGitFile) ?? "")?.[1];
36477
37148
  if (!target) return void 0;
36478
- return isAbsolute(target) ? target : join16(root, target);
37149
+ return isAbsolute(target) ? target : join18(root, target);
36479
37150
  }
36480
37151
  function findGitRoot(start) {
36481
37152
  let dir = start;
36482
37153
  for (; ; ) {
36483
- if (existsSync9(join16(dir, ".git"))) return dir;
37154
+ if (existsSync9(join18(dir, ".git"))) return dir;
36484
37155
  const parent = dirname4(dir);
36485
37156
  if (parent === dir) return void 0;
36486
37157
  dir = parent;
36487
37158
  }
36488
37159
  }
36489
37160
  function resolveGitContext(root) {
36490
- const dotGit = join16(root, ".git");
37161
+ const dotGit = join18(root, ".git");
36491
37162
  try {
36492
37163
  if (statSync6(dotGit).isDirectory()) {
36493
- return { configPath: join16(dotGit, "config"), headRoot: root };
37164
+ return { configPath: join18(dotGit, "config"), headRoot: root };
36494
37165
  }
36495
37166
  } catch {
36496
37167
  return void 0;
36497
37168
  }
36498
37169
  const target = /^gitdir:\s*(.+?)\s*$/m.exec(safeRead(dotGit) ?? "")?.[1];
36499
37170
  if (!target) return void 0;
36500
- const gitdir = isAbsolute(target) ? target : join16(root, target);
36501
- if (existsSync9(join16(gitdir, "config"))) {
36502
- return { configPath: join16(gitdir, "config"), headRoot: root };
37171
+ const gitdir = isAbsolute(target) ? target : join18(root, target);
37172
+ if (existsSync9(join18(gitdir, "config"))) {
37173
+ return { configPath: join18(gitdir, "config"), headRoot: root };
36503
37174
  }
36504
- const commonRaw = safeRead(join16(gitdir, "commondir"))?.trim();
37175
+ const commonRaw = safeRead(join18(gitdir, "commondir"))?.trim();
36505
37176
  if (!commonRaw) return void 0;
36506
- const commonGitDir = isAbsolute(commonRaw) ? commonRaw : join16(gitdir, commonRaw);
37177
+ const commonGitDir = isAbsolute(commonRaw) ? commonRaw : join18(gitdir, commonRaw);
36507
37178
  const headRoot = basename3(commonGitDir) === ".git" ? dirname4(commonGitDir) : root;
36508
- return { configPath: join16(commonGitDir, "config"), headRoot };
37179
+ return { configPath: join18(commonGitDir, "config"), headRoot };
36509
37180
  }
36510
37181
  function safeRead(path) {
36511
37182
  try {
36512
- return readFileSync9(path, "utf8");
37183
+ return readFileSync11(path, "utf8");
36513
37184
  } catch {
36514
37185
  return void 0;
36515
37186
  }
@@ -36571,31 +37242,31 @@ function resolveConfigInventory(input2) {
36571
37242
  };
36572
37243
  try {
36573
37244
  const home = input2.homeDir ?? homedir2();
36574
- const claudeDir = join17(home, ".claude");
37245
+ const claudeDir = join19(home, ".claude");
36575
37246
  const repo = resolveRepoIdentity(input2.cwd);
36576
37247
  const repoIdentity = repo?.url ?? input2.cwd;
36577
37248
  const projectSource = `project:${repoIdentity}`;
36578
- collectSettingsHooks(scan2, join17(claudeDir, "settings.json"), "user");
36579
- collectSettingsHooks(scan2, join17(input2.cwd, ".claude", "settings.json"), "project");
36580
- collectSettingsHooks(scan2, join17(input2.cwd, ".claude", "settings.local.json"), "local");
37249
+ collectSettingsHooks(scan2, join19(claudeDir, "settings.json"), "user");
37250
+ collectSettingsHooks(scan2, join19(input2.cwd, ".claude", "settings.json"), "project");
37251
+ collectSettingsHooks(scan2, join19(input2.cwd, ".claude", "settings.local.json"), "local");
36581
37252
  const projectOrigin = { scope: "project", project: repoIdentity };
36582
- collectMcpFile(scan2, join17(input2.cwd, ".mcp.json"), projectOrigin, { recordErrors: true });
36583
- collectUserClaudeJson(scan2, join17(home, ".claude.json"), input2.cwd, repoIdentity);
36584
- collectMcpFile(scan2, join17(claudeDir, "settings.json"), { scope: "user" });
36585
- collectMcpFile(scan2, join17(input2.cwd, ".claude", "settings.json"), projectOrigin);
36586
- collectMcpFile(scan2, join17(input2.cwd, ".claude", "settings.local.json"), {
37253
+ collectMcpFile(scan2, join19(input2.cwd, ".mcp.json"), projectOrigin, { recordErrors: true });
37254
+ collectUserClaudeJson(scan2, join19(home, ".claude.json"), input2.cwd, repoIdentity);
37255
+ collectMcpFile(scan2, join19(claudeDir, "settings.json"), { scope: "user" });
37256
+ collectMcpFile(scan2, join19(input2.cwd, ".claude", "settings.json"), projectOrigin);
37257
+ collectMcpFile(scan2, join19(input2.cwd, ".claude", "settings.local.json"), {
36587
37258
  scope: "local",
36588
37259
  project: repoIdentity
36589
37260
  });
36590
37261
  collectConfigFiles(scan2, claudeDir, input2.cwd);
36591
- collectSkillsDir(scan2, join17(claudeDir, "skills"), { source: "local", scope: "user" });
36592
- collectSkillsDir(scan2, join17(input2.cwd, ".claude", "skills"), {
37262
+ collectSkillsDir(scan2, join19(claudeDir, "skills"), { source: "local", scope: "user" });
37263
+ collectSkillsDir(scan2, join19(input2.cwd, ".claude", "skills"), {
36593
37264
  source: projectSource,
36594
37265
  scope: "project"
36595
37266
  });
36596
37267
  collectInstalledPlugins(scan2, claudeDir);
36597
37268
  collectMarketplaceSkills(scan2, claudeDir);
36598
- collectSkillsDir(scan2, join17(input2.cwd, "skills"), { source: projectSource, scope: "project" });
37269
+ collectSkillsDir(scan2, join19(input2.cwd, "skills"), { source: projectSource, scope: "project" });
36599
37270
  scan2.skills = dedupeSkills(scan2.skills);
36600
37271
  scan2.mcpServers = dedupeMcpServers(scan2.mcpServers);
36601
37272
  } catch (err) {
@@ -36724,7 +37395,7 @@ function projectEntryFor(projects, cwd) {
36724
37395
  return void 0;
36725
37396
  }
36726
37397
  function collectPluginManifestMcp(scan2, installPath, origin) {
36727
- const manifestPath = join17(installPath, ".claude-plugin", "plugin.json");
37398
+ const manifestPath = join19(installPath, ".claude-plugin", "plugin.json");
36728
37399
  const raw = readOptional(manifestPath);
36729
37400
  if (raw === void 0) return;
36730
37401
  try {
@@ -36732,7 +37403,7 @@ function collectPluginManifestMcp(scan2, installPath, origin) {
36732
37403
  if (typeof parsed2 !== "object" || parsed2 === null) return;
36733
37404
  const declared = parsed2.mcpServers;
36734
37405
  if (typeof declared === "string" && declared.length > 0) {
36735
- collectMcpFile(scan2, join17(installPath, declared), origin, { recordErrors: true });
37406
+ collectMcpFile(scan2, join19(installPath, declared), origin, { recordErrors: true });
36736
37407
  } else {
36737
37408
  collectMcpObject(scan2, declared, manifestPath, origin);
36738
37409
  }
@@ -36749,14 +37420,14 @@ var SETTINGS_KEY_LABELS = [
36749
37420
  ["statusLine", "status line"]
36750
37421
  ];
36751
37422
  function collectConfigFiles(scan2, claudeDir, cwd) {
36752
- settingsConfigFile(scan2, join17(claudeDir, "settings.json"), "user", "User settings");
36753
- settingsConfigFile(scan2, join17(cwd, ".claude", "settings.json"), "project", "Project settings");
36754
- settingsConfigFile(scan2, join17(cwd, ".claude", "settings.local.json"), "local", "Local overrides");
36755
- memoryConfigFile(scan2, join17(claudeDir, "CLAUDE.md"), "user", "User memory");
36756
- memoryConfigFile(scan2, join17(cwd, "CLAUDE.md"), "project", "Project memory");
36757
- mcpJsonConfigFile(scan2, join17(cwd, ".mcp.json"));
36758
- dirConfigFile(scan2, join17(cwd, ".claude", "commands"), "Slash commands", "command");
36759
- dirConfigFile(scan2, join17(cwd, ".claude", "agents"), "Subagents", "subagent");
37423
+ settingsConfigFile(scan2, join19(claudeDir, "settings.json"), "user", "User settings");
37424
+ settingsConfigFile(scan2, join19(cwd, ".claude", "settings.json"), "project", "Project settings");
37425
+ settingsConfigFile(scan2, join19(cwd, ".claude", "settings.local.json"), "local", "Local overrides");
37426
+ memoryConfigFile(scan2, join19(claudeDir, "CLAUDE.md"), "user", "User memory");
37427
+ memoryConfigFile(scan2, join19(cwd, "CLAUDE.md"), "project", "Project memory");
37428
+ mcpJsonConfigFile(scan2, join19(cwd, ".mcp.json"));
37429
+ dirConfigFile(scan2, join19(cwd, ".claude", "commands"), "Slash commands", "command");
37430
+ dirConfigFile(scan2, join19(cwd, ".claude", "agents"), "Subagents", "subagent");
36760
37431
  }
36761
37432
  function configFileEntry(path, scope, kind) {
36762
37433
  try {
@@ -36831,7 +37502,7 @@ function countMarkdownFiles(dir, depth) {
36831
37502
  let count = 0;
36832
37503
  for (const dirent of readdirSync2(dir, { withFileTypes: true })) {
36833
37504
  if (dirent.name.startsWith(".")) continue;
36834
- if (dirent.isDirectory()) count += countMarkdownFiles(join17(dir, dirent.name), depth + 1);
37505
+ if (dirent.isDirectory()) count += countMarkdownFiles(join19(dir, dirent.name), depth + 1);
36835
37506
  else if (dirent.name.endsWith(".md")) count += 1;
36836
37507
  }
36837
37508
  return count;
@@ -36844,7 +37515,7 @@ function collectSkillsDir(scan2, dir, origin) {
36844
37515
  return;
36845
37516
  }
36846
37517
  for (const name of names) {
36847
- const skillFile = join17(dir, name, "SKILL.md");
37518
+ const skillFile = join19(dir, name, "SKILL.md");
36848
37519
  try {
36849
37520
  const raw = readOptional(skillFile);
36850
37521
  if (raw === void 0) continue;
@@ -36853,7 +37524,7 @@ function collectSkillsDir(scan2, dir, origin) {
36853
37524
  name: front.name ?? name,
36854
37525
  source: origin.source,
36855
37526
  scope: origin.scope,
36856
- location: join17(dir, name),
37527
+ location: join19(dir, name),
36857
37528
  updatedAt: statSync7(skillFile).mtime.toISOString()
36858
37529
  };
36859
37530
  const version2 = front.version ?? origin.defaultVersion;
@@ -36884,7 +37555,7 @@ function parseFrontmatter(raw) {
36884
37555
  return out;
36885
37556
  }
36886
37557
  function collectInstalledPlugins(scan2, claudeDir) {
36887
- const manifestPath = join17(claudeDir, "plugins", "installed_plugins.json");
37558
+ const manifestPath = join19(claudeDir, "plugins", "installed_plugins.json");
36888
37559
  const raw = readOptional(manifestPath);
36889
37560
  if (raw === void 0) return;
36890
37561
  let plugins;
@@ -36909,7 +37580,7 @@ function collectInstalledPlugins(scan2, claudeDir) {
36909
37580
  if (typeof installPath !== "string" || seen.has(installPath)) continue;
36910
37581
  seen.add(installPath);
36911
37582
  const version2 = install.version;
36912
- const hooksPath = join17(installPath, "hooks", "hooks.json");
37583
+ const hooksPath = join19(installPath, "hooks", "hooks.json");
36913
37584
  const hooksRaw = readOptional(hooksPath);
36914
37585
  if (hooksRaw !== void 0) {
36915
37586
  try {
@@ -36929,22 +37600,22 @@ function collectInstalledPlugins(scan2, claudeDir) {
36929
37600
  }
36930
37601
  const origin = { source: marketplace, scope: "plugin", pluginName };
36931
37602
  if (typeof version2 === "string") origin.defaultVersion = version2;
36932
- collectSkillsDir(scan2, join17(installPath, "skills"), origin);
37603
+ collectSkillsDir(scan2, join19(installPath, "skills"), origin);
36933
37604
  const mcpOrigin = { scope: "plugin", pluginName, marketplace };
36934
- collectMcpFile(scan2, join17(installPath, ".mcp.json"), mcpOrigin, { recordErrors: true });
37605
+ collectMcpFile(scan2, join19(installPath, ".mcp.json"), mcpOrigin, { recordErrors: true });
36935
37606
  collectPluginManifestMcp(scan2, installPath, mcpOrigin);
36936
37607
  }
36937
37608
  }
36938
37609
  }
36939
37610
  function collectMarketplaceSkills(scan2, claudeDir) {
36940
- for (const mp of readMarketplaces(join17(claudeDir, "plugins", "known_marketplaces.json"))) {
37611
+ for (const mp of readMarketplaces(join19(claudeDir, "plugins", "known_marketplaces.json"))) {
36941
37612
  if (isClaudeOfficialMarketplace(mp.name, mp.repo)) continue;
36942
- collectSkillsDir(scan2, join17(mp.installLocation, "skills"), {
37613
+ collectSkillsDir(scan2, join19(mp.installLocation, "skills"), {
36943
37614
  source: mp.name,
36944
37615
  scope: "plugin"
36945
37616
  });
36946
- collectPluginSkillDirs(scan2, join17(mp.installLocation, "plugins"), mp.name);
36947
- collectPluginSkillDirs(scan2, join17(mp.installLocation, "external_plugins"), mp.name);
37617
+ collectPluginSkillDirs(scan2, join19(mp.installLocation, "plugins"), mp.name);
37618
+ collectPluginSkillDirs(scan2, join19(mp.installLocation, "external_plugins"), mp.name);
36948
37619
  }
36949
37620
  }
36950
37621
  function collectPluginSkillDirs(scan2, pluginsDir, marketplace) {
@@ -36955,7 +37626,7 @@ function collectPluginSkillDirs(scan2, pluginsDir, marketplace) {
36955
37626
  return;
36956
37627
  }
36957
37628
  for (const plugin of plugins) {
36958
- collectSkillsDir(scan2, join17(pluginsDir, plugin, "skills"), {
37629
+ collectSkillsDir(scan2, join19(pluginsDir, plugin, "skills"), {
36959
37630
  source: marketplace,
36960
37631
  scope: "plugin",
36961
37632
  pluginName: plugin
@@ -37009,7 +37680,7 @@ function dedupeMcpServers(servers) {
37009
37680
  }
37010
37681
  function readOptional(path) {
37011
37682
  try {
37012
- return readFileSync10(path, "utf8");
37683
+ return readFileSync12(path, "utf8");
37013
37684
  } catch {
37014
37685
  return void 0;
37015
37686
  }
@@ -37042,8 +37713,8 @@ import { fileURLToPath } from "url";
37042
37713
  import { Worker } from "worker_threads";
37043
37714
 
37044
37715
  // ../../packages/plugin-sdk/src/host-floor.ts
37045
- import { readFileSync as readFileSync12 } from "fs";
37046
- import { join as join19 } from "path";
37716
+ import { readFileSync as readFileSync14 } from "fs";
37717
+ import { join as join21 } from "path";
37047
37718
 
37048
37719
  // ../../packages/plugin-sdk/src/model-governance.ts
37049
37720
  import {
@@ -37051,11 +37722,11 @@ import {
37051
37722
  fstatSync,
37052
37723
  mkdirSync as mkdirSync2,
37053
37724
  openSync as openSync2,
37054
- readFileSync as readFileSync11,
37725
+ readFileSync as readFileSync13,
37055
37726
  readSync,
37056
37727
  writeFileSync as writeFileSync5
37057
37728
  } from "fs";
37058
- import { join as join18 } from "path";
37729
+ import { join as join20 } from "path";
37059
37730
  var TAIL_BYTES = 256 * 1024;
37060
37731
 
37061
37732
  // ../../packages/plugin-sdk/src/host-floor.ts
@@ -37078,11 +37749,11 @@ var HOST_FLOORS = {
37078
37749
 
37079
37750
  // ../../packages/plugin-sdk/src/ignore-layers.ts
37080
37751
  var import_ignore = __toESM(require_ignore(), 1);
37081
- import { readFileSync as readFileSync13 } from "fs";
37082
- import { join as join20 } from "path";
37752
+ import { readFileSync as readFileSync15 } from "fs";
37753
+ import { join as join22 } from "path";
37083
37754
  function readIgnoreLayer(dir, filename, anchorLen) {
37084
37755
  try {
37085
- return { matcher: (0, import_ignore.default)().add(readFileSync13(join20(dir, filename), "utf8")), anchorLen };
37756
+ return { matcher: (0, import_ignore.default)().add(readFileSync15(join22(dir, filename), "utf8")), anchorLen };
37086
37757
  } catch {
37087
37758
  return void 0;
37088
37759
  }
@@ -37139,17 +37810,17 @@ function resolveInventoryContext(input2) {
37139
37810
  }
37140
37811
 
37141
37812
  // ../../packages/plugin-sdk/src/nudge.ts
37142
- import { mkdirSync as mkdirSync3, readFileSync as readFileSync14, writeFileSync as writeFileSync6 } from "fs";
37143
- import { join as join21 } from "path";
37813
+ import { mkdirSync as mkdirSync3, readFileSync as readFileSync16, writeFileSync as writeFileSync6 } from "fs";
37814
+ import { join as join23 } from "path";
37144
37815
  var SESSION_START_MARKER = "session-start-last";
37145
37816
  function claimSessionStart(dataDir2, sessionId) {
37146
37817
  return claimOncePerSession(dataDir2, SESSION_START_MARKER, sessionId);
37147
37818
  }
37148
37819
  function claimOncePerSession(dataDir2, marker, sessionId) {
37149
37820
  if (!sessionId) return true;
37150
- const path = join21(dataDir2, marker);
37821
+ const path = join23(dataDir2, marker);
37151
37822
  try {
37152
- if (readFileSync14(path, "utf8") === sessionId) return false;
37823
+ if (readFileSync16(path, "utf8") === sessionId) return false;
37153
37824
  } catch {
37154
37825
  }
37155
37826
  try {
@@ -37166,7 +37837,7 @@ import { basename as basename5, dirname as dirname5, sep as sep3 } from "path";
37166
37837
 
37167
37838
  // ../../packages/plugin-sdk/src/project-files.ts
37168
37839
  import { existsSync as existsSync11, readdirSync as readdirSync4 } from "fs";
37169
- import { basename as basename6, join as join22 } from "path";
37840
+ import { basename as basename6, join as join24 } from "path";
37170
37841
  var SKIP_DIRS = /* @__PURE__ */ new Set([
37171
37842
  ".git",
37172
37843
  "node_modules",
@@ -37263,8 +37934,8 @@ function resolveProjectFiles(cwd, opts = {}) {
37263
37934
  }
37264
37935
  if (entry.isDirectory()) {
37265
37936
  if (SKIP_DIRS.has(entry.name) || isIgnored(dirLayers, dirRel, entry.name, true)) continue;
37266
- const fullPath = join22(dir, entry.name);
37267
- if (existsSync11(join22(fullPath, ".git"))) continue;
37937
+ const fullPath = join24(dir, entry.name);
37938
+ if (existsSync11(join24(fullPath, ".git"))) continue;
37268
37939
  if (depth >= bounds.maxDepth) {
37269
37940
  walk.omitted = true;
37270
37941
  continue;
@@ -37365,9 +38036,9 @@ var THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1e3;
37365
38036
 
37366
38037
  // ../../packages/plugin-sdk/src/throttle.ts
37367
38038
  import { mkdirSync as mkdirSync4, statSync as statSync8, writeFileSync as writeFileSync7 } from "fs";
37368
- import { join as join23 } from "path";
38039
+ import { join as join25 } from "path";
37369
38040
  function throttled(dataDir2, markerName, windowMs) {
37370
- const marker = join23(dataDir2, markerName);
38041
+ const marker = join25(dataDir2, markerName);
37371
38042
  try {
37372
38043
  if (Date.now() - statSync8(marker).mtimeMs < windowMs) return true;
37373
38044
  } catch {
@@ -37394,31 +38065,12 @@ function isServerRejection(err) {
37394
38065
  var FORWARD_BUDGET_MS = 1500;
37395
38066
  var DECISION_PATH_BUDGET_MS = 800;
37396
38067
  var BREAKER_FAILURE_THRESHOLD = 3;
37397
- var BREAKER_COOLDOWN_MS = 3e4;
37398
38068
  var CLOSED = { consecutiveFailures: 0, openedAtMs: null, lastFailure: null };
37399
- var FAILURES = /* @__PURE__ */ new Set([
37400
- "unauthorized",
37401
- "forbidden",
37402
- "unreachable"
37403
- ]);
37404
38069
  var FORWARD_STATE_FILENAME = ATTACHED_FORWARD_STATE_FILENAME;
37405
38070
  var STATE_FILENAME = FORWARD_STATE_FILENAME;
37406
- function parseBreakerState(raw, nowMs) {
37407
- try {
37408
- const parsed2 = JSON.parse(raw);
37409
- if (typeof parsed2 !== "object" || parsed2 === null) return null;
37410
- const record2 = parsed2;
37411
- const failures = typeof record2.consecutiveFailures === "number" && record2.consecutiveFailures >= 0 ? record2.consecutiveFailures : 0;
37412
- const openedAtMs = typeof record2.openedAtMs === "number" && Number.isFinite(record2.openedAtMs) && record2.openedAtMs <= nowMs ? record2.openedAtMs : null;
37413
- const lastFailure = typeof record2.lastFailure === "string" && FAILURES.has(record2.lastFailure) ? record2.lastFailure : null;
37414
- return { consecutiveFailures: failures, openedAtMs, lastFailure };
37415
- } catch {
37416
- return null;
37417
- }
37418
- }
37419
38071
  function createForwardPolicy(deps) {
37420
38072
  const now = deps.now ?? (() => Date.now());
37421
- const file2 = join24(deps.dir, STATE_FILENAME);
38073
+ const file2 = join26(deps.dir, STATE_FILENAME);
37422
38074
  let state = null;
37423
38075
  let loading = null;
37424
38076
  async function readState() {
@@ -37428,7 +38080,7 @@ function createForwardPolicy(deps) {
37428
38080
  } catch {
37429
38081
  return { ...CLOSED };
37430
38082
  }
37431
- return parseBreakerState(raw, now()) ?? { ...CLOSED };
38083
+ return parseForwardHealth(raw, now()) ?? { ...CLOSED };
37432
38084
  }
37433
38085
  async function load() {
37434
38086
  if (state !== null) return state;
@@ -37474,7 +38126,7 @@ function createForwardPolicy(deps) {
37474
38126
  };
37475
38127
  const at = now();
37476
38128
  if (current.openedAtMs !== null) {
37477
- if (at - current.openedAtMs < BREAKER_COOLDOWN_MS) {
38129
+ if (isForwardPaused(current, at)) {
37478
38130
  return { ok: false, reason: "breaker-open" };
37479
38131
  }
37480
38132
  await persist({
@@ -38011,7 +38663,18 @@ var AttachedDataGateway = class {
38011
38663
  // and the spread above would otherwise drop the field silently — which is
38012
38664
  // exactly what it did, leaving the whole control inert on every device
38013
38665
  // while every test around it stayed green.
38014
- prohibitedModels: cached2.prohibitedModels
38666
+ prohibitedModels: cached2.prohibitedModels,
38667
+ // NAMED for the same reason as the line above, and it is the same defect
38668
+ // if it is not: `...local` above spreads the DEVICE's bundle, so a field
38669
+ // only the cache carries is dropped in silence. That is what left
38670
+ // `prohibitedModels` inert on every attached device with every test
38671
+ // around it green.
38672
+ //
38673
+ // Taken from the cache rather than merged here, because merging it needs
38674
+ // the device's own SETTING — which is not a bundle field and is not in
38675
+ // scope at this seam. The runtime does that merge, raise-only, where both
38676
+ // values are in hand (createPluginRuntime's ensureInitialized).
38677
+ redactFallback: cached2.redactFallback
38015
38678
  // ALSO HONOURED FROM THE CACHE, and not a bundle field at all: each
38016
38679
  // merged policy's own `provenance`. `mergeRaiseOnly` spreads the policies
38017
38680
  // it emits, so an 'authored' policy arriving from the control plane
@@ -38139,10 +38802,6 @@ function toolAuditEvent(input2) {
38139
38802
  };
38140
38803
  }
38141
38804
 
38142
- // ../../packages/plugin-runtime/src/attached/history-state.ts
38143
- import { readFileSync as readFileSync16 } from "fs";
38144
- import { join as join25 } from "path";
38145
-
38146
38805
  // ../../packages/plugin-runtime/src/attached/history-sync.ts
38147
38806
  import { createHash as createHash6 } from "crypto";
38148
38807
  import { hostname as hostname5 } from "os";
@@ -38151,6 +38810,10 @@ import { hostname as hostname5 } from "os";
38151
38810
  var CORRELATION_ID = EventMetadata.shape.correlationId;
38152
38811
  var TRACE_ID = EventMetadata.shape.traceId;
38153
38812
  var EXCEPTION_ID = EventMetadata.shape.exceptionIds.unwrap().element;
38813
+ var REDACT_DEGRADED_TO = EventMetadata.shape.redactDegradedTo.unwrap();
38814
+
38815
+ // ../../packages/plugin-runtime/src/attached/history-sync.ts
38816
+ var CAPTURE_BATCH_BYTES = 1024 * 1024;
38154
38817
 
38155
38818
  // ../../packages/plugin-runtime/src/attached/history-sync-trigger.ts
38156
38819
  import { spawn } from "child_process";
@@ -38216,7 +38879,7 @@ function createPluginBlock(build, policyStore) {
38216
38879
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
38217
38880
  import { randomUUID as randomUUID16 } from "crypto";
38218
38881
  import { readFile as readFile2, rm, writeFile as writeFile2 } from "fs/promises";
38219
- import { join as join26 } from "path";
38882
+ import { join as join27 } from "path";
38220
38883
 
38221
38884
  // ../../packages/plugin-runtime/src/attached/atomic-publish.ts
38222
38885
  import { rename as rename2 } from "fs/promises";
@@ -38240,7 +38903,7 @@ async function publishByRename(tmp, file2, move = rename2) {
38240
38903
 
38241
38904
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
38242
38905
  function createPolicyStore(dir = dataDir()) {
38243
- const file2 = join26(dir, "policy-cache.json");
38906
+ const file2 = join27(dir, "policy-cache.json");
38244
38907
  async function read() {
38245
38908
  try {
38246
38909
  const raw = await readFile2(file2, "utf8");
@@ -38471,11 +39134,11 @@ function readStorePosture(dbPath2) {
38471
39134
  // ../../packages/plugin-runtime/src/attached/posture-store.ts
38472
39135
  import { randomUUID as randomUUID17 } from "crypto";
38473
39136
  import { readFile as readFile3, rm as rm2, writeFile as writeFile3 } from "fs/promises";
38474
- import { join as join27 } from "path";
39137
+ import { join as join28 } from "path";
38475
39138
  var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
38476
39139
  function createPostureStore(dir = settingsDir(), legacyDir) {
38477
- const file2 = join27(dir, "posture-state.json");
38478
- const legacyFile = legacyDir === void 0 ? null : join27(legacyDir, "posture-state.json");
39140
+ const file2 = join28(dir, "posture-state.json");
39141
+ const legacyFile = legacyDir === void 0 ? null : join28(legacyDir, "posture-state.json");
38479
39142
  async function persist(state) {
38480
39143
  await ensureDataDir(dir);
38481
39144
  const tmp = `${file2}.${randomUUID17()}.tmp`;
@@ -38544,7 +39207,7 @@ function createPostureStore(dir = settingsDir(), legacyDir) {
38544
39207
 
38545
39208
  // ../../packages/plugin-runtime/src/attached/sync-state.ts
38546
39209
  import { readFileSync as readFileSync18 } from "fs";
38547
- import { join as join28 } from "path";
39210
+ import { join as join29 } from "path";
38548
39211
 
38549
39212
  // ../../packages/plugin-runtime/src/attached/status.ts
38550
39213
  var REFUSAL_LINES = {
@@ -38586,6 +39249,34 @@ function spawnDetached2(scriptPath) {
38586
39249
  child.unref();
38587
39250
  }
38588
39251
 
39252
+ // ../../packages/plugin-runtime/src/content-retention-pass.ts
39253
+ var MAX_ROWS_PER_SWEEP = 50 * 1e3;
39254
+
39255
+ // ../../packages/plugin-runtime/src/content-retention-trigger.ts
39256
+ import { spawn as spawn3 } from "child_process";
39257
+ import { fileURLToPath as fileURLToPath4 } from "url";
39258
+ var CONTENT_RETENTION_MARKER_NAME = "content-retention-last-attempt";
39259
+ var CONTENT_RETENTION_SCRIPT_NAME = "content-retention.js";
39260
+ var CONTENT_RETENTION_THROTTLE_MS = 60 * 60 * 1e3;
39261
+ function triggerContentRetention(config2, deps = {}) {
39262
+ try {
39263
+ if (!config2.settings.bodyRetention.enabled) return;
39264
+ const isThrottled = deps.isThrottled ?? ((dir) => throttled(dir, CONTENT_RETENTION_MARKER_NAME, CONTENT_RETENTION_THROTTLE_MS));
39265
+ if (isThrottled(config2.dataDir)) return;
39266
+ const scriptPath = fileURLToPath4(
39267
+ deps.scriptUrl ?? new URL(CONTENT_RETENTION_SCRIPT_NAME, import.meta.url)
39268
+ );
39269
+ (deps.spawnChild ?? spawnDetached3)(scriptPath);
39270
+ } catch {
39271
+ }
39272
+ }
39273
+ function spawnDetached3(scriptPath) {
39274
+ const child = spawn3(process.execPath, [scriptPath], { detached: true, stdio: "ignore" });
39275
+ child.on("error", () => {
39276
+ });
39277
+ child.unref();
39278
+ }
39279
+
38589
39280
  // ../../packages/plugin-runtime/src/attached/factory.ts
38590
39281
  import { hostname as hostname6 } from "os";
38591
39282
 
@@ -39102,6 +39793,7 @@ async function handleSessionStart(input2, config2 = loadConfig()) {
39102
39793
  }
39103
39794
  triggerPolicySync(config2);
39104
39795
  triggerHistorySync(config2);
39796
+ triggerContentRetention(config2);
39105
39797
  if (input2.harnessVersion !== void 0 && offersMaintenance(gateway, "staleBinaryNotice")) {
39106
39798
  return { staleBinaryNotice: gateway.staleBinaryNotice(input2.harnessVersion) };
39107
39799
  }
@@ -39183,9 +39875,9 @@ function pluginBuild() {
39183
39875
  }
39184
39876
 
39185
39877
  // src/history/reconcile-trigger.ts
39186
- import { spawn as spawn3 } from "child_process";
39187
- import { dirname as dirname6, join as join30 } from "path";
39188
- import { fileURLToPath as fileURLToPath4 } from "url";
39878
+ import { spawn as spawn4 } from "child_process";
39879
+ import { dirname as dirname6, join as join31 } from "path";
39880
+ import { fileURLToPath as fileURLToPath5 } from "url";
39189
39881
 
39190
39882
  // src/history/tail.ts
39191
39883
  import { createHash as createHash7 } from "crypto";
@@ -39198,7 +39890,7 @@ import {
39198
39890
  readSync as readSync2,
39199
39891
  writeFileSync as writeFileSync8
39200
39892
  } from "fs";
39201
- import { join as join29 } from "path";
39893
+ import { join as join30 } from "path";
39202
39894
  var SAFE_SESSION_ID = /^[A-Za-z0-9._-]+$/;
39203
39895
  function safeSessionId(sessionId) {
39204
39896
  if (SAFE_SESSION_ID.test(sessionId) && sessionId !== "." && sessionId !== "..") {
@@ -39214,8 +39906,8 @@ function triggerReconcile(dataDir2, sessionId, transcriptPath) {
39214
39906
  try {
39215
39907
  const marker = `${RECONCILE_MARKER_PREFIX}-${safeSessionId(sessionId)}`;
39216
39908
  if (throttled(dataDir2, marker, RECONCILE_THROTTLE_MS)) return;
39217
- const here = dirname6(fileURLToPath4(import.meta.url));
39218
- const child = spawn3(process.execPath, [join30(here, "reconcile.js"), sessionId, transcriptPath], {
39909
+ const here = dirname6(fileURLToPath5(import.meta.url));
39910
+ const child = spawn4(process.execPath, [join31(here, "reconcile.js"), sessionId, transcriptPath], {
39219
39911
  detached: true,
39220
39912
  stdio: "ignore"
39221
39913
  });
@@ -39227,7 +39919,7 @@ function triggerReconcile(dataDir2, sessionId, transcriptPath) {
39227
39919
  // src/history/transcripts.ts
39228
39920
  import { closeSync as closeSync4, openSync as openSync4, readdirSync as readdirSync5, readFileSync as readFileSync20, readSync as readSync3, statSync as statSync10 } from "fs";
39229
39921
  import { homedir as homedir3 } from "os";
39230
- import { join as join31 } from "path";
39922
+ import { join as join32 } from "path";
39231
39923
  function isRecord(value) {
39232
39924
  return typeof value === "object" && value !== null;
39233
39925
  }
@@ -39302,7 +39994,7 @@ function getString(record2, key) {
39302
39994
 
39303
39995
  // src/hooks/store-health.ts
39304
39996
  import { mkdirSync as mkdirSync6, readFileSync as readFileSync21, writeFileSync as writeFileSync9 } from "fs";
39305
- import { dirname as dirname7, join as join32 } from "path";
39997
+ import { dirname as dirname7, join as join33 } from "path";
39306
39998
  var STORE_REDIRECT_MARKER = "store-redirect-last-session";
39307
39999
  function markerDirs(dataDir2) {
39308
40000
  return [dataDir2, dirname7(dataDir2)];
@@ -39310,7 +40002,7 @@ function markerDirs(dataDir2) {
39310
40002
  function alreadyClaimed(dirs, marker, sessionId) {
39311
40003
  return dirs.some((dir) => {
39312
40004
  try {
39313
- return readFileSync21(join32(dir, marker), "utf8") === sessionId;
40005
+ return readFileSync21(join33(dir, marker), "utf8") === sessionId;
39314
40006
  } catch {
39315
40007
  return false;
39316
40008
  }
@@ -39320,7 +40012,7 @@ function recordClaim(dirs, marker, sessionId) {
39320
40012
  for (const dir of dirs) {
39321
40013
  try {
39322
40014
  mkdirSync6(dir, { recursive: true, mode: DATA_DIR_MODE });
39323
- writeFileSync9(join32(dir, marker), sessionId, { mode: DATA_FILE_MODE });
40015
+ writeFileSync9(join33(dir, marker), sessionId, { mode: DATA_FILE_MODE });
39324
40016
  return;
39325
40017
  } catch {
39326
40018
  }