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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/scripts/query.js CHANGED
@@ -50,7 +50,7 @@ var require_ignore = __commonJS({
50
50
  var REGEX_SPLITALL_CRLF = /\r?\n/g;
51
51
  var REGEX_TEST_INVALID_PATH = /^\.{0,2}\/|^\.{1,2}$/;
52
52
  var REGEX_TEST_TRAILING_SLASH = /\/$/;
53
- var SLASH2 = "/";
53
+ var SLASH3 = "/";
54
54
  var TMP_KEY_IGNORE = "node-ignore";
55
55
  if (typeof Symbol !== "undefined") {
56
56
  TMP_KEY_IGNORE = /* @__PURE__ */ Symbol.for("node-ignore");
@@ -422,11 +422,11 @@ var require_ignore = __commonJS({
422
422
  if (!REGEX_TEST_TRAILING_SLASH.test(path)) {
423
423
  return this.test(path);
424
424
  }
425
- const slices = path.split(SLASH2).filter(Boolean);
425
+ const slices = path.split(SLASH3).filter(Boolean);
426
426
  slices.pop();
427
427
  if (slices.length) {
428
428
  const parent = this._t(
429
- slices.join(SLASH2) + SLASH2,
429
+ slices.join(SLASH3) + SLASH3,
430
430
  this._testCache,
431
431
  true,
432
432
  slices
@@ -442,14 +442,14 @@ var require_ignore = __commonJS({
442
442
  return cache[path];
443
443
  }
444
444
  if (!slices) {
445
- slices = path.split(SLASH2).filter(Boolean);
445
+ slices = path.split(SLASH3).filter(Boolean);
446
446
  }
447
447
  slices.pop();
448
448
  if (!slices.length) {
449
449
  return cache[path] = this._rules.test(path, checkUnignored, MODE_IGNORE);
450
450
  }
451
451
  const parent = this._t(
452
- slices.join(SLASH2) + SLASH2,
452
+ slices.join(SLASH3) + SLASH3,
453
453
  cache,
454
454
  checkUnignored,
455
455
  slices
@@ -502,6 +502,14 @@ var ATTACHED_FORWARD_DROPS_FILENAME = "attached-forward-drops.json";
502
502
  import { chmodSync as chmodSync2, lstatSync as lstatSync2, readFileSync, rmSync as rmSync3, statSync } from "fs";
503
503
  import { join as join2 } from "path";
504
504
 
505
+ // ../../packages/schema/src/drizzle/deferred-migrations.ts
506
+ var DEFERRED_MIGRATION_TAGS = [
507
+ "0031_audit_capture_by_time_index",
508
+ "0032_audit_capture_by_id_index",
509
+ "0033_audit_capture_location_index",
510
+ "0034_findings_read_indexes"
511
+ ];
512
+
505
513
  // ../../packages/schema/src/drizzle/sqlite-ddl.ts
506
514
  var SQLITE_MIGRATIONS = [
507
515
  {
@@ -619,6 +627,30 @@ var SQLITE_MIGRATIONS = [
619
627
  {
620
628
  tag: "0028_activity_session_probe_indexes",
621
629
  sql: "CREATE INDEX `idx_audit_session_prompt` ON `audit_events` (`root_session_id`) WHERE event_type = 'prompt';--> statement-breakpoint\nCREATE INDEX `idx_audit_session_share` ON `audit_events` (`root_session_id`) WHERE event_type = 'share';--> statement-breakpoint\nCREATE INDEX `idx_audit_ended_at` ON `audit_events` (`ended_at`,`root_session_id`) WHERE ended_at IS NOT NULL;--> statement-breakpoint\nCREATE INDEX `idx_audit_session_ended` ON `audit_events` (`root_session_id`,`ended_at`) WHERE ended_at IS NOT NULL;--> statement-breakpoint\n-- Expression index for the activity list's turns rollup: a live-captured\n-- session's turns are the DISTINCT `run_key` across its `llm_call` leaves, and\n-- carrying the extracted key in the index answers that count from the index\n-- alone instead of parsing every leaf's attribute bag. Written by hand, as\n-- 0013's `idx_audit_code_change_path` was: drizzle-kit cannot emit an\n-- expression containing a comma, so this index is not declared in sqlite.ts.\nCREATE INDEX `idx_audit_session_run_key` ON `audit_events` (`root_session_id`, json_extract(`attributes`, '$.run_key')) WHERE `event_type` = 'llm_call';\n"
630
+ },
631
+ {
632
+ tag: "0029_audit_capture_rollup_index",
633
+ sql: "CREATE INDEX `idx_audit_capture_rollup` ON `audit_events` (`event_type`,`started_at`,`repo`,`id`) WHERE event_type IN ('prompt','response','code_change','tool_use');"
634
+ },
635
+ {
636
+ tag: "0030_audit_content_expiry",
637
+ sql: "ALTER TABLE `audit_events` ADD `content_expired_at` integer;--> statement-breakpoint\nCREATE INDEX `idx_audit_expirable_body` ON `audit_events` (`started_at`) WHERE content IS NOT NULL;"
638
+ },
639
+ {
640
+ tag: "0031_audit_capture_by_time_index",
641
+ sql: "CREATE INDEX `idx_audit_capture_by_time` ON `audit_events` (`started_at`,`id`,`event_type`,`root_session_id`,`source_tool`,`repo`,`file_path`,`tool_name`) WHERE event_type IN ('prompt','response','code_change','tool_use');"
642
+ },
643
+ {
644
+ tag: "0032_audit_capture_by_id_index",
645
+ sql: "CREATE INDEX `idx_audit_capture_by_id` ON `audit_events` (`id`,`started_at`,`event_type`,`root_session_id`,`source_tool`,`repo`,`file_path`,`tool_name`) WHERE event_type IN ('prompt','response','code_change','tool_use');"
646
+ },
647
+ {
648
+ tag: "0033_audit_capture_location_index",
649
+ sql: "CREATE INDEX `idx_audit_capture_location` ON `audit_events` (`repo`,`file_path`,`started_at`,`id`,`event_type`) WHERE event_type IN ('prompt','response','code_change','tool_use');"
650
+ },
651
+ {
652
+ tag: "0034_findings_read_indexes",
653
+ sql: "CREATE INDEX `idx_inspection_definitions_rule` ON `inspection_definitions` (`rule_id`,`severity`,`category`);--> statement-breakpoint\nCREATE INDEX `idx_inspection_findings_def` ON `inspection_findings` (`inspection_definition_id`,`audit_event_id`);--> statement-breakpoint\nCREATE INDEX `idx_inspection_findings_event_cover` ON `inspection_findings` (`audit_event_id`,`inspection_definition_id`,`action_taken`,`finding_key`,`id`);"
622
654
  }
623
655
  ];
624
656
 
@@ -20427,9 +20459,8 @@ var SEVERITY_WEIGHT = {
20427
20459
  medium: 2,
20428
20460
  low: 1
20429
20461
  };
20430
- var SEVERITY_WEIGHT_BY_STRING = SEVERITY_WEIGHT;
20431
20462
  function severityWeight(severity) {
20432
- return SEVERITY_WEIGHT_BY_STRING[severity] ?? 0;
20463
+ return Object.hasOwn(SEVERITY_WEIGHT, severity) ? SEVERITY_WEIGHT[severity] : 0;
20433
20464
  }
20434
20465
  var ADVICE = {
20435
20466
  secret: "Rotate the exposed credentials and move them out of prompts (secrets manager / env vars).",
@@ -20821,6 +20852,15 @@ var FindingCategory = external_exports.enum([
20821
20852
  ]).meta({ id: "FindingCategory" });
20822
20853
  var FindingOrigin = external_exports.enum(["in-flight", "at-rest"]).meta({ id: "FindingOrigin" });
20823
20854
  var FindingStatus = external_exports.enum(["open", "handled", "resolved", "dismissed"]).meta({ id: "FindingStatus" });
20855
+ var SyncFailureReason = external_exports.enum(["deployment_refused", "payload_invalid", "detached_undelivered"]).meta({ id: "SyncFailureReason" });
20856
+ var FindingDeliveryState = external_exports.enum(["sent", "queued", "not_sent", "never_offered", "local_scan"]).meta({ id: "FindingDeliveryState" });
20857
+ var FindingDelivery = external_exports.object({
20858
+ state: FindingDeliveryState,
20859
+ // The delivery time for `sent`; the failure time for `not_sent` when recorded.
20860
+ at: external_exports.iso.datetime().optional(),
20861
+ // Only on `not_sent`, and only when a known reason was recorded.
20862
+ reason: SyncFailureReason.optional()
20863
+ }).meta({ id: "FindingDelivery" });
20824
20864
  var ResolutionMethod = external_exports.enum([
20825
20865
  "enforced-in-flight",
20826
20866
  "fixed-at-source",
@@ -20877,7 +20917,10 @@ var FindingInstance = external_exports.object({
20877
20917
  // The session that event belongs to, when it has one — the seam a
20878
20918
  // per-instance "view session" link needs. Absent for events captured
20879
20919
  // outside a session.
20880
- sessionId: external_exports.string().optional()
20920
+ sessionId: external_exports.string().optional(),
20921
+ // The delivery state of the event above (see FindingDelivery). Optional so
20922
+ // readers that do not project it stay valid.
20923
+ delivery: FindingDelivery.optional()
20881
20924
  }).meta({ id: "FindingInstance" });
20882
20925
  var FindingGroup = external_exports.object({
20883
20926
  id: external_exports.string(),
@@ -20929,7 +20972,10 @@ var FindingFacets = external_exports.object({
20929
20972
  // Host tool (attributes.tool_name). Present only on the instance-level
20930
20973
  // reads, which can filter by it; the type-level read omits the dimension
20931
20974
  // because a group spans tools.
20932
- tool: external_exports.array(FindingFacetItem).optional()
20975
+ tool: external_exports.array(FindingFacetItem).optional(),
20976
+ // Delivery states (FindingDeliveryState). Present only on the
20977
+ // instance-level reads, like `tool`.
20978
+ deployment: external_exports.array(FindingFacetItem).optional()
20933
20979
  }).meta({ id: "FindingFacets" });
20934
20980
  var FindingTypeSummary = FindingGroup.omit({ instances: true, match: true }).meta({
20935
20981
  id: "FindingTypeSummary"
@@ -21040,6 +21086,8 @@ var ListFindingInstancesQuery = external_exports.object({
21040
21086
  // Exact host-tool names (attributes.tool_name, e.g. 'Bash'). A real filter,
21041
21087
  // where the free-text `q` can only match the rendered "via Bash" label.
21042
21088
  tool: external_exports.array(external_exports.string()).optional(),
21089
+ // The delivery state of each finding's event (see FindingDelivery).
21090
+ deployment: external_exports.array(FindingDeliveryState).optional(),
21043
21091
  // Exact repository / file-path matches, for the drill-down out of the
21044
21092
  // locations view. A row whose event carries no repo/file matches neither.
21045
21093
  repo: external_exports.string().optional(),
@@ -21060,6 +21108,10 @@ var ListFindingInstancesResponse = external_exports.object({
21060
21108
  items: external_exports.array(FindingInstanceDetail),
21061
21109
  nextCursor: external_exports.string().nullable()
21062
21110
  }).meta({ id: "ListFindingInstancesResponse" });
21111
+ var ListFindingInstancesPage = external_exports.object({
21112
+ items: external_exports.array(FindingInstanceDetail),
21113
+ nextCursor: external_exports.string().nullable()
21114
+ }).meta({ id: "ListFindingInstancesPage" });
21063
21115
  var FindingLocationSummary = external_exports.object({
21064
21116
  // Opaque, stable, minted from the pair by encodeLocationId. It exists
21065
21117
  // because a location's identity is two values and a URL param carries one:
@@ -21102,6 +21154,8 @@ var ListFindingLocationsQuery = external_exports.object({
21102
21154
  // instances that match, and folds its status from those.
21103
21155
  status: external_exports.array(FindingStatus).optional(),
21104
21156
  tool: external_exports.array(external_exports.string()).optional(),
21157
+ // The delivery state of each finding's event (see FindingDelivery).
21158
+ deployment: external_exports.array(FindingDeliveryState).optional(),
21105
21159
  q: external_exports.string().optional(),
21106
21160
  sessionId: external_exports.string().optional(),
21107
21161
  from: external_exports.iso.datetime().optional(),
@@ -21304,6 +21358,10 @@ var CaptureAttributes = external_exports.object({
21304
21358
  // to 'allow' — the enforcement audit trail's link back to the grant that
21305
21359
  // authorized the bypass.
21306
21360
  exception_ids: external_exports.array(external_exports.guid()).optional(),
21361
+ // The persisted spellings of EventMetadata's messageId/conversationId — the
21362
+ // join back to the `llm_call` leaf for the same assistant turn.
21363
+ message_id: external_exports.string().optional(),
21364
+ conversation_id: external_exports.string().optional(),
21307
21365
  // Whole milliseconds this capture's inspection blocked its caller — the
21308
21366
  // plugin's own added latency (see EventMetadata.inspectionMs, whose value
21309
21367
  // this is). Promoted to the `inspection_ms` generated column so the facet is
@@ -21312,7 +21370,19 @@ var CaptureAttributes = external_exports.object({
21312
21370
  // inline json_extract and is not itself an optimization.
21313
21371
  // ABSENT on replayed captures (backfill / worktree scan) and on rows written
21314
21372
  // before the measurement shipped — never present as a placeholder 0.
21315
- inspection_ms: external_exports.number().int().nonnegative().optional()
21373
+ inspection_ms: external_exports.number().int().nonnegative().optional(),
21374
+ // What a `redact` this capture could not carry out became instead (see
21375
+ // EventMetadata.redactDegradedTo, whose value this is). Present only when a
21376
+ // degrade actually happened, so absence is the ordinary case rather than a
21377
+ // reader having to distinguish it from a zero.
21378
+ //
21379
+ // PER CAPTURE, while `inspection_findings.action_taken` is per finding —
21380
+ // so on a multi-finding row this does not say which finding degraded, and
21381
+ // its presence does not mean the fallback decided the capture's action. A
21382
+ // capture denied by another finding's own Block policy carries `block`
21383
+ // here too. The full statement is on EventMetadata.redactDegradedTo; it is
21384
+ // repeated rather than referenced because a store reader opens this file.
21385
+ redact_degraded_to: ActionTaken.optional()
21316
21386
  }).catchall(external_exports.unknown());
21317
21387
  var ToolCallInspection = external_exports.object({
21318
21388
  ruleId: external_exports.string().min(1),
@@ -21511,7 +21581,17 @@ var AuditEvent = external_exports.object({
21511
21581
  /** `share` to a first-party/internal destination. */
21512
21582
  internal: external_exports.boolean(),
21513
21583
  /** Event needs review (e.g. unverified egress). */
21514
- flagged: external_exports.boolean()
21584
+ flagged: external_exports.boolean(),
21585
+ /**
21586
+ * The body this event's `title` is drawn from was cleared by local body
21587
+ * expiry, so an EMPTY title here means "gone", not "never had one".
21588
+ *
21589
+ * A separate flag rather than a sentinel written into `title`: the title is
21590
+ * rendered text, and a store-layer module that invented display copy for it
21591
+ * would be choosing words the view is supposed to choose. Additive and
21592
+ * defaulted, so an older producer still validates.
21593
+ */
21594
+ bodyExpired: external_exports.boolean().default(false)
21515
21595
  }).meta({ id: "ActivityAuditEvent" });
21516
21596
  var ActivitySessionSummary = external_exports.object({
21517
21597
  id: external_exports.string(),
@@ -22852,6 +22932,12 @@ var EventMetadata = external_exports.object({
22852
22932
  // to 'allow' — the enforcement audit trail's link back to the grant that
22853
22933
  // authorized the bypass. Absent on captures where no exception applied.
22854
22934
  exceptionIds: external_exports.array(external_exports.guid()).optional(),
22935
+ // The assistant message this capture belongs to, and the conversation it sits
22936
+ // in — set by the browser extension's network capture so a stored `response`
22937
+ // row can be joined to the `llm_call` leaf describing the same turn. Absent
22938
+ // on every other capture path, which has no such id.
22939
+ messageId: external_exports.string().optional(),
22940
+ conversationId: external_exports.string().optional(),
22855
22941
  // How long THIS capture's inspection blocked its caller, in whole
22856
22942
  // milliseconds — the plugin's own added latency, NOT the LLM call it sat in
22857
22943
  // front of. Measured inside `capture()` (@akasecurity/plugin-sdk) across
@@ -22864,7 +22950,37 @@ var EventMetadata = external_exports.object({
22864
22950
  // Absent is also what every pre-measurement client writes, and what a
22865
22951
  // clock failure degrades to — a reader must treat absence as "not measured"
22866
22952
  // and never as a zero, which would read as "inspection is free".
22867
- inspectionMs: external_exports.number().int().nonnegative().optional()
22953
+ inspectionMs: external_exports.number().int().nonnegative().optional(),
22954
+ // What a `redact` this capture COULD NOT CARRY OUT became instead — the
22955
+ // workspace's `redactFallback`, applied because the field could not be
22956
+ // masked in place (a shell command, a URL, or any argument on a host whose
22957
+ // hook contract offers no rewrite channel).
22958
+ //
22959
+ // It exists because the action alone cannot say why. A finding recorded as
22960
+ // `warn` reads identically whether its detection was ASSIGNED Warn or was
22961
+ // assigned Redact on a field that could not take one — and those are
22962
+ // different facts about the same row: the first is a policy the user chose,
22963
+ // the second is a masking the host could not perform. Absent means no
22964
+ // degrade happened, which is every ordinary capture.
22965
+ //
22966
+ // TWO LIMITS a reader of a stored row has to know, because the grain here
22967
+ // is the CAPTURE while `actionTaken` is per FINDING:
22968
+ //
22969
+ // - It does not say WHICH finding degraded. A capture carrying a degraded
22970
+ // `redact` alongside a finding ASSIGNED the same action stores both
22971
+ // identically and one reason for the pair; attributing it to both
22972
+ // describes the assigned one wrongly, and to neither loses the degrade.
22973
+ // - PRESENCE IS NOT CAUSATION. The value is the action the lost redact
22974
+ // became, not the reason the capture ended as it did — a capture denied
22975
+ // by some other finding's own Block policy still carries `block` here,
22976
+ // and clearing the workspace's fallback would not have let it through.
22977
+ // Gate on the value against what a fallback can produce; never read the
22978
+ // field's presence as "this was the fallback's doing".
22979
+ //
22980
+ // Both are pinned as behaviour in @akasecurity/plugin-sdk's runtime suite.
22981
+ // Closing either means moving the reason onto the finding row, which
22982
+ // already carries its own action.
22983
+ redactDegradedTo: ActionTaken.optional()
22868
22984
  }).meta({ id: "EventMetadata" });
22869
22985
  var Event = external_exports.object({
22870
22986
  id: external_exports.guid(),
@@ -22974,7 +23090,32 @@ var RotateKeyInput = external_exports.object({
22974
23090
  confirmation: external_exports.string()
22975
23091
  });
22976
23092
 
23093
+ // ../../packages/schema/src/zod/finding-delivery.ts
23094
+ var KNOWN_REASONS = SyncFailureReason.options;
23095
+ function knownReason(value) {
23096
+ return value !== null && KNOWN_REASONS.includes(value) ? value : void 0;
23097
+ }
23098
+ function deriveFindingDelivery(row) {
23099
+ if (row.kind === "code_change") return { state: "local_scan" };
23100
+ if (row.syncedAt !== null && row.syncedAt > 0) {
23101
+ return { state: "sent", at: epochMillisToIso(row.syncedAt) };
23102
+ }
23103
+ if (row.syncedAt !== null) {
23104
+ const reason = knownReason(row.syncFailure);
23105
+ return {
23106
+ state: "not_sent",
23107
+ ...row.syncFailedAt === null ? {} : { at: epochMillisToIso(row.syncFailedAt) },
23108
+ ...reason === void 0 ? {} : { reason }
23109
+ };
23110
+ }
23111
+ if (row.outboxOwed === 1 || row.syncClaimedAt !== null) return { state: "queued" };
23112
+ return { state: "never_offered" };
23113
+ }
23114
+
22977
23115
  // ../../packages/schema/src/zod/findings-group-build.ts
23116
+ function lookupOwn(map2, key) {
23117
+ return Object.hasOwn(map2, key) ? map2[key] : void 0;
23118
+ }
22978
23119
  function toApiAction(dbVal) {
22979
23120
  const map2 = {
22980
23121
  log: "monitored",
@@ -22983,7 +23124,7 @@ function toApiAction(dbVal) {
22983
23124
  warn: "warned",
22984
23125
  allow: "allowed"
22985
23126
  };
22986
- return map2[dbVal] ?? "allowed";
23127
+ return lookupOwn(map2, dbVal) ?? "allowed";
22987
23128
  }
22988
23129
  function toApiCategory(dbVal) {
22989
23130
  if (dbVal === "code_context") return "source_code";
@@ -22991,13 +23132,18 @@ function toApiCategory(dbVal) {
22991
23132
  return parsed2.success ? parsed2.data : "custom";
22992
23133
  }
22993
23134
  function toApiProvider(sourceTool) {
22994
- return TOOL_TO_HARNESS[sourceTool] ?? HARNESS.Api;
23135
+ return lookupOwn(TOOL_TO_HARNESS, sourceTool) ?? HARNESS.Api;
22995
23136
  }
22996
- var STATUS_PRECEDENCE = ["open", "handled", "dismissed", "resolved"];
23137
+ var FINDING_STATUS_PRECEDENCE = [
23138
+ "open",
23139
+ "handled",
23140
+ "dismissed",
23141
+ "resolved"
23142
+ ];
22997
23143
  function foldGroupStatus(instanceStatuses) {
22998
23144
  const statuses = new Set(instanceStatuses.filter((s) => s !== void 0));
22999
23145
  if (statuses.size === 0) return void 0;
23000
- for (const candidate of STATUS_PRECEDENCE) {
23146
+ for (const candidate of FINDING_STATUS_PRECEDENCE) {
23001
23147
  if (statuses.has(candidate)) return candidate;
23002
23148
  }
23003
23149
  return void 0;
@@ -23104,11 +23250,16 @@ function applyFindingFilters(types, opts) {
23104
23250
  }
23105
23251
  return filtered;
23106
23252
  }
23107
- var SEVERITY_ORDER = { critical: 0, high: 1, medium: 2, low: 3 };
23108
- var SEVERITY_RANK = SEVERITY_ORDER;
23253
+ function rankByOrder(members2) {
23254
+ return Object.fromEntries(members2.map((member, index) => [member, index]));
23255
+ }
23256
+ var SEVERITY_RANK = rankByOrder(Severity.options);
23257
+ function severityRank(severity) {
23258
+ return lookupOwn(SEVERITY_RANK, severity);
23259
+ }
23109
23260
  function compareFindingGroupOrder(a, b) {
23110
- const rankA = SEVERITY_RANK[a.severity] ?? -1;
23111
- const rankB = SEVERITY_RANK[b.severity] ?? -1;
23261
+ const rankA = severityRank(a.severity) ?? -1;
23262
+ const rankB = severityRank(b.severity) ?? -1;
23112
23263
  const severityDiff = rankA - rankB;
23113
23264
  if (severityDiff !== 0) return severityDiff;
23114
23265
  const recencyDiff = b.latestDetectedAt.localeCompare(a.latestDetectedAt);
@@ -23183,6 +23334,20 @@ function computeFindingFacets(allTypes, opts) {
23183
23334
  }
23184
23335
 
23185
23336
  // ../../packages/schema/src/zod/findings-flat-build.ts
23337
+ function compareCodePoints(a, b) {
23338
+ const aIter = a[Symbol.iterator]();
23339
+ const bIter = b[Symbol.iterator]();
23340
+ for (; ; ) {
23341
+ const aNext = aIter.next();
23342
+ const bNext = bIter.next();
23343
+ if (aNext.done && bNext.done) return 0;
23344
+ if (aNext.done) return -1;
23345
+ if (bNext.done) return 1;
23346
+ const aPoint = aNext.value.codePointAt(0) ?? 0;
23347
+ const bPoint = bNext.value.codePointAt(0) ?? 0;
23348
+ if (aPoint !== bPoint) return aPoint - bPoint;
23349
+ }
23350
+ }
23186
23351
  function rowHaystack(row) {
23187
23352
  return [
23188
23353
  row.ruleId,
@@ -23207,6 +23372,8 @@ function matchesDimension(row, opts, dimension) {
23207
23372
  return !opts.actions?.length || opts.actions.includes(toApiAction(row.actionTaken));
23208
23373
  case "statuses":
23209
23374
  return !opts.statuses?.length || row.status !== void 0 && opts.statuses.includes(row.status);
23375
+ case "deliveries":
23376
+ return !opts.deliveries?.length || row.delivery !== void 0 && opts.deliveries.includes(row.delivery.state);
23210
23377
  case "tools":
23211
23378
  return !opts.tools?.length || row.toolName !== void 0 && opts.tools.includes(row.toolName);
23212
23379
  // An EMPTY value is a real filter here, not an absent one. The location
@@ -23233,6 +23400,7 @@ var DIMENSIONS = [
23233
23400
  "providers",
23234
23401
  "actions",
23235
23402
  "statuses",
23403
+ "deliveries",
23236
23404
  "tools",
23237
23405
  "repo",
23238
23406
  "file",
@@ -23246,10 +23414,19 @@ function matchesInstanceFilters(row, opts, except) {
23246
23414
  return true;
23247
23415
  }
23248
23416
  function toItems(counts) {
23249
- return [...counts.entries()].map(([value, count]) => ({ value, count })).sort((a, b) => b.count - a.count || a.value.localeCompare(b.value));
23417
+ return [...counts.entries()].map(([value, count]) => ({ value, count })).sort(
23418
+ (a, b) => b.count - a.count || a.value.localeCompare(b.value) || // localeCompare reports canonically-equivalent strings (an NFC and an
23419
+ // NFD spelling of the same text) as equal, so a count tie between
23420
+ // them would otherwise be ordered by whichever the Map iteration
23421
+ // produced. compareCodePoints breaks that tie deterministically, which
23422
+ // makes this a TOTAL order — not one that agrees with SQL collation,
23423
+ // which it need not: foldFacetTuples runs this same sort over grouped
23424
+ // tuples, so both paths order facets identically by construction.
23425
+ compareCodePoints(a.value, b.value)
23426
+ );
23250
23427
  }
23251
- function bump(counts, value) {
23252
- counts.set(value, (counts.get(value) ?? 0) + 1);
23428
+ function bump(counts, value, by = 1) {
23429
+ counts.set(value, (counts.get(value) ?? 0) + by);
23253
23430
  }
23254
23431
  function createInstanceFacetAccumulator(opts) {
23255
23432
  const severity = /* @__PURE__ */ new Map();
@@ -23258,6 +23435,7 @@ function createInstanceFacetAccumulator(opts) {
23258
23435
  const action = /* @__PURE__ */ new Map();
23259
23436
  const status = /* @__PURE__ */ new Map();
23260
23437
  const tool = /* @__PURE__ */ new Map();
23438
+ const deployment = /* @__PURE__ */ new Map();
23261
23439
  return {
23262
23440
  add(row) {
23263
23441
  if (matchesInstanceFilters(row, opts, "severity")) bump(severity, row.severity);
@@ -23272,6 +23450,9 @@ function createInstanceFacetAccumulator(opts) {
23272
23450
  if (row.toolName !== void 0 && matchesInstanceFilters(row, opts, "tools")) {
23273
23451
  bump(tool, row.toolName);
23274
23452
  }
23453
+ if (row.delivery !== void 0 && matchesInstanceFilters(row, opts, "deliveries")) {
23454
+ bump(deployment, row.delivery.state);
23455
+ }
23275
23456
  },
23276
23457
  facets: () => ({
23277
23458
  severity: toItems(severity),
@@ -23279,7 +23460,8 @@ function createInstanceFacetAccumulator(opts) {
23279
23460
  provider: toItems(provider),
23280
23461
  action: toItems(action),
23281
23462
  status: toItems(status),
23282
- tool: toItems(tool)
23463
+ tool: toItems(tool),
23464
+ deployment: toItems(deployment)
23283
23465
  })
23284
23466
  };
23285
23467
  }
@@ -23293,6 +23475,7 @@ function toInstanceDetail(row) {
23293
23475
  ...row.toolName === void 0 ? {} : { toolName: row.toolName },
23294
23476
  eventId: row.eventId,
23295
23477
  ...row.sessionId === void 0 ? {} : { sessionId: row.sessionId },
23478
+ ...row.delivery === void 0 ? {} : { delivery: row.delivery },
23296
23479
  ...row.user === void 0 ? {} : { user: row.user },
23297
23480
  action: toApiAction(row.actionTaken),
23298
23481
  detectedAt: row.occurredAt,
@@ -23307,12 +23490,6 @@ function toInstanceDetail(row) {
23307
23490
  policy: { id: `category:${category}`, name: category }
23308
23491
  };
23309
23492
  }
23310
- var SEVERITY_ORDER2 = {
23311
- critical: 0,
23312
- high: 1,
23313
- medium: 2,
23314
- low: 3
23315
- };
23316
23493
  function newLocationAccumulator() {
23317
23494
  return {
23318
23495
  instanceCount: 0,
@@ -23327,7 +23504,7 @@ function newLocationAccumulator() {
23327
23504
  }
23328
23505
  function addToLocation(acc, row) {
23329
23506
  acc.instanceCount += 1;
23330
- const rank = SEVERITY_ORDER2[row.severity] ?? Number.MAX_SAFE_INTEGER - 1;
23507
+ const rank = severityRank(row.severity) ?? Number.MAX_SAFE_INTEGER - 1;
23331
23508
  if (rank < acc.maxSeverityRank) {
23332
23509
  acc.maxSeverityRank = rank;
23333
23510
  acc.maxSeverity = row.severity;
@@ -23337,15 +23514,15 @@ function addToLocation(acc, row) {
23337
23514
  acc.ruleIds.add(row.ruleId);
23338
23515
  }
23339
23516
  function compareLocationOrder(a, b) {
23340
- const rankA = SEVERITY_ORDER2[a.maxSeverity] ?? -1;
23341
- const rankB = SEVERITY_ORDER2[b.maxSeverity] ?? -1;
23517
+ const rankA = severityRank(a.maxSeverity) ?? -1;
23518
+ const rankB = severityRank(b.maxSeverity) ?? -1;
23342
23519
  if (rankA !== rankB) return rankA - rankB;
23343
23520
  if (a.latestDetectedAt !== b.latestDetectedAt) {
23344
23521
  return a.latestDetectedAt < b.latestDetectedAt ? 1 : -1;
23345
23522
  }
23346
- if (a.repo !== b.repo) return a.repo < b.repo ? -1 : 1;
23347
- if (a.file !== b.file) return a.file < b.file ? -1 : 1;
23348
- return 0;
23523
+ const repoDiff = compareCodePoints(a.repo, b.repo);
23524
+ if (repoDiff !== 0) return repoDiff;
23525
+ return compareCodePoints(a.file, b.file);
23349
23526
  }
23350
23527
  function encodeLocationId(repo, file2) {
23351
23528
  return `${encodePart(repo)}/${encodePart(file2)}`;
@@ -23420,6 +23597,11 @@ var Policy = external_exports.object({
23420
23597
  // test `prohibitedModels` passes and `reversibleRuleIds` fails.
23421
23598
  provenance: PolicyProvenance.optional()
23422
23599
  }).meta({ id: "Policy" });
23600
+ var KNOWN_BUILTIN_IDS = ["monitor", "warn", "redact", "vault", "block"];
23601
+ var BuiltinPolicyId = external_exports.enum(KNOWN_BUILTIN_IDS).meta({ id: "BuiltinPolicyId" });
23602
+ var RedactFallback = BuiltinPolicyId.extract(["monitor", "warn", "block"]).meta({
23603
+ id: "RedactFallback"
23604
+ });
23423
23605
  var PolicyBundle = external_exports.object({
23424
23606
  version: external_exports.string(),
23425
23607
  policies: external_exports.array(Policy),
@@ -23467,6 +23649,16 @@ var PolicyBundle = external_exports.object({
23467
23649
  // control plane), so no name resolution stands between the decision and the
23468
23650
  // comparison.
23469
23651
  prohibitedModels: external_exports.array(external_exports.string()).optional(),
23652
+ // What a resolved `redact` becomes on a field the host cannot rewrite, as
23653
+ // the ORGANIZATION would have it. Merged raise-only against the device's own
23654
+ // `WorkspaceSettings.redactFallback` (see strongerRedactFallback below), so
23655
+ // a control plane can tighten a machine and never loosen one — the same
23656
+ // direction `mergeRaiseOnly` enforces for policies.
23657
+ //
23658
+ // Optional so an older backend, and an older on-disk cache, still parses;
23659
+ // absent leaves the device's own setting in force, which is the behaviour
23660
+ // that predates the field and the safe direction to default.
23661
+ redactFallback: RedactFallback.optional(),
23470
23662
  customKeywords: external_exports.array(external_exports.string()),
23471
23663
  fetchedAt: external_exports.iso.datetime()
23472
23664
  }).meta({ id: "PolicyBundle" });
@@ -23496,11 +23688,6 @@ function severityFloorPolicy(category) {
23496
23688
  const peak = CATEGORY_PEAK_SEVERITY[category];
23497
23689
  return peak === "critical" || peak === "high" ? "warn" : "monitor";
23498
23690
  }
23499
- var KNOWN_BUILTIN_IDS = ["monitor", "warn", "redact", "vault", "block"];
23500
- var BuiltinPolicyId = external_exports.enum(KNOWN_BUILTIN_IDS).meta({ id: "BuiltinPolicyId" });
23501
- var RedactFallback = BuiltinPolicyId.extract(["monitor", "warn", "block"]).meta({
23502
- id: "RedactFallback"
23503
- });
23504
23691
  var BUILTIN_ORDER = KNOWN_BUILTIN_IDS;
23505
23692
  var BUILTIN_POLICY_SPECS = {
23506
23693
  monitor: {
@@ -23798,7 +23985,7 @@ var VaultConsent = external_exports.object({
23798
23985
  });
23799
23986
 
23800
23987
  // ../../packages/schema/src/zod/local.ts
23801
- var WORKSPACE_SETTINGS_SPEC_VERSION = 7;
23988
+ var WORKSPACE_SETTINGS_SPEC_VERSION = 8;
23802
23989
  var MODEL_JUDGE_PAYLOAD_VERSION = 1;
23803
23990
  var RunMode = external_exports.enum(["standalone", "attached"]);
23804
23991
  var ControlPlaneConnection = external_exports.object({
@@ -23818,6 +24005,15 @@ var HistorySyncConsent = external_exports.object({
23818
24005
  payloadVersion: external_exports.number().int().positive(),
23819
24006
  endpoint: external_exports.string()
23820
24007
  });
24008
+ var BODY_RETENTION_DEFAULT_DAYS = 30;
24009
+ var BodyRetention = external_exports.object({
24010
+ enabled: external_exports.boolean().default(false),
24011
+ // Never 0, and the ceiling is a fat-finger guard rather than a policy
24012
+ // limit — `enabled` is the real gate. A low value cannot reach a row the
24013
+ // sync ledger still owes: the sweep's age filter only ever NARROWS a
24014
+ // candidate set that is already bounded by "delivered, or never owed".
24015
+ retainDays: external_exports.number().int().min(1).max(3650).default(BODY_RETENTION_DEFAULT_DAYS)
24016
+ }).meta({ id: "BodyRetention" });
23821
24017
  var WorkspaceSettings = external_exports.object({
23822
24018
  specVersion: external_exports.number().int().positive().default(WORKSPACE_SETTINGS_SPEC_VERSION),
23823
24019
  runMode: RunMode.default("standalone"),
@@ -23866,7 +24062,13 @@ var WorkspaceSettings = external_exports.object({
23866
24062
  // carry prompt/reply/tool-output text in `content`; the key name predates
23867
24063
  // both widenings. Absent until granted, and a grant for a different endpoint
23868
24064
  // or an older payload no longer counts.
23869
- historySyncConsent: HistorySyncConsent.optional()
24065
+ historySyncConsent: HistorySyncConsent.optional(),
24066
+ // Local body expiry (see BodyRetention). Off until switched on; expiring a
24067
+ // body never removes the row or its findings.
24068
+ bodyRetention: BodyRetention.default({
24069
+ enabled: false,
24070
+ retainDays: BODY_RETENTION_DEFAULT_DAYS
24071
+ })
23870
24072
  });
23871
24073
  function defaultWorkspaceSettings() {
23872
24074
  return WorkspaceSettings.parse({});
@@ -23961,12 +24163,15 @@ function toCaptureAttributes(event) {
23961
24163
  ...metadata?.traceId !== void 0 ? { trace_id: metadata.traceId } : {},
23962
24164
  ...metadata?.exceptionIds !== void 0 ? { exception_ids: metadata.exceptionIds } : {},
23963
24165
  ...metadata?.inspectionMs !== void 0 ? { inspection_ms: metadata.inspectionMs } : {},
24166
+ ...metadata?.redactDegradedTo !== void 0 ? { redact_degraded_to: metadata.redactDegradedTo } : {},
23964
24167
  // `model`/`turnIndex` have no dedicated CaptureAttributes field (no writer
23965
24168
  // has ever populated either), but every legacy metadata key still rides
23966
24169
  // the bag rather than being silently dropped — CaptureAttributes'
23967
24170
  // `.catchall(z.unknown())` carries the long tail.
23968
24171
  ...metadata?.model !== void 0 ? { model: metadata.model } : {},
23969
- ...metadata?.turnIndex !== void 0 ? { turn_index: metadata.turnIndex } : {}
24172
+ ...metadata?.turnIndex !== void 0 ? { turn_index: metadata.turnIndex } : {},
24173
+ ...metadata?.messageId !== void 0 ? { message_id: metadata.messageId } : {},
24174
+ ...metadata?.conversationId !== void 0 ? { conversation_id: metadata.conversationId } : {}
23970
24175
  };
23971
24176
  }
23972
24177
  function captureDefinitionVersion(finding) {
@@ -23994,13 +24199,22 @@ var ManagedSettingKey = external_exports.enum([
23994
24199
  "vaultInlineReveal",
23995
24200
  "modelJudgeConsent",
23996
24201
  "dataSharesInPlace",
23997
- "redactFallback"
24202
+ "redactFallback",
24203
+ // Pins the toggle and the day count together — see BodyRetention on why the
24204
+ // two are one unit. An administrator mandating a window wants the count
24205
+ // enforced with it, not one a user can widen while the toggle stays on.
24206
+ "bodyRetention"
23998
24207
  ]).meta({ id: "ManagedSettingKey" });
23999
24208
  function isManagedSettingKey(value) {
24000
24209
  return ManagedSettingKey.safeParse(value).success;
24001
24210
  }
24002
24211
  var ManagedSettingsValues = external_exports.object({
24003
24212
  runMode: external_exports.enum(["standalone", "attached"]).optional(),
24213
+ // `controlPlane` and `bodyRetention` are the two nested values, and both are
24214
+ // plain, non-strict objects: a key under either that this build does not know
24215
+ // is stripped and nothing reports it. The unknown-value split in
24216
+ // ManagedSettings below classifies top-level names only, so it stops at
24217
+ // these boundaries.
24004
24218
  controlPlane: external_exports.object({
24005
24219
  endpoint: external_exports.string().min(1),
24006
24220
  label: external_exports.string().min(1).optional()
@@ -24011,7 +24225,8 @@ var ManagedSettingsValues = external_exports.object({
24011
24225
  vaultInlineReveal: external_exports.enum(["masked", "full", "off"]).optional(),
24012
24226
  modelJudgeConsent: external_exports.boolean().optional(),
24013
24227
  dataSharesInPlace: external_exports.boolean().optional(),
24014
- redactFallback: RedactFallback.optional()
24228
+ redactFallback: RedactFallback.optional(),
24229
+ bodyRetention: BodyRetention.optional()
24015
24230
  }).meta({ id: "ManagedSettingsValues" });
24016
24231
  var ManagedSettings = external_exports.object({
24017
24232
  specVersion: external_exports.number().int().positive().default(MANAGED_SETTINGS_SPEC_VERSION),
@@ -24019,7 +24234,21 @@ var ManagedSettings = external_exports.object({
24019
24234
  // decision from a bug. Absent renders as a generic "your organization".
24020
24235
  organization: external_exports.string().min(1).optional(),
24021
24236
  // What the administrator pinned.
24022
- values: ManagedSettingsValues.default({}),
24237
+ //
24238
+ // Parsed as a RECORD rather than as the nested schema, and split below for
24239
+ // the same reason `lockedFields` is parsed as names: a plain `z.object`
24240
+ // drops an unrecognised key and succeeds, so a pin this build does not know
24241
+ // vanished and nothing anywhere said so. A pin with no lock is a supported
24242
+ // shape — it is a DEFAULT the user may still change — so that silence hit
24243
+ // exactly the file an administrator is most likely to write while a fleet
24244
+ // is mid-upgrade.
24245
+ //
24246
+ // Splitting here rather than calling `.strict()`: strict would REFUSE the
24247
+ // file, which is the outcome the lock half already rejected — an older
24248
+ // build then runs entirely unmanaged, every pin and lock gone. A bad KNOWN
24249
+ // value still fails, because the nested schema is re-run over the known
24250
+ // subset and its issues are re-raised on this parse.
24251
+ values: external_exports.record(external_exports.string(), external_exports.unknown()).default({}),
24023
24252
  // Which of those the user may not change. A key here with no matching value
24024
24253
  // freezes whatever the user last chose; a value with no lock is a DEFAULT
24025
24254
  // the user may still override. The two are separable on purpose.
@@ -24032,17 +24261,31 @@ var ManagedSettings = external_exports.object({
24032
24261
  // the fleets most likely to carry a version skew. A name outside the enum
24033
24262
  // is still never HONOURED: the lockable set stays explicit above.
24034
24263
  lockedFields: external_exports.array(external_exports.string()).default([])
24035
- }).transform(({ lockedFields, ...rest }) => {
24264
+ }).transform(({ lockedFields, values, ...rest }, ctx) => {
24036
24265
  const known = [];
24037
24266
  const unknown2 = [];
24038
24267
  for (const name of lockedFields) {
24039
24268
  if (isManagedSettingKey(name)) known.push(name);
24040
24269
  else unknown2.push(name);
24041
24270
  }
24271
+ const knownValues = /* @__PURE__ */ Object.create(null);
24272
+ const unknownValues = [];
24273
+ for (const [name, value] of Object.entries(values)) {
24274
+ if (Object.hasOwn(ManagedSettingsValues.shape, name)) knownValues[name] = value;
24275
+ else unknownValues.push(name);
24276
+ }
24277
+ const pinned = ManagedSettingsValues.safeParse(knownValues);
24278
+ if (!pinned.success) {
24279
+ for (const issue2 of pinned.error.issues)
24280
+ ctx.addIssue({ ...issue2, path: ["values", ...issue2.path] });
24281
+ return external_exports.NEVER;
24282
+ }
24042
24283
  return {
24043
24284
  ...rest,
24285
+ values: pinned.data,
24044
24286
  lockedFields: known,
24045
- ...unknown2.length > 0 ? { unknownLockedFields: unknown2 } : {}
24287
+ ...unknown2.length > 0 ? { unknownLockedFields: unknown2 } : {},
24288
+ ...unknownValues.length > 0 ? { unknownValueFields: unknownValues } : {}
24046
24289
  };
24047
24290
  }).meta({ id: "ManagedSettings" });
24048
24291
 
@@ -24306,7 +24549,23 @@ var SaveSettingsInput = external_exports.object({
24306
24549
  modelJudgeConsent: ModelJudgeConsentChoice,
24307
24550
  historySyncConsent: HistorySyncConsentChoice,
24308
24551
  vaultConsent: external_exports.string(),
24309
- vaultInlineReveal: external_exports.string()
24552
+ vaultInlineReveal: external_exports.string(),
24553
+ // Widened to `string` like its neighbours rather than typed as
24554
+ // `RedactFallback`, on this module's own layering rule: shape here, VALUE at
24555
+ // the call site, so the domain check receives the type it was written for.
24556
+ //
24557
+ // NOT because a narrower schema would reject differently. `parseActionInput`
24558
+ // is a `safeParse` wrapper and throws for no field schema, so either spelling
24559
+ // reaches a recoverable `{ ok: false }` and there is no rejected promise to
24560
+ // trade against. The real cost runs the other way and is the part worth
24561
+ // knowing: a value this schema admits and the domain enum then rejects lands
24562
+ // on the action's shared refusal, which names NO field, where a shape
24563
+ // rejection reaches `malformedInput` and names the schema key.
24564
+ redactFallback: external_exports.string(),
24565
+ // Shape only, the way the enum fields above are strings only: the RANGE is
24566
+ // `BodyRetention`'s and the action checks it there, so there is one place
24567
+ // that decides what a legal horizon is rather than two that can drift.
24568
+ bodyRetention: external_exports.object({ enabled: external_exports.boolean(), retainDays: external_exports.number() })
24310
24569
  });
24311
24570
  var AttachInput = external_exports.object({
24312
24571
  endpoint: external_exports.string(),
@@ -24478,6 +24737,52 @@ function reviewSeverityRank(reasons) {
24478
24737
  return Math.min(...reasons.map((r) => REVIEW_SEVERITY_RANK[r]));
24479
24738
  }
24480
24739
 
24740
+ // ../../packages/schema/src/zod/web-capture.ts
24741
+ var WebUsageSource = external_exports.enum(["site", "estimated", "none"]);
24742
+ var WebUsage = external_exports.object({
24743
+ inputTokens: external_exports.number().int().nonnegative().optional(),
24744
+ outputTokens: external_exports.number().int().nonnegative().optional(),
24745
+ cacheReadInputTokens: external_exports.number().int().nonnegative().optional(),
24746
+ cacheCreationInputTokens: external_exports.number().int().nonnegative().optional()
24747
+ });
24748
+ var WebToolCall = external_exports.object({
24749
+ toolUseId: external_exports.string().min(1),
24750
+ toolName: external_exports.string().min(1),
24751
+ target: external_exports.string().optional(),
24752
+ isError: external_exports.boolean().optional(),
24753
+ inputSize: external_exports.number().int().nonnegative().optional(),
24754
+ outputSize: external_exports.number().int().nonnegative().optional()
24755
+ });
24756
+ var WebExchange = external_exports.object({
24757
+ messageId: external_exports.string().min(1),
24758
+ startedAt: external_exports.iso.datetime(),
24759
+ model: external_exports.string().optional(),
24760
+ usage: WebUsage.optional(),
24761
+ usageSource: WebUsageSource,
24762
+ stopReason: external_exports.string().optional(),
24763
+ conversationId: external_exports.string().optional(),
24764
+ turnIndex: external_exports.number().int().nonnegative().optional(),
24765
+ toolCalls: external_exports.array(WebToolCall).default([]),
24766
+ // Absent when the adapter recovered no text. Capped by the caller at
24767
+ // RESPONSE_TEXT_MAX_BYTES; `truncated` records that the cap was reached, so a
24768
+ // short capture is never mistaken for a short reply.
24769
+ responseText: external_exports.string().optional(),
24770
+ truncated: external_exports.boolean().default(false)
24771
+ });
24772
+ var RESPONSE_TEXT_MAX_BYTES = 2 * 1024 * 1024;
24773
+ var WebCaptureStatus = external_exports.object({
24774
+ patched: external_exports.boolean(),
24775
+ live: external_exports.boolean(),
24776
+ blind: external_exports.boolean(),
24777
+ sendsSeenDom: external_exports.number().int().nonnegative(),
24778
+ exchangesSeenNet: external_exports.number().int().nonnegative(),
24779
+ parseFailures: external_exports.number().int().nonnegative(),
24780
+ unparsedBodies: external_exports.number().int().nonnegative(),
24781
+ // The adapter-declared JSON key paths that were absent from a real payload —
24782
+ // the earliest signal that a site's contract moved.
24783
+ shapeMisses: external_exports.array(external_exports.string()).default([])
24784
+ });
24785
+
24481
24786
  // ../../packages/persistence/src/paths.ts
24482
24787
  import {
24483
24788
  chmodSync,
@@ -24808,6 +25113,22 @@ function discardStore(file2, backup) {
24808
25113
  }
24809
25114
  }
24810
25115
 
25116
+ // ../../packages/persistence/src/internal/sql-functions.ts
25117
+ var utf8 = new TextDecoder();
25118
+ function akaLower(value) {
25119
+ if (value === null) return null;
25120
+ if (typeof value === "string") return value.toLowerCase();
25121
+ if (typeof value === "number" || typeof value === "bigint") return String(value).toLowerCase();
25122
+ return utf8.decode(value).toLowerCase();
25123
+ }
25124
+ function registerSqlFunctions(db) {
25125
+ db.function(
25126
+ "aka_lower",
25127
+ { deterministic: true, directOnly: true, useBigIntArguments: true },
25128
+ akaLower
25129
+ );
25130
+ }
25131
+
24811
25132
  // ../../packages/persistence/src/internal/sql-text.ts
24812
25133
  function escapeLikePattern(s) {
24813
25134
  return s.replace(/\\/g, "\\\\").replace(/%/g, "\\%").replace(/_/g, "\\_");
@@ -24892,6 +25213,11 @@ function schemaObjectExists(db, kind, name) {
24892
25213
  function indexExists(db, name) {
24893
25214
  return schemaObjectExists(db, "index", name);
24894
25215
  }
25216
+ function indexColumns(db, name) {
25217
+ if (!indexExists(db, name)) return [];
25218
+ const columns = db.prepare(`PRAGMA index_info(${name})`).all();
25219
+ return columns.map((c) => c.name).filter((c) => c !== null);
25220
+ }
24895
25221
  function columnNames(db, table2, opts) {
24896
25222
  const pragma = opts?.includeGenerated ? "table_xinfo" : "table_info";
24897
25223
  const columns = db.prepare(`PRAGMA ${pragma}(${table2})`).all();
@@ -24953,178 +25279,820 @@ function mapRowsTolerant(rows, map2) {
24953
25279
  return out;
24954
25280
  }
24955
25281
 
24956
- // ../../packages/persistence/src/migrations.ts
24957
- function describeObject(object2) {
24958
- return object2.kind === "column" ? `column ${object2.table}.${object2.name}` : `table ${object2.name}`;
24959
- }
24960
- function splitStatements(sql) {
24961
- return sql.split(/-->\s*statement-breakpoint/).map((s) => s.trim()).filter((s) => s.length > 0);
24962
- }
24963
- function createdIndexName(statement) {
24964
- const body = statement.replace(/^(?:\s*--[^\n]*\n?)+/, "").trimStart();
24965
- return /^CREATE (?:UNIQUE )?INDEX (?:IF NOT EXISTS )?`([^`]+)`/.exec(body)?.[1];
25282
+ // ../../packages/persistence/src/internal/outbox-lane.ts
25283
+ var OUTBOX_CAPTURE_EVENT_TYPES = ["prompt", "response", "tool_use"];
25284
+ var OUTBOX_CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25285
+
25286
+ // ../../packages/persistence/src/sync-failure.ts
25287
+ var SYNC_FAILURE_REASONS = SyncFailureReason.options;
25288
+ function syncFailureRejectCondition(column = "sync_failure") {
25289
+ const members2 = SYNC_FAILURE_REASONS.map((r) => `'${r}'`).join(", ");
25290
+ return `NEW.${column} IS NOT NULL AND NEW.${column} NOT IN (${members2})`;
24966
25291
  }
24967
- var LEGACY_DROP_MIGRATION_TAG = "0014_drop_legacy_events_findings";
24968
- function applyMigrations(db, file2) {
24969
- const legacyCount = db.prepare("PRAGMA user_version").get().user_version;
24970
- db.exec(
24971
- "CREATE TABLE IF NOT EXISTS migration_ledger (tag TEXT PRIMARY KEY, applied_at INTEGER NOT NULL)"
24972
- );
24973
- const applied = new Set(
24974
- db.prepare("SELECT tag FROM migration_ledger").all().map((r) => r.tag)
24975
- );
24976
- const preLedgerStore = applied.size === 0 && legacyCount > 0;
24977
- const record2 = db.prepare(
24978
- "INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)"
24979
- );
24980
- for (const [index, migration] of SQLITE_MIGRATIONS.entries()) {
24981
- if (applied.has(migration.tag)) continue;
24982
- if (migration.tag === LEGACY_DROP_MIGRATION_TAG) continue;
24983
- const evidence = evidenceObjects(migration.sql);
24984
- const present = evidence.filter((o) => evidenceExists(db, o));
24985
- if (present.length > 0 && present.length < evidence.length) {
24986
- const missing = evidence.filter((o) => !present.includes(o));
24987
- const message = `sqlite migration ${migration.tag} has no ledger row, but the store already has ${present.map(describeObject).join(", ")} while missing ${missing.map(describeObject).join(", ")} \u2014 the schema diverged from the migration history; refusing to replay or skip.`;
24988
- akaWarn(message);
24989
- throw new Error(`[aka] ${message}`);
24990
- }
24991
- const alreadyApplied = evidence.length > 0 ? present.length === evidence.length : preLedgerStore && index < legacyCount;
24992
- const wantsFkOff = /PRAGMA foreign_keys\s*=\s*OFF/i.test(migration.sql);
24993
- const statements = splitStatements(migration.sql);
24994
- if (wantsFkOff) db.exec("PRAGMA foreign_keys = OFF");
24995
- try {
24996
- withTransaction(
24997
- db,
24998
- () => {
24999
- for (const statement of statements) {
25000
- const indexName = createdIndexName(statement);
25001
- if (indexName === void 0) {
25002
- if (alreadyApplied) continue;
25003
- } else if (indexExists(db, indexName)) {
25004
- continue;
25005
- }
25006
- db.exec(statement);
25007
- }
25008
- if (wantsFkOff && !alreadyApplied) {
25009
- const violations = db.prepare("PRAGMA foreign_key_check").all();
25010
- if (violations.length > 0) {
25011
- throw new Error(
25012
- `[aka] sqlite migration ${migration.tag} left ${String(violations.length)} foreign-key violation(s); rolling back.`
25013
- );
25014
- }
25015
- }
25016
- record2.run(migration.tag, Date.now());
25017
- },
25018
- "IMMEDIATE"
25019
- );
25020
- } finally {
25021
- if (wantsFkOff) db.exec("PRAGMA foreign_keys = ON");
25022
- }
25292
+
25293
+ // ../../packages/persistence/src/repositories/history-sync.ts
25294
+ var STRUCTURAL_EVENT_TYPES = ["session", "llm_call", "tool_call"];
25295
+ var TYPE_LIST = STRUCTURAL_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25296
+ var CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_TYPE_LIST;
25297
+ var COUNTED_EVENT_TYPES = [
25298
+ ...STRUCTURAL_EVENT_TYPES,
25299
+ ...OUTBOX_CAPTURE_EVENT_TYPES
25300
+ ];
25301
+ var COUNTED_TYPE_LIST = COUNTED_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25302
+ var PARTITION_BUCKETS = `
25303
+ SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NULL THEN 1 ELSE 0 END) AS queued,
25304
+ SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NOT NULL THEN 1 ELSE 0 END) AS inProgress,
25305
+ SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS synced,
25306
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25307
+ AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
25308
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25309
+ AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached,
25310
+ -- Spelled as what it INCLUDES rather than what it excludes, so a reason
25311
+ -- added later lands in no bucket and fails the sum assertion, instead
25312
+ -- of silently joining this one.
25313
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25314
+ AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
25315
+ THEN 1 ELSE 0 END) AS failed,
25316
+ COUNT(*) AS total`;
25317
+ var COUNTED_SCOPE = `
25318
+ WHERE event_type IN (${COUNTED_TYPE_LIST})
25319
+ AND (
25320
+ event_type IN (${TYPE_LIST})
25321
+ OR synced_at IS NOT NULL
25322
+ OR outbox_owed = 1
25323
+ )`;
25324
+ var SKIPPED = -1;
25325
+ var ROW_COLUMNS = `id,
25326
+ parent_id AS parentId,
25327
+ root_session_id AS rootSessionId,
25328
+ event_type AS eventType,
25329
+ host_id AS hostId,
25330
+ harness_id AS harnessId,
25331
+ source_project_id AS sourceProjectId,
25332
+ started_at AS startedAt,
25333
+ ended_at AS endedAt,
25334
+ severity,
25335
+ priority,
25336
+ content,
25337
+ content_hash AS contentHash,
25338
+ attributes`;
25339
+ var SqliteHistorySyncRepository = class {
25340
+ constructor(db) {
25341
+ this.db = db;
25342
+ this.ensureRowStmt = db.prepare(`INSERT OR IGNORE INTO history_sync (id) VALUES (1)`);
25343
+ this.sessionsStmt = db.prepare(
25344
+ `SELECT COALESCE(root_session_id, id) AS sessionId, MIN(started_at) AS earliest
25345
+ FROM audit_events
25346
+ WHERE synced_at IS NULL
25347
+ AND event_type IN (${TYPE_LIST})
25348
+ AND started_at < :before
25349
+ GROUP BY sessionId
25350
+ ORDER BY earliest
25351
+ LIMIT :limit`
25352
+ );
25353
+ this.rowsStmt = db.prepare(
25354
+ `SELECT ${ROW_COLUMNS}
25355
+ FROM audit_events
25356
+ WHERE synced_at IS NULL
25357
+ AND event_type IN (${TYPE_LIST})
25358
+ AND started_at < :before
25359
+ AND COALESCE(root_session_id, id) = :sessionId
25360
+ ORDER BY (event_type = 'session') DESC, started_at
25361
+ LIMIT :limit`
25362
+ );
25363
+ this.captureRowsStmt = db.prepare(
25364
+ `SELECT ${ROW_COLUMNS}
25365
+ FROM audit_events
25366
+ WHERE synced_at IS NULL
25367
+ AND sync_claimed_at IS NULL
25368
+ AND outbox_owed = 1
25369
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25370
+ AND started_at < :before
25371
+ ORDER BY started_at
25372
+ LIMIT :limit`
25373
+ );
25374
+ this.markOwedStmt = db.prepare(
25375
+ `UPDATE audit_events SET outbox_owed = 1 WHERE id = :id AND synced_at IS NULL`
25376
+ );
25377
+ this.markCaptureBacklogOwedStmt = db.prepare(
25378
+ `UPDATE audit_events SET outbox_owed = 1
25379
+ WHERE synced_at IS NULL
25380
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25381
+ AND started_at < :before`
25382
+ );
25383
+ this.stampStmt = db.prepare(
25384
+ `UPDATE audit_events
25385
+ SET synced_at = :at,
25386
+ sync_claimed_at = NULL,
25387
+ sync_failed_at = :failedAt,
25388
+ sync_failure = :failure
25389
+ WHERE id = :id`
25390
+ );
25391
+ this.claimRowStmt = db.prepare(
25392
+ `UPDATE audit_events SET sync_claimed_at = :at WHERE id = :id AND synced_at IS NULL`
25393
+ );
25394
+ this.releaseRowStmt = db.prepare(
25395
+ `UPDATE audit_events SET sync_claimed_at = NULL WHERE id = :id`
25396
+ );
25397
+ this.releaseStaleClaimsStmt = db.prepare(
25398
+ `UPDATE audit_events SET sync_claimed_at = NULL
25399
+ WHERE sync_claimed_at IS NOT NULL AND sync_claimed_at < :staleBefore`
25400
+ );
25401
+ this.partitionStmt = db.prepare(`SELECT${PARTITION_BUCKETS}
25402
+ FROM audit_events${COUNTED_SCOPE}`);
25403
+ this.partitionByKindStmt = db.prepare(
25404
+ `SELECT event_type AS kind,${PARTITION_BUCKETS}
25405
+ FROM audit_events INDEXED BY idx_audit_events_sync${COUNTED_SCOPE}
25406
+ GROUP BY event_type`
25407
+ );
25408
+ this.countsStmt = db.prepare(
25409
+ `SELECT
25410
+ SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
25411
+ SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
25412
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25413
+ AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
25414
+ THEN 1 ELSE 0 END) AS skipped,
25415
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25416
+ AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
25417
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25418
+ AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached
25419
+ FROM audit_events
25420
+ WHERE event_type IN (${TYPE_LIST})`
25421
+ );
25422
+ this.captureSkipCountStmt = db.prepare(
25423
+ // EVERY sentinel capture, whatever the reason — deliberately NOT split the
25424
+ // way the structural totals are. The split exists because a refusal is
25425
+ // terminal only against the deployment that gave it, and the structural
25426
+ // re-arm frees it on a change of deployment. The capture lane has no such
25427
+ // escape: re-arming a capture would offer one deployment's undelivered
25428
+ // prompts, with their text, to a deployment that never saw them, which is
25429
+ // exactly what disownCapturesStmt exists to prevent. So on this lane both
25430
+ // reasons mean the same thing — this row will not be sent — and splitting
25431
+ // them would put refused captures in a bucket nothing reads and nothing
25432
+ // frees.
25433
+ `SELECT COUNT(*) AS skipped
25434
+ FROM audit_events
25435
+ WHERE synced_at = ${String(SKIPPED)}
25436
+ AND event_type IN (${CAPTURE_TYPE_LIST})`
25437
+ );
25438
+ this.fingerprintStmt = db.prepare(
25439
+ `SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
25440
+ FROM history_sync WHERE id = 1`
25441
+ );
25442
+ this.setFingerprintStmt = db.prepare(
25443
+ `UPDATE history_sync
25444
+ SET endpoint_fingerprint = :fingerprint, backlog_before = :backlogBefore
25445
+ WHERE id = 1`
25446
+ );
25447
+ this.disownCapturesStmt = db.prepare(
25448
+ `UPDATE audit_events SET outbox_owed = NULL
25449
+ WHERE outbox_owed IS NOT NULL
25450
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25451
+ AND started_at < :attachedAt`
25452
+ );
25453
+ this.rearmStmt = db.prepare(
25454
+ `UPDATE audit_events
25455
+ SET synced_at = NULL, sync_failed_at = NULL, sync_failure = NULL
25456
+ WHERE (synced_at > 0
25457
+ OR sync_failure IN ('deployment_refused', 'detached_undelivered'))
25458
+ AND event_type IN (${TYPE_LIST})`
25459
+ );
25460
+ this.claimStmt = db.prepare(
25461
+ `UPDATE history_sync
25462
+ SET owner_pid = :pid, owner_host = :host, acquired_at = :now, heartbeat_at = :now
25463
+ WHERE id = 1
25464
+ AND (owner_pid IS NULL
25465
+ OR heartbeat_at IS NULL
25466
+ OR heartbeat_at < :staleBefore
25467
+ OR heartbeat_at > :now)`
25468
+ );
25469
+ this.heartbeatStmt = db.prepare(
25470
+ `UPDATE history_sync SET heartbeat_at = :now WHERE id = 1 AND owner_pid = :pid`
25471
+ );
25472
+ this.releaseStmt = db.prepare(
25473
+ `UPDATE history_sync
25474
+ SET owner_pid = NULL, owner_host = NULL, acquired_at = NULL, heartbeat_at = NULL
25475
+ WHERE id = 1 AND owner_pid = :pid`
25476
+ );
25477
+ this.closeWindowStmt = db.prepare(
25478
+ `UPDATE audit_events
25479
+ SET synced_at = ${String(SKIPPED)},
25480
+ sync_failed_at = :at,
25481
+ sync_failure = 'detached_undelivered'
25482
+ WHERE synced_at IS NULL
25483
+ AND event_type IN (${TYPE_LIST})
25484
+ AND started_at >= :attachedAt`
25485
+ );
25486
+ this.releaseBoundaryStmt = db.prepare(
25487
+ `UPDATE history_sync SET backlog_before = NULL WHERE id = 1`
25488
+ );
25489
+ this.freezeBoundaryStmt = db.prepare(
25490
+ `UPDATE history_sync SET backlog_before = :backlogBefore WHERE id = 1`
25491
+ );
25492
+ this.leaseStmt = db.prepare(
25493
+ `SELECT owner_pid AS ownerPid, owner_host AS ownerHost,
25494
+ acquired_at AS acquiredAt, heartbeat_at AS heartbeatAt
25495
+ FROM history_sync WHERE id = 1`
25496
+ );
25497
+ this.inspectionsStmt = db.prepare(
25498
+ `SELECT d.rule_id AS ruleId,
25499
+ d.name AS ruleName,
25500
+ d.version AS ruleVersion,
25501
+ d.category AS category,
25502
+ d.severity AS severity,
25503
+ f.span_start AS spanStart,
25504
+ f.span_end AS spanEnd,
25505
+ f.masked_match AS maskedMatch,
25506
+ f.action_taken AS actionTaken,
25507
+ f.confidence AS confidence
25508
+ FROM inspection_findings f
25509
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
25510
+ WHERE f.audit_event_id = :auditEventId
25511
+ ORDER BY f.span_start, f.id`
25512
+ );
25023
25513
  }
25024
- if (legacyCount < SQLITE_MIGRATIONS.length) {
25025
- db.exec(`PRAGMA user_version = ${String(SQLITE_MIGRATIONS.length)}`);
25514
+ db;
25515
+ ensureRowStmt;
25516
+ sessionsStmt;
25517
+ rowsStmt;
25518
+ stampStmt;
25519
+ countsStmt;
25520
+ fingerprintStmt;
25521
+ setFingerprintStmt;
25522
+ rearmStmt;
25523
+ claimStmt;
25524
+ heartbeatStmt;
25525
+ releaseStmt;
25526
+ leaseStmt;
25527
+ inspectionsStmt;
25528
+ closeWindowStmt;
25529
+ releaseBoundaryStmt;
25530
+ freezeBoundaryStmt;
25531
+ captureRowsStmt;
25532
+ markOwedStmt;
25533
+ markCaptureBacklogOwedStmt;
25534
+ captureSkipCountStmt;
25535
+ disownCapturesStmt;
25536
+ partitionStmt;
25537
+ partitionByKindStmt;
25538
+ claimRowStmt;
25539
+ releaseRowStmt;
25540
+ releaseStaleClaimsStmt;
25541
+ /**
25542
+ * The masked detections recorded against one tool call.
25543
+ *
25544
+ * These travel with the event because a tool call's target is not
25545
+ * re-inspectable from the event alone — unlike a capture, where the text
25546
+ * itself is re-scannable. What crosses is the masked match and the rule that
25547
+ * produced it, never the value.
25548
+ */
25549
+ inspectionsFor(auditEventId) {
25550
+ return allRows(this.inspectionsStmt, { auditEventId });
25026
25551
  }
25027
- ensureSyncedAtColumn(db, "audit_events");
25028
- ensureScanLedgerTable(db);
25029
- ensureHistorySyncTable(db);
25030
- ensureBlockedDetectionsTable(db);
25031
- ensureRuleProbeCacheTable(db);
25032
- ensureWriteGateTrigger(db);
25033
- ensureTokenUsageColumns(db);
25034
- reconcileSourceProjectIds(db);
25035
- if (!applied.has(LEGACY_DROP_MIGRATION_TAG)) {
25036
- const drained = runLegacyHistoryBackfill(db);
25037
- if (drained) applyLegacyDropMigration(db, file2);
25552
+ /**
25553
+ * Sessions with structural rows still to send, oldest first.
25554
+ *
25555
+ * BOUNDED BY THE BACKLOG BOUNDARY, which is the whole correctness of this
25556
+ * read. Anything recorded after the machine attached is the live forward
25557
+ * path's to deliver; this drain exists for what was recorded before it, and a
25558
+ * row both paths send is at best a duplicate request and at worst — for a
25559
+ * session root — an overwrite of the inventory ids the live path resolved.
25560
+ */
25561
+ pendingSessions(limit, before) {
25562
+ return allRows(this.sessionsStmt, { limit, before }).map(
25563
+ (r) => r.sessionId
25564
+ );
25038
25565
  }
25039
- }
25040
- function readLegacyTables(db) {
25041
- let holdsRows = false;
25042
- const marks = [];
25043
- for (const table2 of ["events", "findings"]) {
25044
- try {
25045
- const row = db.prepare(`SELECT count(*) AS n, ifnull(max(rowid), -1) AS hi FROM ${table2}`).get();
25046
- if (row === void 0) {
25047
- holdsRows = true;
25048
- marks.push(`${table2}:unreadable`);
25049
- continue;
25050
- }
25051
- if (row.n > 0) holdsRows = true;
25052
- marks.push(`${table2}:${String(row.n)}:${String(row.hi)}`);
25053
- } catch {
25054
- holdsRows = true;
25055
- marks.push(`${table2}:unreadable`);
25056
- }
25566
+ /** One session's undelivered structural rows within the backlog, root first. */
25567
+ pendingRows(sessionId, limit, before) {
25568
+ return allRows(this.rowsStmt, { sessionId, limit, before });
25057
25569
  }
25058
- return { holdsRows, mark: marks.join("|") };
25059
- }
25060
- function applyLegacyDropMigration(db, file2) {
25061
- const migration = SQLITE_MIGRATIONS.find((m) => m.tag === LEGACY_DROP_MIGRATION_TAG);
25062
- if (!migration) return;
25063
- const before = file2 === void 0 ? void 0 : readLegacyTables(db);
25064
- if (file2 !== void 0 && before?.holdsRows === true) {
25065
- try {
25066
- backupBeforeLegacyDrop(db, file2);
25067
- } catch (error61) {
25068
- akaWarn(`legacy events/findings backup failed; deferring the drop: ${String(error61)}`);
25069
- return;
25070
- }
25570
+ /**
25571
+ * Captures this machine still owes the deployment, oldest first.
25572
+ *
25573
+ * Selected by the `outbox_owed` marker the attached forward path writes, not
25574
+ * by a time window — see captureRowsStmt for why a window could not express
25575
+ * this. `before` is the grace window that leaves a just-recorded capture to
25576
+ * the live path.
25577
+ */
25578
+ pendingCaptureRows(limit, before) {
25579
+ return allRows(this.captureRowsStmt, { limit, before });
25071
25580
  }
25072
- try {
25581
+ /**
25582
+ * Record that a capture is OWED to the deployment.
25583
+ *
25584
+ * Written by the attached forward path when a live send did not confirm
25585
+ * delivery, and read by the drain as the whole of its eligibility test. It is
25586
+ * a fact rather than an inference: the machine was attached, the send did not
25587
+ * land, so the row is owed — which no time window can state, because the same
25588
+ * window that holds the rows a past attachment left owed also holds every
25589
+ * capture recorded while the machine was DETACHED, and those were never
25590
+ * offered to anyone.
25591
+ *
25592
+ * Idempotent, and never un-set: `markSynced` settling the row is what takes it
25593
+ * out of the drain's read.
25594
+ */
25595
+ markCaptureOwed(id) {
25596
+ this.markOwedStmt.run({ id });
25597
+ }
25598
+ /**
25599
+ * Mark every capture already on disk as owed, as of `before`.
25600
+ *
25601
+ * The consent-time backfill, called once from `aka attach` when a human
25602
+ * grants existing-history consent — never from an ongoing drain pass, and
25603
+ * never inferred from a boundary that could later move. `before` is the
25604
+ * caller's own "now" at the moment consent was granted, so what this marks
25605
+ * is exactly the backlog the consent prompt already counted, not whatever a
25606
+ * later re-attach or key rotation might widen it to.
25607
+ *
25608
+ * Returns how many rows matched, for the caller to log or test against. Not a
25609
+ * count of NEWLY marked rows — a row still unsynced from an earlier call
25610
+ * matches again and is counted again, the same as `UPDATE`'s own `changes`.
25611
+ */
25612
+ markCaptureBacklogOwed(before) {
25613
+ return Number(this.markCaptureBacklogOwedStmt.run({ before }).changes);
25614
+ }
25615
+ /**
25616
+ * Record delivery. Called only AFTER the far side has accepted the rows.
25617
+ *
25618
+ * CLEARS any failure reason in the same statement. A row that failed against
25619
+ * one deployment and then landed is delivered, and leaving the reason behind
25620
+ * would leave the store holding two contradictory answers about one row —
25621
+ * with the surface free to render either.
25622
+ */
25623
+ markSynced(ids, atMs) {
25624
+ this.stampAll(ids, atMs, null);
25625
+ }
25626
+ /**
25627
+ * Record that THIS MACHINE cannot express the row on the wire.
25628
+ *
25629
+ * Reserved for a local defect — a row that cannot be rebuilt into a valid
25630
+ * payload, or a body the client itself refused to send. It fails identically
25631
+ * against every deployment, so it is terminal everywhere and the re-arm leaves
25632
+ * it alone. A row that merely failed to REACH the deployment stays NULL, so it
25633
+ * is retried; marking those would turn one outage into permanent data loss.
25634
+ */
25635
+ markSkipped(ids, atMs) {
25636
+ this.stampAll(ids, SKIPPED, "payload_invalid", atMs);
25637
+ }
25638
+ /**
25639
+ * Record that THIS DEPLOYMENT refused the row.
25640
+ *
25641
+ * The same sentinel as `markSkipped`, and deliberately so: both stop the row
25642
+ * being re-offered on this lane, and `synced_at` goes on answering whether a
25643
+ * row is outstanding rather than why. What separates them is the reason, and
25644
+ * what the reason buys is the re-arm — a refusal is one deployment's verdict
25645
+ * on one body, so it is terminal only for as long as this machine points at
25646
+ * that deployment, and `rearmFor` clears it when the deployment changes.
25647
+ *
25648
+ * Leaving such a row NULL instead would be worse than the loss it replaces:
25649
+ * these reads carry no cursor, so an unstamped row the deployment refuses is
25650
+ * the head of every subsequent page, and the lane stalls behind it for ever.
25651
+ */
25652
+ markRefused(ids, atMs) {
25653
+ this.stampAll(ids, SKIPPED, "deployment_refused", atMs);
25654
+ }
25655
+ eachInTransaction(ids, run) {
25656
+ if (ids.length === 0) return;
25073
25657
  withTransaction(
25074
- db,
25658
+ this.db,
25075
25659
  () => {
25076
- const alreadyDropped = db.prepare("SELECT 1 FROM migration_ledger WHERE tag = ?").get(migration.tag);
25077
- if (alreadyDropped) return;
25078
- if (before !== void 0 && readLegacyTables(db).mark !== before.mark) {
25079
- akaWarn(
25080
- "legacy events/findings rows changed after the pre-drop snapshot decision; deferring the drop so the next open can copy them first."
25081
- );
25082
- return;
25083
- }
25084
- for (const statement of splitStatements(migration.sql)) {
25085
- db.exec(statement);
25086
- }
25087
- db.prepare("INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)").run(
25088
- migration.tag,
25089
- Date.now()
25090
- );
25660
+ for (const id of ids) run(id);
25091
25661
  },
25092
25662
  "IMMEDIATE"
25093
25663
  );
25094
- } catch (error61) {
25095
- akaWarn(`legacy events/findings drop failed; deferring: ${String(error61)}`);
25096
25664
  }
25097
- }
25098
- function backupBeforeLegacyDrop(db, file2) {
25099
- reapStalePartials(file2);
25100
- const backup = backupPath(file2, "pre-drop");
25101
- snapshotStore(db, backup);
25102
- return backup;
25103
- }
25104
- var TOKEN_USAGE_COLUMNS = [
25105
- {
25106
- name: "input_tokens",
25107
- ddl: "ALTER TABLE audit_events ADD COLUMN input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.input_tokens')) VIRTUAL"
25108
- },
25109
- {
25110
- name: "output_tokens",
25111
- ddl: "ALTER TABLE audit_events ADD COLUMN output_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.output_tokens')) VIRTUAL"
25112
- },
25113
- {
25114
- name: "cache_creation_input_tokens",
25115
- ddl: "ALTER TABLE audit_events ADD COLUMN cache_creation_input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.cache_creation_input_tokens')) VIRTUAL"
25116
- },
25117
- {
25118
- name: "cache_read_input_tokens",
25119
- ddl: "ALTER TABLE audit_events ADD COLUMN cache_read_input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.cache_read_input_tokens')) VIRTUAL"
25120
- },
25121
- {
25122
- name: "model",
25123
- ddl: "ALTER TABLE audit_events ADD COLUMN model text GENERATED ALWAYS AS (json_extract(attributes, '$.model')) VIRTUAL"
25124
- },
25125
- {
25126
- name: "provider",
25127
- ddl: "ALTER TABLE audit_events ADD COLUMN provider text GENERATED ALWAYS AS (json_extract(attributes, '$.provider')) VIRTUAL"
25665
+ stampAll(ids, value, failure, failedAtMs) {
25666
+ if (ids.length === 0) return;
25667
+ const failedAt = failure === null ? null : failedAtMs ?? null;
25668
+ withTransaction(
25669
+ this.db,
25670
+ () => {
25671
+ for (const id of ids) this.stampStmt.run({ at: value, failedAt, failure, id });
25672
+ },
25673
+ "IMMEDIATE"
25674
+ );
25675
+ }
25676
+ /**
25677
+ * Claim rows as in-flight.
25678
+ *
25679
+ * Advisory in exactly the sense the lease is: it records that a send is in
25680
+ * progress so a surface can say so, and a lost claim costs a row showing as
25681
+ * queued while it is actually being sent. It is not exclusion — the far side
25682
+ * settles a duplicate on the row id.
25683
+ */
25684
+ claimRows(ids, atMs) {
25685
+ this.eachInTransaction(ids, (id) => this.claimRowStmt.run({ at: atMs, id }));
25686
+ }
25687
+ /** Give back a claim without settling — the send failed, the row is queued again. */
25688
+ releaseRows(ids) {
25689
+ this.eachInTransaction(ids, (id) => this.releaseRowStmt.run({ id }));
25690
+ }
25691
+ /**
25692
+ * Clear claims older than `staleBefore`, and report how many were cleared.
25693
+ *
25694
+ * A process killed between claiming and settling leaves rows claimed with
25695
+ * nothing left to settle them. Without this they read as "sending" for ever.
25696
+ */
25697
+ releaseStaleClaims(staleBefore) {
25698
+ return Number(this.releaseStaleClaimsStmt.run({ staleBefore }).changes);
25699
+ }
25700
+ /**
25701
+ * Every tracked row in exactly one delivery state.
25702
+ *
25703
+ * Takes no boundary on purpose. The boundary answers "what should the drain
25704
+ * pick up now", which is a different question from "what state is this row
25705
+ * in" — and a machine that has never attached has no boundary to pass, so
25706
+ * requiring one would force a caller to invent one and report the whole store
25707
+ * as queued.
25708
+ */
25709
+ /**
25710
+ * The same partition, one row per kind that a lane carries.
25711
+ *
25712
+ * A kind with nothing to report is ABSENT rather than a row of zeros: the
25713
+ * scope decides which rows exist at all, so a kind that has never been
25714
+ * recorded — or whose captures nobody ever owed — produces no group. A caller
25715
+ * rendering a fixed list of kinds must therefore treat a missing one as "no
25716
+ * rows", never as "zero sent"; the two look identical in a bar and mean
25717
+ * different things.
25718
+ */
25719
+ partitionByKind() {
25720
+ return allRows(
25721
+ this.partitionByKindStmt,
25722
+ {}
25723
+ ).map((row) => ({
25724
+ kind: row.kind,
25725
+ queued: row.queued ?? 0,
25726
+ inProgress: row.inProgress ?? 0,
25727
+ synced: row.synced ?? 0,
25728
+ failed: row.failed ?? 0,
25729
+ refused: row.refused ?? 0,
25730
+ detached: row.detached ?? 0,
25731
+ total: row.total ?? 0
25732
+ }));
25733
+ }
25734
+ partition() {
25735
+ const row = getRow(this.partitionStmt, {});
25736
+ return {
25737
+ queued: row?.queued ?? 0,
25738
+ inProgress: row?.inProgress ?? 0,
25739
+ synced: row?.synced ?? 0,
25740
+ failed: row?.failed ?? 0,
25741
+ refused: row?.refused ?? 0,
25742
+ detached: row?.detached ?? 0,
25743
+ total: row?.total ?? 0
25744
+ };
25745
+ }
25746
+ /** `pending` counts only what is inside the backlog; sent and skipped are totals. */
25747
+ counts(before) {
25748
+ const row = getRow(this.countsStmt, { before });
25749
+ const captures = getRow(this.captureSkipCountStmt);
25750
+ return {
25751
+ pending: row?.pending ?? 0,
25752
+ sent: row?.sent ?? 0,
25753
+ skipped: row?.skipped ?? 0,
25754
+ refused: row?.refused ?? 0,
25755
+ detached: row?.detached ?? 0,
25756
+ capturesSkipped: captures?.skipped ?? 0
25757
+ };
25758
+ }
25759
+ /**
25760
+ * The deployment the current stamps were made against, and where its backlog
25761
+ * ends.
25762
+ *
25763
+ * READ-ONLY. An absent row reads as an absent deployment, which is what a
25764
+ * machine that has never drained is — and every writer below seeds the row
25765
+ * before it needs one, so nothing depends on this creating it. Keeping the
25766
+ * write off the gate path matters because the gate runs on every pass while a
25767
+ * write has to take the database's write lock.
25768
+ */
25769
+ deployment() {
25770
+ const row = getRow(
25771
+ this.fingerprintStmt
25772
+ );
25773
+ return {
25774
+ fingerprint: row?.fingerprint ?? void 0,
25775
+ backlogBefore: row?.backlogBefore ?? void 0
25776
+ };
25777
+ }
25778
+ /**
25779
+ * Point the ledger at a different deployment, discarding what it recorded
25780
+ * about the previous one.
25781
+ *
25782
+ * Delivery is a fact about ONE recipient: rows sent to the deployment a
25783
+ * machine has just left are undelivered as far as the new one is concerned.
25784
+ * All four in one transaction, so a crash between them cannot leave stamps
25785
+ * attributed to the wrong deployment, a boundary that belongs to another, or
25786
+ * a disown with no re-mark to follow it.
25787
+ *
25788
+ * The boundary is written HERE and only here, which is what freezes it: a
25789
+ * re-attach to the SAME deployment (a key rotation) leaves the fingerprint
25790
+ * unchanged, so this never runs and the backlog does not widen back over rows
25791
+ * the live path has since delivered.
25792
+ *
25793
+ * `backfillCapturesBefore` is the caller's OWN "now" at the instant a human
25794
+ * granted existing-history consent for the deployment this call is arming —
25795
+ * a DIFFERENT instant from `backlogBefore`: the re-mark boundary is the GRANT
25796
+ * instant, `backlogBefore` is the ATTACH instant, and the two can be far
25797
+ * apart. Passed only when that grant is valid, since this method has no way
25798
+ * to check consent itself and must not mark a row owed for a machine that
25799
+ * never agreed to it. Applied AFTER the disown above, in the SAME
25800
+ * transaction: what the disown clears is every marker below `backlogBefore`,
25801
+ * which includes this deployment's OWN pre-attach rows — `aka attach` calls
25802
+ * `seedCaptureBacklogOwed` at the attach instant, so every row it marks sits
25803
+ * on the cleared side of that bound — and the re-mark in the same
25804
+ * transaction is what puts those rows back. A crash between the two cannot
25805
+ * strand the ledger disowned with nothing re-marked — the transaction either
25806
+ * lands whole or not at all, and a fingerprint mismatch that has not yet
25807
+ * committed re-enters this method on the very next pass. Omit it (the
25808
+ * structural-only tests do) to exercise the disown in isolation.
25809
+ *
25810
+ * The disown is bounded by `backlogBefore`, which is what keeps it from
25811
+ * touching a marker the NEW deployment's OWN live path has already set: B's
25812
+ * live path can mark a capture owed from the moment `aka attach` writes the
25813
+ * descriptor, before the drain's first pass ever reaches this method, and
25814
+ * such a row sits at or after the bound rather than below it. What keeps the
25815
+ * disown from eating THIS SAME CALL's own re-mark is the order, not the
25816
+ * bound — disown runs first, re-mark second, both inside the one
25817
+ * transaction above.
25818
+ */
25819
+ rearmFor(fingerprint, backlogBefore, backfillCapturesBefore) {
25820
+ this.ensureRowStmt.run();
25821
+ withTransaction(
25822
+ this.db,
25823
+ () => {
25824
+ const previous = getRow(this.fingerprintStmt)?.fingerprint;
25825
+ this.rearmStmt.run();
25826
+ if (previous !== null && previous !== void 0 && previous !== fingerprint) {
25827
+ this.disownCapturesStmt.run({ attachedAt: backlogBefore });
25828
+ }
25829
+ if (backfillCapturesBefore !== void 0) {
25830
+ this.markCaptureBacklogOwedStmt.run({ before: backfillCapturesBefore });
25831
+ }
25832
+ this.setFingerprintStmt.run({ fingerprint, backlogBefore });
25833
+ },
25834
+ "IMMEDIATE"
25835
+ );
25836
+ }
25837
+ /**
25838
+ * End the attached period: hand its rows to the live path, and release the
25839
+ * boundary so the next attachment can freeze a new one.
25840
+ *
25841
+ * WITHOUT THIS, a detach and a re-attach to the same deployment leave a window
25842
+ * nothing delivers. The fingerprint is unchanged, so the boundary is never
25843
+ * re-frozen and stays at the FIRST attachment — while nothing forwards at all
25844
+ * during the detached period, because the machine is not attached. Rows
25845
+ * recorded in that window sit after the boundary and before the re-attach, so
25846
+ * neither path takes them, and the pending count reports none outstanding.
25847
+ *
25848
+ * WHAT IT RECORDS, and what it deliberately does not. These rows were the
25849
+ * closing attachment's to deliver and are no longer outstanding — that is what
25850
+ * lets the boundary move. It is NOT a claim that any of them arrived, and the
25851
+ * distinction is not academic: this used to write a delivery TIME, which every
25852
+ * read treats as delivery, so one detach turned a window of undelivered rows
25853
+ * into a window of delivered ones and no surface could tell. It writes the
25854
+ * skip sentinel and a reason of its own instead, so "no longer owed" and
25855
+ * "received" stop being the same fact.
25856
+ *
25857
+ * A change of deployment still frees them (see the re-arm), because the next
25858
+ * deployment has seen none of this machine's history — so the rows reach it
25859
+ * exactly as they did when this wrote a delivery time.
25860
+ *
25861
+ * ONE TRANSACTION, so a crash cannot release the boundary while leaving the
25862
+ * window unstamped — that half-state would re-send the whole attached period
25863
+ * on the next attach, which is the failure the boundary exists to prevent.
25864
+ */
25865
+ closeAttachedWindow(attachedAtMs, atMs) {
25866
+ this.ensureRowStmt.run();
25867
+ withTransaction(
25868
+ this.db,
25869
+ () => {
25870
+ const row = getRow(this.fingerprintStmt);
25871
+ const from = row?.backlogBefore ?? attachedAtMs;
25872
+ this.closeWindowStmt.run({ at: atMs, attachedAt: from });
25873
+ this.releaseBoundaryStmt.run();
25874
+ },
25875
+ "IMMEDIATE"
25876
+ );
25877
+ }
25878
+ /**
25879
+ * Freeze a boundary for the deployment already on file, KEEPING the stamps.
25880
+ *
25881
+ * The re-attach half of the above. Distinct from `rearmFor`, which is for a
25882
+ * different deployment and therefore discards what was delivered to the old
25883
+ * one: here the recipient is the same, so everything already sent to it stays
25884
+ * sent.
25885
+ */
25886
+ freezeBoundary(backlogBefore) {
25887
+ this.ensureRowStmt.run();
25888
+ this.freezeBoundaryStmt.run({ backlogBefore });
25889
+ }
25890
+ /** Take the claim, or report that someone live already holds it. */
25891
+ claim(pid, host, nowMs, staleAfterMs) {
25892
+ this.ensureRowStmt.run();
25893
+ let taken = false;
25894
+ withTransaction(
25895
+ this.db,
25896
+ () => {
25897
+ const result = this.claimStmt.run({
25898
+ pid,
25899
+ host,
25900
+ now: nowMs,
25901
+ staleBefore: nowMs - staleAfterMs
25902
+ });
25903
+ taken = result.changes === 1;
25904
+ },
25905
+ "IMMEDIATE"
25906
+ );
25907
+ return taken;
25908
+ }
25909
+ /** Say the holder is still alive. A no-op once the claim has moved on. */
25910
+ heartbeat(pid, nowMs) {
25911
+ this.heartbeatStmt.run({ now: nowMs, pid });
25912
+ }
25913
+ /** Give the claim up. Scoped to this holder, so a taken-over claim is left be. */
25914
+ release(pid) {
25915
+ this.releaseStmt.run({ pid });
25916
+ }
25917
+ /** Who holds the claim, if anyone. Read-only, for the same reason as above. */
25918
+ lease() {
25919
+ return getRow(this.leaseStmt);
25920
+ }
25921
+ };
25922
+
25923
+ // ../../packages/persistence/src/migrations.ts
25924
+ function describeObject(object2) {
25925
+ return object2.kind === "column" ? `column ${object2.table}.${object2.name}` : `table ${object2.name}`;
25926
+ }
25927
+ function splitStatements(sql) {
25928
+ return sql.split(/-->\s*statement-breakpoint/).map((s) => s.trim()).filter((s) => s.length > 0);
25929
+ }
25930
+ function createdIndexName(statement) {
25931
+ const body = statement.replace(/^(?:\s*--[^\n]*\n?)+/, "").trimStart();
25932
+ return /^CREATE (?:UNIQUE )?INDEX (?:IF NOT EXISTS )?`([^`]+)`/.exec(body)?.[1];
25933
+ }
25934
+ var LEGACY_DROP_MIGRATION_TAG = "0014_drop_legacy_events_findings";
25935
+ function applyMigrations(db, file2, options = {}) {
25936
+ const legacyCount = db.prepare("PRAGMA user_version").get().user_version;
25937
+ db.exec(
25938
+ "CREATE TABLE IF NOT EXISTS migration_ledger (tag TEXT PRIMARY KEY, applied_at INTEGER NOT NULL)"
25939
+ );
25940
+ const applied = new Set(
25941
+ db.prepare("SELECT tag FROM migration_ledger").all().map((r) => r.tag)
25942
+ );
25943
+ const preLedgerStore = applied.size === 0 && legacyCount > 0;
25944
+ const record2 = db.prepare(
25945
+ "INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)"
25946
+ );
25947
+ for (const [index, migration] of SQLITE_MIGRATIONS.entries()) {
25948
+ if (applied.has(migration.tag)) continue;
25949
+ if (options.skipTags?.has(migration.tag) === true) continue;
25950
+ if (migration.tag === LEGACY_DROP_MIGRATION_TAG) continue;
25951
+ const evidence = evidenceObjects(migration.sql);
25952
+ const present = evidence.filter((o) => evidenceExists(db, o));
25953
+ if (present.length > 0 && present.length < evidence.length) {
25954
+ const missing = evidence.filter((o) => !present.includes(o));
25955
+ const message = `sqlite migration ${migration.tag} has no ledger row, but the store already has ${present.map(describeObject).join(", ")} while missing ${missing.map(describeObject).join(", ")} \u2014 the schema diverged from the migration history; refusing to replay or skip.`;
25956
+ akaWarn(message);
25957
+ throw new Error(`[aka] ${message}`);
25958
+ }
25959
+ const alreadyApplied = evidence.length > 0 ? present.length === evidence.length : preLedgerStore && index < legacyCount;
25960
+ const wantsFkOff = /PRAGMA foreign_keys\s*=\s*OFF/i.test(migration.sql);
25961
+ const statements = splitStatements(migration.sql);
25962
+ if (wantsFkOff) db.exec("PRAGMA foreign_keys = OFF");
25963
+ try {
25964
+ withTransaction(
25965
+ db,
25966
+ () => {
25967
+ for (const statement of statements) {
25968
+ const indexName = createdIndexName(statement);
25969
+ if (indexName === void 0) {
25970
+ if (alreadyApplied) continue;
25971
+ } else if (indexExists(db, indexName)) {
25972
+ continue;
25973
+ }
25974
+ db.exec(statement);
25975
+ }
25976
+ if (wantsFkOff && !alreadyApplied) {
25977
+ const violations = db.prepare("PRAGMA foreign_key_check").all();
25978
+ if (violations.length > 0) {
25979
+ throw new Error(
25980
+ `[aka] sqlite migration ${migration.tag} left ${String(violations.length)} foreign-key violation(s); rolling back.`
25981
+ );
25982
+ }
25983
+ }
25984
+ record2.run(migration.tag, Date.now());
25985
+ },
25986
+ "IMMEDIATE"
25987
+ );
25988
+ } finally {
25989
+ if (wantsFkOff) db.exec("PRAGMA foreign_keys = ON");
25990
+ }
25991
+ }
25992
+ if (legacyCount < SQLITE_MIGRATIONS.length) {
25993
+ db.exec(`PRAGMA user_version = ${String(SQLITE_MIGRATIONS.length)}`);
25994
+ }
25995
+ ensureSyncedAtColumn(db, "audit_events");
25996
+ ensureScanLedgerTable(db);
25997
+ ensureHistorySyncTable(db);
25998
+ ensureBlockedDetectionsTable(db);
25999
+ ensureRuleProbeCacheTable(db);
26000
+ ensureWriteGateTrigger(db);
26001
+ ensureTokenUsageColumns(db);
26002
+ reconcileSourceProjectIds(db);
26003
+ if (!applied.has(LEGACY_DROP_MIGRATION_TAG)) {
26004
+ const drained = runLegacyHistoryBackfill(db);
26005
+ if (drained) applyLegacyDropMigration(db, file2);
26006
+ }
26007
+ }
26008
+ function readLegacyTables(db) {
26009
+ let holdsRows = false;
26010
+ const marks = [];
26011
+ for (const table2 of ["events", "findings"]) {
26012
+ try {
26013
+ const row = db.prepare(`SELECT count(*) AS n, ifnull(max(rowid), -1) AS hi FROM ${table2}`).get();
26014
+ if (row === void 0) {
26015
+ holdsRows = true;
26016
+ marks.push(`${table2}:unreadable`);
26017
+ continue;
26018
+ }
26019
+ if (row.n > 0) holdsRows = true;
26020
+ marks.push(`${table2}:${String(row.n)}:${String(row.hi)}`);
26021
+ } catch {
26022
+ holdsRows = true;
26023
+ marks.push(`${table2}:unreadable`);
26024
+ }
26025
+ }
26026
+ return { holdsRows, mark: marks.join("|") };
26027
+ }
26028
+ function applyLegacyDropMigration(db, file2) {
26029
+ const migration = SQLITE_MIGRATIONS.find((m) => m.tag === LEGACY_DROP_MIGRATION_TAG);
26030
+ if (!migration) return;
26031
+ const before = file2 === void 0 ? void 0 : readLegacyTables(db);
26032
+ if (file2 !== void 0 && before?.holdsRows === true) {
26033
+ try {
26034
+ backupBeforeLegacyDrop(db, file2);
26035
+ } catch (error61) {
26036
+ akaWarn(`legacy events/findings backup failed; deferring the drop: ${String(error61)}`);
26037
+ return;
26038
+ }
26039
+ }
26040
+ try {
26041
+ withTransaction(
26042
+ db,
26043
+ () => {
26044
+ const alreadyDropped = db.prepare("SELECT 1 FROM migration_ledger WHERE tag = ?").get(migration.tag);
26045
+ if (alreadyDropped) return;
26046
+ if (before !== void 0 && readLegacyTables(db).mark !== before.mark) {
26047
+ akaWarn(
26048
+ "legacy events/findings rows changed after the pre-drop snapshot decision; deferring the drop so the next open can copy them first."
26049
+ );
26050
+ return;
26051
+ }
26052
+ for (const statement of splitStatements(migration.sql)) {
26053
+ db.exec(statement);
26054
+ }
26055
+ db.prepare("INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)").run(
26056
+ migration.tag,
26057
+ Date.now()
26058
+ );
26059
+ },
26060
+ "IMMEDIATE"
26061
+ );
26062
+ } catch (error61) {
26063
+ akaWarn(`legacy events/findings drop failed; deferring: ${String(error61)}`);
26064
+ }
26065
+ }
26066
+ function backupBeforeLegacyDrop(db, file2) {
26067
+ reapStalePartials(file2);
26068
+ const backup = backupPath(file2, "pre-drop");
26069
+ snapshotStore(db, backup);
26070
+ return backup;
26071
+ }
26072
+ var TOKEN_USAGE_COLUMNS = [
26073
+ {
26074
+ name: "input_tokens",
26075
+ ddl: "ALTER TABLE audit_events ADD COLUMN input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.input_tokens')) VIRTUAL"
26076
+ },
26077
+ {
26078
+ name: "output_tokens",
26079
+ ddl: "ALTER TABLE audit_events ADD COLUMN output_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.output_tokens')) VIRTUAL"
26080
+ },
26081
+ {
26082
+ name: "cache_creation_input_tokens",
26083
+ ddl: "ALTER TABLE audit_events ADD COLUMN cache_creation_input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.cache_creation_input_tokens')) VIRTUAL"
26084
+ },
26085
+ {
26086
+ name: "cache_read_input_tokens",
26087
+ ddl: "ALTER TABLE audit_events ADD COLUMN cache_read_input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.cache_read_input_tokens')) VIRTUAL"
26088
+ },
26089
+ {
26090
+ name: "model",
26091
+ ddl: "ALTER TABLE audit_events ADD COLUMN model text GENERATED ALWAYS AS (json_extract(attributes, '$.model')) VIRTUAL"
26092
+ },
26093
+ {
26094
+ name: "provider",
26095
+ ddl: "ALTER TABLE audit_events ADD COLUMN provider text GENERATED ALWAYS AS (json_extract(attributes, '$.provider')) VIRTUAL"
25128
26096
  }
25129
26097
  ];
25130
26098
  function ensureTokenUsageColumns(db) {
@@ -25385,10 +26353,62 @@ function ensureSyncedAtColumn(db, table2) {
25385
26353
  if (!columns.includes("outbox_owed")) {
25386
26354
  db.exec(`ALTER TABLE ${table2} ADD COLUMN outbox_owed integer`);
25387
26355
  }
26356
+ if (!columns.includes("sync_failed_at")) {
26357
+ db.exec(`ALTER TABLE ${table2} ADD COLUMN sync_failed_at integer`);
26358
+ }
26359
+ if (!columns.includes("sync_failure")) {
26360
+ withTransaction(
26361
+ db,
26362
+ () => {
26363
+ db.exec(`ALTER TABLE ${table2} ADD COLUMN sync_failure text`);
26364
+ db.exec(
26365
+ `UPDATE ${table2} SET synced_at = NULL
26366
+ WHERE synced_at = -1
26367
+ AND event_type IN (${COUNTED_EVENT_TYPES.map((t) => `'${t}'`).join(", ")})`
26368
+ );
26369
+ },
26370
+ "IMMEDIATE"
26371
+ );
26372
+ }
25388
26373
  db.exec(
25389
- `CREATE INDEX IF NOT EXISTS idx_audit_events_sync
25390
- ON audit_events (event_type, synced_at, sync_claimed_at, started_at)`
26374
+ `CREATE TRIGGER IF NOT EXISTS aka_sync_failure_guard
26375
+ BEFORE UPDATE OF sync_failure ON ${table2}
26376
+ WHEN ${syncFailureRejectCondition()}
26377
+ BEGIN SELECT RAISE(ABORT, 'sync_failure is not one of the recorded reasons'); END`
25391
26378
  );
26379
+ const syncIndexColumns = [
26380
+ "event_type",
26381
+ "synced_at",
26382
+ "sync_claimed_at",
26383
+ "started_at",
26384
+ // Appended LAST on purpose. The delivery-state read now projects it, so it
26385
+ // has to be in the index for the read to stay covered — but putting it
26386
+ // ahead of `started_at` would reorder the prefix the structural drain's
26387
+ // reads match on.
26388
+ "sync_failure"
26389
+ // `outbox_owed` is DELIBERATELY ABSENT, and it was measured both ways.
26390
+ //
26391
+ // The delivery-state read tests it — a capture's state depends on whether a
26392
+ // live forward marked it owed — so carrying it here makes that read covering
26393
+ // rather than a row fetch per row: 16 ms against 40 ms on a real 6 GB store.
26394
+ // But a sixth column changes what the planner charges for this index, and
26395
+ // with no ANALYZE statistics it plans from schema shape alone: measured, it
26396
+ // then stops choosing the per-session index for the token rollup and walks
26397
+ // every `llm_call` in the store through the event-type index instead. That
26398
+ // read grows with the store; this one does not.
26399
+ //
26400
+ // 40 ms on the largest store measured, once per render, is a cost worth
26401
+ // paying to leave every other read's plan where it was.
26402
+ ];
26403
+ const currentSyncIndex = indexColumns(db, "idx_audit_events_sync");
26404
+ const syncIndexMatches = currentSyncIndex.length === syncIndexColumns.length && currentSyncIndex.every((column, i) => column === syncIndexColumns[i]);
26405
+ if (!syncIndexMatches) {
26406
+ db.exec("DROP INDEX IF EXISTS idx_audit_events_sync");
26407
+ db.exec(
26408
+ `CREATE INDEX idx_audit_events_sync
26409
+ ON audit_events (${syncIndexColumns.join(", ")})`
26410
+ );
26411
+ }
25392
26412
  db.exec(
25393
26413
  `CREATE INDEX IF NOT EXISTS idx_audit_outbox_owed
25394
26414
  ON audit_events (event_type, synced_at, sync_claimed_at, started_at) WHERE outbox_owed = 1`
@@ -25610,7 +26630,11 @@ function buildAuditEvent(row) {
25610
26630
  link: linkParsed?.success ? linkParsed.data : null,
25611
26631
  targetId: row.target_id,
25612
26632
  internal: intToBool(row.internal),
25613
- flagged: intToBool(row.flagged)
26633
+ flagged: intToBool(row.flagged),
26634
+ // Only meaningful when the title came out empty — a row whose body was
26635
+ // expired but whose title fell back to `tool_name` still has something to
26636
+ // render, and flagging it would make the view apologise for nothing.
26637
+ bodyExpired: row.content_expired_at !== null && (row.title ?? "") === ""
25614
26638
  };
25615
26639
  }
25616
26640
  var TIMELINE_COLUMNS = `
@@ -25618,6 +26642,7 @@ var TIMELINE_COLUMNS = `
25618
26642
  event_type,
25619
26643
  started_at,
25620
26644
  coalesce(content, json_extract(attributes, '$.tool_name')) AS title,
26645
+ content_expired_at,
25621
26646
  coalesce(json_extract(attributes, '$.detail'), json_extract(attributes, '$.target')) AS detail,
25622
26647
  coalesce(json_extract(attributes, '$.tool_name'), json_extract(attributes, '$.tool')) AS tool,
25623
26648
  json_extract(attributes, '$.severity') AS severity,
@@ -26283,6 +27308,88 @@ var SqliteAuditEventsRepository = class {
26283
27308
  }
26284
27309
  };
26285
27310
 
27311
+ // ../../packages/persistence/src/repositories/body-retention.ts
27312
+ var DEFAULT_BATCH_SIZE = 500;
27313
+ var DEFAULT_MAX_ROWS = 5e4;
27314
+ var SYNC_LANE_TYPES_SQL = OUTBOX_CAPTURE_TYPE_LIST;
27315
+ var SqliteBodyRetentionRepository = class {
27316
+ constructor(db) {
27317
+ this.db = db;
27318
+ const select = (laneClause) => `
27319
+ SELECT id, LENGTH(CAST(content AS BLOB)) AS bytes
27320
+ FROM audit_events
27321
+ WHERE content IS NOT NULL
27322
+ AND started_at < :cutoff
27323
+ AND event_type IN (${CAPTURE_EVENT_TYPES_SQL})
27324
+ ${laneClause}
27325
+ ORDER BY started_at
27326
+ LIMIT :limit`;
27327
+ this.candidatesStmt = this.db.prepare(select(""));
27328
+ this.candidatesSyncSafeStmt = this.db.prepare(
27329
+ select(`AND (event_type NOT IN (${SYNC_LANE_TYPES_SQL}) OR synced_at IS NOT NULL)`)
27330
+ );
27331
+ this.heldBySyncStmt = this.db.prepare(`
27332
+ SELECT COUNT(*) AS n
27333
+ FROM audit_events
27334
+ WHERE content IS NOT NULL
27335
+ AND started_at < :cutoff
27336
+ AND event_type IN (${SYNC_LANE_TYPES_SQL})
27337
+ AND synced_at IS NULL`);
27338
+ this.expireStmt = this.db.prepare(
27339
+ `UPDATE audit_events SET content = NULL, content_expired_at = :now WHERE id = :id`
27340
+ );
27341
+ }
27342
+ db;
27343
+ candidatesStmt;
27344
+ candidatesSyncSafeStmt;
27345
+ heldBySyncStmt;
27346
+ expireStmt;
27347
+ /** How many bytes a pass with these options would free, changing nothing. */
27348
+ preview(opts) {
27349
+ const limit = opts.maxRows ?? DEFAULT_MAX_ROWS;
27350
+ const stmt = opts.sweepSyncLane ? this.candidatesStmt : this.candidatesSyncSafeStmt;
27351
+ const rows = stmt.all({ cutoff: opts.cutoff, limit });
27352
+ return {
27353
+ rowsExpired: rows.length,
27354
+ bytesFreed: rows.reduce((sum, r) => sum + r.bytes, 0),
27355
+ rowsHeldBySync: this.countHeldBySync(opts)
27356
+ };
27357
+ }
27358
+ /** Clear eligible bodies, in bounded batches. */
27359
+ expire(opts) {
27360
+ const batchSize = opts.batchSize ?? DEFAULT_BATCH_SIZE;
27361
+ const maxRows = opts.maxRows ?? DEFAULT_MAX_ROWS;
27362
+ const stmt = opts.sweepSyncLane ? this.candidatesStmt : this.candidatesSyncSafeStmt;
27363
+ let rowsExpired = 0;
27364
+ let bytesFreed = 0;
27365
+ let done = true;
27366
+ while (rowsExpired < maxRows) {
27367
+ const remaining = Math.min(batchSize, maxRows - rowsExpired);
27368
+ const batch = stmt.all({ cutoff: opts.cutoff, limit: remaining });
27369
+ if (batch.length === 0) break;
27370
+ withTransaction(
27371
+ this.db,
27372
+ () => {
27373
+ for (const row of batch) this.expireStmt.run({ id: row.id, now: opts.now });
27374
+ },
27375
+ "IMMEDIATE"
27376
+ );
27377
+ rowsExpired += batch.length;
27378
+ bytesFreed += batch.reduce((sum, r) => sum + r.bytes, 0);
27379
+ if (batch.length < remaining) break;
27380
+ if (rowsExpired >= maxRows) {
27381
+ done = stmt.all({ cutoff: opts.cutoff, limit: 1 }).length === 0;
27382
+ }
27383
+ }
27384
+ return { rowsExpired, bytesFreed, rowsHeldBySync: this.countHeldBySync(opts), done };
27385
+ }
27386
+ countHeldBySync(opts) {
27387
+ if (opts.sweepSyncLane) return 0;
27388
+ const row = this.heldBySyncStmt.get({ cutoff: opts.cutoff });
27389
+ return row.n;
27390
+ }
27391
+ };
27392
+
26286
27393
  // ../../packages/persistence/src/repositories/classified-data.ts
26287
27394
  var SqliteClassifiedDataRepository = class {
26288
27395
  constructor(db) {
@@ -27111,7 +28218,15 @@ function toFlatFindingRow(r) {
27111
28218
  ...r.tool_name === null ? {} : { toolName: r.tool_name },
27112
28219
  eventId: r.event_id,
27113
28220
  ...r.session_id === null ? {} : { sessionId: r.session_id },
27114
- status: deriveInstanceStatus(r)
28221
+ status: deriveInstanceStatus(r),
28222
+ delivery: deriveFindingDelivery({
28223
+ kind: r.kind,
28224
+ syncedAt: r.synced_at,
28225
+ syncClaimedAt: r.sync_claimed_at,
28226
+ syncFailedAt: r.sync_failed_at,
28227
+ syncFailure: r.sync_failure,
28228
+ outboxOwed: r.outbox_owed
28229
+ })
27115
28230
  };
27116
28231
  }
27117
28232
  function encodeGroupCursor(group) {
@@ -27175,7 +28290,10 @@ var FINDING_ROW_COLUMNS_SQL = `f.id AS id, d.rule_id AS rule_id, d.category AS c
27175
28290
  e.tool_name AS tool_name,
27176
28291
  f.audit_event_id AS event_id, e.root_session_id AS session_id,
27177
28292
  e.event_type AS kind, f.finding_key AS finding_key,
27178
- ${latestResolutionStatusSql("f")} AS latest_status`;
28293
+ ${latestResolutionStatusSql("f")} AS latest_status,
28294
+ e.synced_at AS synced_at, e.sync_claimed_at AS sync_claimed_at,
28295
+ e.sync_failed_at AS sync_failed_at, e.sync_failure AS sync_failure,
28296
+ e.outbox_owed AS outbox_owed`;
27179
28297
  var DAY_MS3 = 864e5;
27180
28298
  var SqliteFindingsRepository = class {
27181
28299
  constructor(db) {
@@ -27420,6 +28538,7 @@ var SqliteFindingsRepository = class {
27420
28538
  providers: query.provider,
27421
28539
  actions: query.action,
27422
28540
  statuses: query.status,
28541
+ deliveries: query.deployment,
27423
28542
  tools: query.tool,
27424
28543
  repo: query.repo,
27425
28544
  file: query.file,
@@ -27487,6 +28606,7 @@ var SqliteFindingsRepository = class {
27487
28606
  providers: query.provider,
27488
28607
  actions: query.action,
27489
28608
  statuses: query.status,
28609
+ deliveries: query.deployment,
27490
28610
  tools: query.tool,
27491
28611
  q: query.q
27492
28612
  };
@@ -27750,7 +28870,9 @@ var SqliteFindingsRepository = class {
27750
28870
  )
27751
28871
  );
27752
28872
  for (const row of grouped) {
27753
- if (row.action_taken in byAction) byAction[row.action_taken] = row.c;
28873
+ if (Object.hasOwn(byAction, row.action_taken)) {
28874
+ byAction[row.action_taken] = row.c;
28875
+ }
27754
28876
  }
27755
28877
  const bySeverity = { critical: 0, high: 0, medium: 0, low: 0 };
27756
28878
  const sevRows = allRows(
@@ -27767,7 +28889,9 @@ var SqliteFindingsRepository = class {
27767
28889
  )
27768
28890
  );
27769
28891
  for (const row of sevRows) {
27770
- if (row.severity in bySeverity) bySeverity[row.severity] = row.c;
28892
+ if (Object.hasOwn(bySeverity, row.severity)) {
28893
+ bySeverity[row.severity] = row.c;
28894
+ }
27771
28895
  }
27772
28896
  const categories = ENFORCEABLE_CATEGORIES;
27773
28897
  const enabledRows = allRows(
@@ -27816,525 +28940,6 @@ function isoDay(ms) {
27816
28940
  return new Date(ms).toISOString().slice(0, 10);
27817
28941
  }
27818
28942
 
27819
- // ../../packages/persistence/src/repositories/history-sync.ts
27820
- var STRUCTURAL_EVENT_TYPES = ["session", "llm_call", "tool_call"];
27821
- var TYPE_LIST = STRUCTURAL_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
27822
- var OUTBOX_CAPTURE_EVENT_TYPES = ["prompt", "response", "tool_use"];
27823
- var CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
27824
- var SKIPPED = -1;
27825
- var ROW_COLUMNS = `id,
27826
- parent_id AS parentId,
27827
- root_session_id AS rootSessionId,
27828
- event_type AS eventType,
27829
- host_id AS hostId,
27830
- harness_id AS harnessId,
27831
- source_project_id AS sourceProjectId,
27832
- started_at AS startedAt,
27833
- ended_at AS endedAt,
27834
- severity,
27835
- priority,
27836
- content,
27837
- content_hash AS contentHash,
27838
- attributes`;
27839
- var SqliteHistorySyncRepository = class {
27840
- constructor(db) {
27841
- this.db = db;
27842
- this.ensureRowStmt = db.prepare(`INSERT OR IGNORE INTO history_sync (id) VALUES (1)`);
27843
- this.sessionsStmt = db.prepare(
27844
- `SELECT COALESCE(root_session_id, id) AS sessionId, MIN(started_at) AS earliest
27845
- FROM audit_events
27846
- WHERE synced_at IS NULL
27847
- AND event_type IN (${TYPE_LIST})
27848
- AND started_at < :before
27849
- GROUP BY sessionId
27850
- ORDER BY earliest
27851
- LIMIT :limit`
27852
- );
27853
- this.rowsStmt = db.prepare(
27854
- `SELECT ${ROW_COLUMNS}
27855
- FROM audit_events
27856
- WHERE synced_at IS NULL
27857
- AND event_type IN (${TYPE_LIST})
27858
- AND started_at < :before
27859
- AND COALESCE(root_session_id, id) = :sessionId
27860
- ORDER BY (event_type = 'session') DESC, started_at
27861
- LIMIT :limit`
27862
- );
27863
- this.captureRowsStmt = db.prepare(
27864
- `SELECT ${ROW_COLUMNS}
27865
- FROM audit_events
27866
- WHERE synced_at IS NULL
27867
- AND sync_claimed_at IS NULL
27868
- AND outbox_owed = 1
27869
- AND event_type IN (${CAPTURE_TYPE_LIST})
27870
- AND started_at < :before
27871
- ORDER BY started_at
27872
- LIMIT :limit`
27873
- );
27874
- this.markOwedStmt = db.prepare(
27875
- `UPDATE audit_events SET outbox_owed = 1 WHERE id = :id AND synced_at IS NULL`
27876
- );
27877
- this.markCaptureBacklogOwedStmt = db.prepare(
27878
- `UPDATE audit_events SET outbox_owed = 1
27879
- WHERE synced_at IS NULL
27880
- AND event_type IN (${CAPTURE_TYPE_LIST})
27881
- AND started_at < :before`
27882
- );
27883
- this.stampStmt = db.prepare(
27884
- `UPDATE audit_events SET synced_at = :at, sync_claimed_at = NULL WHERE id = :id`
27885
- );
27886
- this.claimRowStmt = db.prepare(
27887
- `UPDATE audit_events SET sync_claimed_at = :at WHERE id = :id AND synced_at IS NULL`
27888
- );
27889
- this.releaseRowStmt = db.prepare(
27890
- `UPDATE audit_events SET sync_claimed_at = NULL WHERE id = :id`
27891
- );
27892
- this.releaseStaleClaimsStmt = db.prepare(
27893
- `UPDATE audit_events SET sync_claimed_at = NULL
27894
- WHERE sync_claimed_at IS NOT NULL AND sync_claimed_at < :staleBefore`
27895
- );
27896
- this.partitionStmt = db.prepare(
27897
- `SELECT
27898
- SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NULL THEN 1 ELSE 0 END) AS queued,
27899
- SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NOT NULL THEN 1 ELSE 0 END) AS inProgress,
27900
- SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS synced,
27901
- SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0 THEN 1 ELSE 0 END) AS failed,
27902
- COUNT(*) AS total
27903
- FROM audit_events
27904
- WHERE event_type IN (${TYPE_LIST})`
27905
- );
27906
- this.countsStmt = db.prepare(
27907
- `SELECT
27908
- SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
27909
- SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
27910
- SUM(CASE WHEN synced_at = ${String(SKIPPED)} THEN 1 ELSE 0 END) AS skipped
27911
- FROM audit_events
27912
- WHERE event_type IN (${TYPE_LIST})`
27913
- );
27914
- this.captureSkipCountStmt = db.prepare(
27915
- `SELECT COUNT(*) AS skipped
27916
- FROM audit_events
27917
- WHERE synced_at = ${String(SKIPPED)}
27918
- AND event_type IN (${CAPTURE_TYPE_LIST})`
27919
- );
27920
- this.fingerprintStmt = db.prepare(
27921
- `SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
27922
- FROM history_sync WHERE id = 1`
27923
- );
27924
- this.setFingerprintStmt = db.prepare(
27925
- `UPDATE history_sync
27926
- SET endpoint_fingerprint = :fingerprint, backlog_before = :backlogBefore
27927
- WHERE id = 1`
27928
- );
27929
- this.disownCapturesStmt = db.prepare(
27930
- `UPDATE audit_events SET outbox_owed = NULL
27931
- WHERE outbox_owed IS NOT NULL
27932
- AND event_type IN (${CAPTURE_TYPE_LIST})
27933
- AND started_at < :attachedAt`
27934
- );
27935
- this.rearmStmt = db.prepare(
27936
- `UPDATE audit_events SET synced_at = NULL
27937
- WHERE synced_at > 0 AND event_type IN (${TYPE_LIST})`
27938
- );
27939
- this.claimStmt = db.prepare(
27940
- `UPDATE history_sync
27941
- SET owner_pid = :pid, owner_host = :host, acquired_at = :now, heartbeat_at = :now
27942
- WHERE id = 1
27943
- AND (owner_pid IS NULL
27944
- OR heartbeat_at IS NULL
27945
- OR heartbeat_at < :staleBefore
27946
- OR heartbeat_at > :now)`
27947
- );
27948
- this.heartbeatStmt = db.prepare(
27949
- `UPDATE history_sync SET heartbeat_at = :now WHERE id = 1 AND owner_pid = :pid`
27950
- );
27951
- this.releaseStmt = db.prepare(
27952
- `UPDATE history_sync
27953
- SET owner_pid = NULL, owner_host = NULL, acquired_at = NULL, heartbeat_at = NULL
27954
- WHERE id = 1 AND owner_pid = :pid`
27955
- );
27956
- this.closeWindowStmt = db.prepare(
27957
- `UPDATE audit_events SET synced_at = :at
27958
- WHERE synced_at IS NULL
27959
- AND event_type IN (${TYPE_LIST})
27960
- AND started_at >= :attachedAt`
27961
- );
27962
- this.releaseBoundaryStmt = db.prepare(
27963
- `UPDATE history_sync SET backlog_before = NULL WHERE id = 1`
27964
- );
27965
- this.freezeBoundaryStmt = db.prepare(
27966
- `UPDATE history_sync SET backlog_before = :backlogBefore WHERE id = 1`
27967
- );
27968
- this.leaseStmt = db.prepare(
27969
- `SELECT owner_pid AS ownerPid, owner_host AS ownerHost,
27970
- acquired_at AS acquiredAt, heartbeat_at AS heartbeatAt
27971
- FROM history_sync WHERE id = 1`
27972
- );
27973
- this.inspectionsStmt = db.prepare(
27974
- `SELECT d.rule_id AS ruleId,
27975
- d.name AS ruleName,
27976
- d.version AS ruleVersion,
27977
- d.category AS category,
27978
- d.severity AS severity,
27979
- f.span_start AS spanStart,
27980
- f.span_end AS spanEnd,
27981
- f.masked_match AS maskedMatch,
27982
- f.action_taken AS actionTaken,
27983
- f.confidence AS confidence
27984
- FROM inspection_findings f
27985
- JOIN inspection_definitions d ON d.id = f.inspection_definition_id
27986
- WHERE f.audit_event_id = :auditEventId
27987
- ORDER BY f.span_start, f.id`
27988
- );
27989
- }
27990
- db;
27991
- ensureRowStmt;
27992
- sessionsStmt;
27993
- rowsStmt;
27994
- stampStmt;
27995
- countsStmt;
27996
- fingerprintStmt;
27997
- setFingerprintStmt;
27998
- rearmStmt;
27999
- claimStmt;
28000
- heartbeatStmt;
28001
- releaseStmt;
28002
- leaseStmt;
28003
- inspectionsStmt;
28004
- closeWindowStmt;
28005
- releaseBoundaryStmt;
28006
- freezeBoundaryStmt;
28007
- captureRowsStmt;
28008
- markOwedStmt;
28009
- markCaptureBacklogOwedStmt;
28010
- captureSkipCountStmt;
28011
- disownCapturesStmt;
28012
- partitionStmt;
28013
- claimRowStmt;
28014
- releaseRowStmt;
28015
- releaseStaleClaimsStmt;
28016
- /**
28017
- * The masked detections recorded against one tool call.
28018
- *
28019
- * These travel with the event because a tool call's target is not
28020
- * re-inspectable from the event alone — unlike a capture, where the text
28021
- * itself is re-scannable. What crosses is the masked match and the rule that
28022
- * produced it, never the value.
28023
- */
28024
- inspectionsFor(auditEventId) {
28025
- return allRows(this.inspectionsStmt, { auditEventId });
28026
- }
28027
- /**
28028
- * Sessions with structural rows still to send, oldest first.
28029
- *
28030
- * BOUNDED BY THE BACKLOG BOUNDARY, which is the whole correctness of this
28031
- * read. Anything recorded after the machine attached is the live forward
28032
- * path's to deliver; this drain exists for what was recorded before it, and a
28033
- * row both paths send is at best a duplicate request and at worst — for a
28034
- * session root — an overwrite of the inventory ids the live path resolved.
28035
- */
28036
- pendingSessions(limit, before) {
28037
- return allRows(this.sessionsStmt, { limit, before }).map(
28038
- (r) => r.sessionId
28039
- );
28040
- }
28041
- /** One session's undelivered structural rows within the backlog, root first. */
28042
- pendingRows(sessionId, limit, before) {
28043
- return allRows(this.rowsStmt, { sessionId, limit, before });
28044
- }
28045
- /**
28046
- * Captures this machine still owes the deployment, oldest first.
28047
- *
28048
- * Selected by the `outbox_owed` marker the attached forward path writes, not
28049
- * by a time window — see captureRowsStmt for why a window could not express
28050
- * this. `before` is the grace window that leaves a just-recorded capture to
28051
- * the live path.
28052
- */
28053
- pendingCaptureRows(limit, before) {
28054
- return allRows(this.captureRowsStmt, { limit, before });
28055
- }
28056
- /**
28057
- * Record that a capture is OWED to the deployment.
28058
- *
28059
- * Written by the attached forward path when a live send did not confirm
28060
- * delivery, and read by the drain as the whole of its eligibility test. It is
28061
- * a fact rather than an inference: the machine was attached, the send did not
28062
- * land, so the row is owed — which no time window can state, because the same
28063
- * window that holds the rows a past attachment left owed also holds every
28064
- * capture recorded while the machine was DETACHED, and those were never
28065
- * offered to anyone.
28066
- *
28067
- * Idempotent, and never un-set: `markSynced` settling the row is what takes it
28068
- * out of the drain's read.
28069
- */
28070
- markCaptureOwed(id) {
28071
- this.markOwedStmt.run({ id });
28072
- }
28073
- /**
28074
- * Mark every capture already on disk as owed, as of `before`.
28075
- *
28076
- * The consent-time backfill, called once from `aka attach` when a human
28077
- * grants existing-history consent — never from an ongoing drain pass, and
28078
- * never inferred from a boundary that could later move. `before` is the
28079
- * caller's own "now" at the moment consent was granted, so what this marks
28080
- * is exactly the backlog the consent prompt already counted, not whatever a
28081
- * later re-attach or key rotation might widen it to.
28082
- *
28083
- * Returns how many rows matched, for the caller to log or test against. Not a
28084
- * count of NEWLY marked rows — a row still unsynced from an earlier call
28085
- * matches again and is counted again, the same as `UPDATE`'s own `changes`.
28086
- */
28087
- markCaptureBacklogOwed(before) {
28088
- return Number(this.markCaptureBacklogOwedStmt.run({ before }).changes);
28089
- }
28090
- /** Record delivery. Called only AFTER the far side has accepted the rows. */
28091
- markSynced(ids, atMs) {
28092
- this.stampAll(ids, atMs);
28093
- }
28094
- /**
28095
- * Record that a row will never be sent.
28096
- *
28097
- * Reserved for a local defect — a row that cannot be rebuilt into a valid
28098
- * payload. A row that merely failed to reach the deployment stays NULL, so it
28099
- * is retried; marking those would turn one outage into permanent data loss.
28100
- */
28101
- markSkipped(ids) {
28102
- this.stampAll(ids, SKIPPED);
28103
- }
28104
- eachInTransaction(ids, run) {
28105
- if (ids.length === 0) return;
28106
- withTransaction(
28107
- this.db,
28108
- () => {
28109
- for (const id of ids) run(id);
28110
- },
28111
- "IMMEDIATE"
28112
- );
28113
- }
28114
- stampAll(ids, value) {
28115
- if (ids.length === 0) return;
28116
- withTransaction(
28117
- this.db,
28118
- () => {
28119
- for (const id of ids) this.stampStmt.run({ at: value, id });
28120
- },
28121
- "IMMEDIATE"
28122
- );
28123
- }
28124
- /**
28125
- * Claim rows as in-flight.
28126
- *
28127
- * Advisory in exactly the sense the lease is: it records that a send is in
28128
- * progress so a surface can say so, and a lost claim costs a row showing as
28129
- * queued while it is actually being sent. It is not exclusion — the far side
28130
- * settles a duplicate on the row id.
28131
- */
28132
- claimRows(ids, atMs) {
28133
- this.eachInTransaction(ids, (id) => this.claimRowStmt.run({ at: atMs, id }));
28134
- }
28135
- /** Give back a claim without settling — the send failed, the row is queued again. */
28136
- releaseRows(ids) {
28137
- this.eachInTransaction(ids, (id) => this.releaseRowStmt.run({ id }));
28138
- }
28139
- /**
28140
- * Clear claims older than `staleBefore`, and report how many were cleared.
28141
- *
28142
- * A process killed between claiming and settling leaves rows claimed with
28143
- * nothing left to settle them. Without this they read as "sending" for ever.
28144
- */
28145
- releaseStaleClaims(staleBefore) {
28146
- return Number(this.releaseStaleClaimsStmt.run({ staleBefore }).changes);
28147
- }
28148
- /**
28149
- * Every tracked row in exactly one delivery state.
28150
- *
28151
- * Takes no boundary on purpose. The boundary answers "what should the drain
28152
- * pick up now", which is a different question from "what state is this row
28153
- * in" — and a machine that has never attached has no boundary to pass, so
28154
- * requiring one would force a caller to invent one and report the whole store
28155
- * as queued.
28156
- */
28157
- partition() {
28158
- const row = getRow(this.partitionStmt, {});
28159
- return {
28160
- queued: row?.queued ?? 0,
28161
- inProgress: row?.inProgress ?? 0,
28162
- synced: row?.synced ?? 0,
28163
- failed: row?.failed ?? 0,
28164
- total: row?.total ?? 0
28165
- };
28166
- }
28167
- /** `pending` counts only what is inside the backlog; sent and skipped are totals. */
28168
- counts(before) {
28169
- const row = getRow(
28170
- this.countsStmt,
28171
- { before }
28172
- );
28173
- const captures = getRow(this.captureSkipCountStmt);
28174
- return {
28175
- pending: row?.pending ?? 0,
28176
- sent: row?.sent ?? 0,
28177
- skipped: row?.skipped ?? 0,
28178
- capturesSkipped: captures?.skipped ?? 0
28179
- };
28180
- }
28181
- /**
28182
- * The deployment the current stamps were made against, and where its backlog
28183
- * ends.
28184
- *
28185
- * READ-ONLY. An absent row reads as an absent deployment, which is what a
28186
- * machine that has never drained is — and every writer below seeds the row
28187
- * before it needs one, so nothing depends on this creating it. Keeping the
28188
- * write off the gate path matters because the gate runs on every pass while a
28189
- * write has to take the database's write lock.
28190
- */
28191
- deployment() {
28192
- const row = getRow(
28193
- this.fingerprintStmt
28194
- );
28195
- return {
28196
- fingerprint: row?.fingerprint ?? void 0,
28197
- backlogBefore: row?.backlogBefore ?? void 0
28198
- };
28199
- }
28200
- /**
28201
- * Point the ledger at a different deployment, discarding what it recorded
28202
- * about the previous one.
28203
- *
28204
- * Delivery is a fact about ONE recipient: rows sent to the deployment a
28205
- * machine has just left are undelivered as far as the new one is concerned.
28206
- * All four in one transaction, so a crash between them cannot leave stamps
28207
- * attributed to the wrong deployment, a boundary that belongs to another, or
28208
- * a disown with no re-mark to follow it.
28209
- *
28210
- * The boundary is written HERE and only here, which is what freezes it: a
28211
- * re-attach to the SAME deployment (a key rotation) leaves the fingerprint
28212
- * unchanged, so this never runs and the backlog does not widen back over rows
28213
- * the live path has since delivered.
28214
- *
28215
- * `backfillCapturesBefore` is the caller's OWN "now" at the instant a human
28216
- * granted existing-history consent for the deployment this call is arming —
28217
- * a DIFFERENT instant from `backlogBefore`: the re-mark boundary is the GRANT
28218
- * instant, `backlogBefore` is the ATTACH instant, and the two can be far
28219
- * apart. Passed only when that grant is valid, since this method has no way
28220
- * to check consent itself and must not mark a row owed for a machine that
28221
- * never agreed to it. Applied AFTER the disown above, in the SAME
28222
- * transaction: what the disown clears is every marker below `backlogBefore`,
28223
- * which includes this deployment's OWN pre-attach rows — `aka attach` calls
28224
- * `seedCaptureBacklogOwed` at the attach instant, so every row it marks sits
28225
- * on the cleared side of that bound — and the re-mark in the same
28226
- * transaction is what puts those rows back. A crash between the two cannot
28227
- * strand the ledger disowned with nothing re-marked — the transaction either
28228
- * lands whole or not at all, and a fingerprint mismatch that has not yet
28229
- * committed re-enters this method on the very next pass. Omit it (the
28230
- * structural-only tests do) to exercise the disown in isolation.
28231
- *
28232
- * The disown is bounded by `backlogBefore`, which is what keeps it from
28233
- * touching a marker the NEW deployment's OWN live path has already set: B's
28234
- * live path can mark a capture owed from the moment `aka attach` writes the
28235
- * descriptor, before the drain's first pass ever reaches this method, and
28236
- * such a row sits at or after the bound rather than below it. What keeps the
28237
- * disown from eating THIS SAME CALL's own re-mark is the order, not the
28238
- * bound — disown runs first, re-mark second, both inside the one
28239
- * transaction above.
28240
- */
28241
- rearmFor(fingerprint, backlogBefore, backfillCapturesBefore) {
28242
- this.ensureRowStmt.run();
28243
- withTransaction(
28244
- this.db,
28245
- () => {
28246
- const previous = getRow(this.fingerprintStmt)?.fingerprint;
28247
- this.rearmStmt.run();
28248
- if (previous !== null && previous !== void 0 && previous !== fingerprint) {
28249
- this.disownCapturesStmt.run({ attachedAt: backlogBefore });
28250
- }
28251
- if (backfillCapturesBefore !== void 0) {
28252
- this.markCaptureBacklogOwedStmt.run({ before: backfillCapturesBefore });
28253
- }
28254
- this.setFingerprintStmt.run({ fingerprint, backlogBefore });
28255
- },
28256
- "IMMEDIATE"
28257
- );
28258
- }
28259
- /**
28260
- * End the attached period: hand its rows to the live path, and release the
28261
- * boundary so the next attachment can freeze a new one.
28262
- *
28263
- * WITHOUT THIS, a detach and a re-attach to the same deployment leave a window
28264
- * nothing delivers. The fingerprint is unchanged, so the boundary is never
28265
- * re-frozen and stays at the FIRST attachment — while nothing forwards at all
28266
- * during the detached period, because the machine is not attached. Rows
28267
- * recorded in that window sit after the boundary and before the re-attach, so
28268
- * neither path takes them, and the pending count reports none outstanding.
28269
- *
28270
- * Stamping the attached window is not a claim that every one of those rows
28271
- * reached the deployment — the live path drops on failure and says so
28272
- * elsewhere. It records that they were ITS to deliver, which is exactly the
28273
- * status quo: they sit outside the frozen boundary today and are equally never
28274
- * re-sent. Making it explicit is what lets the boundary move.
28275
- *
28276
- * ONE TRANSACTION, so a crash cannot release the boundary while leaving the
28277
- * window unstamped — that half-state would re-send the whole attached period
28278
- * on the next attach, which is the failure the boundary exists to prevent.
28279
- */
28280
- closeAttachedWindow(attachedAtMs, atMs) {
28281
- this.ensureRowStmt.run();
28282
- withTransaction(
28283
- this.db,
28284
- () => {
28285
- const row = getRow(this.fingerprintStmt);
28286
- const from = row?.backlogBefore ?? attachedAtMs;
28287
- this.closeWindowStmt.run({ at: atMs, attachedAt: from });
28288
- this.releaseBoundaryStmt.run();
28289
- },
28290
- "IMMEDIATE"
28291
- );
28292
- }
28293
- /**
28294
- * Freeze a boundary for the deployment already on file, KEEPING the stamps.
28295
- *
28296
- * The re-attach half of the above. Distinct from `rearmFor`, which is for a
28297
- * different deployment and therefore discards what was delivered to the old
28298
- * one: here the recipient is the same, so everything already sent to it stays
28299
- * sent.
28300
- */
28301
- freezeBoundary(backlogBefore) {
28302
- this.ensureRowStmt.run();
28303
- this.freezeBoundaryStmt.run({ backlogBefore });
28304
- }
28305
- /** Take the claim, or report that someone live already holds it. */
28306
- claim(pid, host, nowMs, staleAfterMs) {
28307
- this.ensureRowStmt.run();
28308
- let taken = false;
28309
- withTransaction(
28310
- this.db,
28311
- () => {
28312
- const result = this.claimStmt.run({
28313
- pid,
28314
- host,
28315
- now: nowMs,
28316
- staleBefore: nowMs - staleAfterMs
28317
- });
28318
- taken = result.changes === 1;
28319
- },
28320
- "IMMEDIATE"
28321
- );
28322
- return taken;
28323
- }
28324
- /** Say the holder is still alive. A no-op once the claim has moved on. */
28325
- heartbeat(pid, nowMs) {
28326
- this.heartbeatStmt.run({ now: nowMs, pid });
28327
- }
28328
- /** Give the claim up. Scoped to this holder, so a taken-over claim is left be. */
28329
- release(pid) {
28330
- this.releaseStmt.run({ pid });
28331
- }
28332
- /** Who holds the claim, if anyone. Read-only, for the same reason as above. */
28333
- lease() {
28334
- return getRow(this.leaseStmt);
28335
- }
28336
- };
28337
-
28338
28943
  // ../../packages/persistence/src/repositories/inspection-definitions.ts
28339
28944
  var SqliteInspectionDefinitionsRepository = class {
28340
28945
  constructor(db) {
@@ -28562,6 +29167,7 @@ function overlayManagedSettings(settings, managed, now = () => /* @__PURE__ */ n
28562
29167
  if (values.vaultInlineReveal !== void 0) merged.vaultInlineReveal = values.vaultInlineReveal;
28563
29168
  if (values.dataSharesInPlace !== void 0) merged.dataSharesInPlace = values.dataSharesInPlace;
28564
29169
  if (values.redactFallback !== void 0) merged.redactFallback = values.redactFallback;
29170
+ if (values.bodyRetention !== void 0) merged.bodyRetention = values.bodyRetention;
28565
29171
  if (values.vaultConsent !== void 0) {
28566
29172
  merged.vaultConsent = values.vaultConsent ? (
28567
29173
  // Keep an existing valid grant so its acknowledgedAt survives; mint one
@@ -31069,7 +31675,7 @@ var SqliteSecurityRepository = class {
31069
31675
  ELSE 0
31070
31676
  END) AS open_at_rest
31071
31677
  FROM inspection_findings f
31072
- JOIN audit_events e ON e.id = f.audit_event_id
31678
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31073
31679
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
31074
31680
  LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
31075
31681
  ON latest.finding_key = f.finding_key
@@ -31295,7 +31901,7 @@ var SqliteSecurityRepository = class {
31295
31901
  this.db.prepare(
31296
31902
  `SELECT e.repo AS repo, count(*) AS c
31297
31903
  FROM inspection_findings f
31298
- JOIN audit_events e ON e.id = f.audit_event_id
31904
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31299
31905
  WHERE e.started_at >= :from AND e.started_at < :to
31300
31906
  AND e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
31301
31907
  AND e.repo IS NOT NULL
@@ -31419,7 +32025,7 @@ var SqliteSecurityRepository = class {
31419
32025
  d.severity AS severity,
31420
32026
  COUNT(*) AS count
31421
32027
  FROM inspection_findings f
31422
- JOIN audit_events e ON e.id = f.audit_event_id
32028
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31423
32029
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
31424
32030
  LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
31425
32031
  ON latest.finding_key = f.finding_key
@@ -31454,7 +32060,7 @@ var SqliteSecurityRepository = class {
31454
32060
  `SELECT e.started_at AS occurred_at, d.severity AS severity, f.action_taken AS action_taken,
31455
32061
  d.rule_id AS rule_id, d.category AS category
31456
32062
  FROM inspection_findings f
31457
- JOIN audit_events e ON e.id = f.audit_event_id
32063
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31458
32064
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
31459
32065
  WHERE e.started_at >= :from AND e.started_at < :to
31460
32066
  AND e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
@@ -32295,6 +32901,7 @@ function openWithPragmas(file2) {
32295
32901
  db.exec("PRAGMA journal_mode = WAL");
32296
32902
  db.exec("PRAGMA busy_timeout = 2000");
32297
32903
  db.exec("PRAGMA foreign_keys = ON");
32904
+ registerSqlFunctions(db);
32298
32905
  } catch (err) {
32299
32906
  closeQuietly(db);
32300
32907
  throw err;
@@ -32324,7 +32931,7 @@ function backupLegacyStore(db, file2) {
32324
32931
  discardStore(file2, backup);
32325
32932
  return backup;
32326
32933
  }
32327
- function openAndInitialize(file2, base) {
32934
+ function openAndInitialize(file2, base, skipTags) {
32328
32935
  let db = openWithPragmas(file2);
32329
32936
  try {
32330
32937
  if (isForeignSqliteLineage(db)) {
@@ -32334,7 +32941,7 @@ function openAndInitialize(file2, base) {
32334
32941
  `Detected an older, incompatible (tenant-bearing) ${DB_FILENAME}; backed it up to ${backup} and created a fresh store.`
32335
32942
  );
32336
32943
  }
32337
- applyMigrations(db, file2);
32944
+ applyMigrations(db, file2, { skipTags });
32338
32945
  tightenPerms(file2);
32339
32946
  const policies = new SqlitePoliciesRepository(db);
32340
32947
  const installedPacks = new SqliteInstalledPacksRepository(db, base);
@@ -32349,6 +32956,7 @@ function openAndInitialize(file2, base) {
32349
32956
  exceptions: new SqliteExceptionsRepository(db),
32350
32957
  resolutions: new SqliteResolutionsRepository(db),
32351
32958
  ruleProbeCache: new SqliteRuleProbeCacheRepository(db),
32959
+ bodyRetention: new SqliteBodyRetentionRepository(db),
32352
32960
  security: new SqliteSecurityRepository(db),
32353
32961
  detections: new SqliteDetectionsRepository(db),
32354
32962
  shares: new SqliteSharesRepository(db),
@@ -32371,7 +32979,8 @@ function openAndInitialize(file2, base) {
32371
32979
  throw err;
32372
32980
  }
32373
32981
  }
32374
- function openLocalDatabase(dir) {
32982
+ var DEFERRED_TAGS = new Set(DEFERRED_MIGRATION_TAGS);
32983
+ function openLocalDatabase(dir, options = {}) {
32375
32984
  ensureDataDirSync(dir);
32376
32985
  const file2 = join7(dir, DB_FILENAME);
32377
32986
  reapStalePartials(file2);
@@ -32383,6 +32992,7 @@ function openLocalDatabase(dir) {
32383
32992
  installedPacks,
32384
32993
  scanLedger,
32385
32994
  historySync,
32995
+ bodyRetention,
32386
32996
  secretVault,
32387
32997
  exceptions,
32388
32998
  resolutions,
@@ -32406,7 +33016,8 @@ function openLocalDatabase(dir) {
32406
33016
  // `dir` is always `<base>/data` — every caller resolves it through
32407
33017
  // `dataDir()` — so its parent is the `~/.aka` base the layout splits into
32408
33018
  // settings/ and data/, and the pack-policy floor needs both halves.
32409
- dirname2(dir)
33019
+ dirname2(dir),
33020
+ options.applyDeferredMigrations === true ? void 0 : DEFERRED_TAGS
32410
33021
  );
32411
33022
  function captureRowId(event) {
32412
33023
  return captureId(
@@ -32599,6 +33210,7 @@ function openLocalDatabase(dir) {
32599
33210
  installedPacks,
32600
33211
  scanLedger,
32601
33212
  historySync,
33213
+ bodyRetention,
32602
33214
  secretVault,
32603
33215
  exceptions,
32604
33216
  resolutions,
@@ -32639,8 +33251,35 @@ function openLocalDatabase(dir) {
32639
33251
 
32640
33252
  // ../../packages/persistence/src/egress-wire.ts
32641
33253
  import { createHash as createHash3 } from "crypto";
33254
+ var PROJECT_KEY_DIGEST_VERSION = "v2";
33255
+ var SCP_FORM = /^(?:[^@/]+@)?([^/:]+):(.+)$/;
33256
+ var DOS_DRIVE = /^[A-Za-z]:[\\/]/;
33257
+ var FILE_URL = /^file:\/\//i;
33258
+ var SCHEME_FORM = /^[a-z][a-z0-9+.-]*:\/\/(?:[^@/]+@)?([^/:]+)(?::\d+)?(\/.*)?$/i;
33259
+ var SLASH = "/".charCodeAt(0);
33260
+ var GIT_SUFFIX = ".git";
33261
+ function trimSlashes(path) {
33262
+ let start = 0;
33263
+ let end = path.length;
33264
+ while (start < end && path.charCodeAt(start) === SLASH) start += 1;
33265
+ while (end > start && path.charCodeAt(end - 1) === SLASH) end -= 1;
33266
+ return path.slice(start, end);
33267
+ }
33268
+ function canonicalGitUrl(url2) {
33269
+ const trimmed = url2.trim();
33270
+ if (DOS_DRIVE.test(trimmed) || FILE_URL.test(trimmed)) return trimmed;
33271
+ const scheme = SCHEME_FORM.exec(trimmed);
33272
+ const scp = scheme === null ? SCP_FORM.exec(trimmed) : null;
33273
+ const host = (scheme?.[1] ?? scp?.[1])?.toLowerCase();
33274
+ if (host === void 0) return trimmed;
33275
+ const path = (scheme === null ? scp?.[2] : scheme[2]) ?? "";
33276
+ const bare = trimSlashes(path);
33277
+ const cleaned = bare.endsWith(GIT_SUFFIX) ? bare.slice(0, -GIT_SUFFIX.length) : bare;
33278
+ return cleaned === "" ? host : `${host}/${cleaned}`;
33279
+ }
32642
33280
  function hashProjectKey(projectKey) {
32643
- return createHash3("sha256").update(projectKey, "utf8").digest("hex");
33281
+ const canonical = projectKey.startsWith("git:") ? `git:${canonicalGitUrl(projectKey.slice("git:".length))}` : projectKey;
33282
+ return createHash3("sha256").update(`${PROJECT_KEY_DIGEST_VERSION}:${canonical}`, "utf8").digest("hex");
32644
33283
  }
32645
33284
  function toIngestHit(hit) {
32646
33285
  return {
@@ -32716,18 +33355,50 @@ function readFingerprintKey(dataDir2) {
32716
33355
  return parseKeyFile(raw);
32717
33356
  }
32718
33357
 
33358
+ // ../../packages/persistence/src/forward-health.ts
33359
+ import { readFileSync as readFileSync7 } from "fs";
33360
+ import { join as join9 } from "path";
33361
+ var FAILURES = /* @__PURE__ */ new Set([
33362
+ "unauthorized",
33363
+ "forbidden",
33364
+ "unreachable"
33365
+ ]);
33366
+ var BREAKER_COOLDOWN_MS = 3e4;
33367
+ function parseForwardHealth(raw, nowMs) {
33368
+ try {
33369
+ const parsed2 = JSON.parse(raw);
33370
+ if (typeof parsed2 !== "object" || parsed2 === null) return null;
33371
+ const record2 = parsed2;
33372
+ const failures = typeof record2.consecutiveFailures === "number" && record2.consecutiveFailures >= 0 ? record2.consecutiveFailures : 0;
33373
+ const openedAtMs = typeof record2.openedAtMs === "number" && Number.isFinite(record2.openedAtMs) && record2.openedAtMs <= nowMs ? record2.openedAtMs : null;
33374
+ const lastFailure = typeof record2.lastFailure === "string" && FAILURES.has(record2.lastFailure) ? record2.lastFailure : null;
33375
+ return { consecutiveFailures: failures, openedAtMs, lastFailure };
33376
+ } catch {
33377
+ return null;
33378
+ }
33379
+ }
33380
+ function isForwardPaused(health, nowMs) {
33381
+ const openedAtMs = health?.openedAtMs ?? null;
33382
+ if (openedAtMs === null) return false;
33383
+ return nowMs - openedAtMs < BREAKER_COOLDOWN_MS;
33384
+ }
33385
+
32719
33386
  // ../../packages/persistence/src/history-backfill.ts
32720
33387
  import { existsSync as existsSync4 } from "fs";
32721
- import { join as join9 } from "path";
33388
+ import { join as join10 } from "path";
32722
33389
 
32723
33390
  // ../../packages/persistence/src/history-preview.ts
32724
33391
  import { existsSync as existsSync5 } from "fs";
32725
- import { join as join10 } from "path";
33392
+ import { join as join11 } from "path";
32726
33393
  import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
32727
33394
 
33395
+ // ../../packages/persistence/src/history-sync-state.ts
33396
+ import { readFileSync as readFileSync8 } from "fs";
33397
+ import { join as join12 } from "path";
33398
+
32728
33399
  // ../../packages/persistence/src/store-symlinks.ts
32729
33400
  import { existsSync as existsSync6, lstatSync as lstatSync3, readlinkSync, realpathSync, statSync as statSync4 } from "fs";
32730
- import { dirname as dirname3, join as join11, resolve } from "path";
33401
+ import { dirname as dirname3, join as join13, resolve } from "path";
32731
33402
 
32732
33403
  // ../../packages/persistence/src/vault/crypto.ts
32733
33404
  import {
@@ -32741,19 +33412,19 @@ import {
32741
33412
  // ../../packages/persistence/src/vault/key-provider.ts
32742
33413
  import { execFileSync } from "child_process";
32743
33414
  import { randomBytes as randomBytes2 } from "crypto";
32744
- import { chmodSync as chmodSync3, readFileSync as readFileSync7, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
32745
- import { join as join12 } from "path";
33415
+ import { chmodSync as chmodSync3, readFileSync as readFileSync9, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
33416
+ import { join as join14 } from "path";
32746
33417
 
32747
33418
  // ../../packages/persistence/src/vault/vault.ts
32748
33419
  import { randomBytes as randomBytes3, randomUUID as randomUUID12 } from "crypto";
32749
33420
 
32750
33421
  // ../../packages/persistence/src/warn-era-cap.ts
32751
33422
  import { existsSync as existsSync7, writeFileSync as writeFileSync4 } from "fs";
32752
- import { join as join13 } from "path";
33423
+ import { join as join15 } from "path";
32753
33424
  var MARKER = "warn-era-capped";
32754
33425
  function capWarnEraEnforcementOnce(db, policyMode, dataDir2) {
32755
33426
  if (policyMode !== "warn") return { capped: 0, skipped: "not-warn" };
32756
- const marker = join13(dataDir2, MARKER);
33427
+ const marker = join15(dataDir2, MARKER);
32757
33428
  if (existsSync7(marker)) return { capped: 0, skipped: "already-run" };
32758
33429
  const capped = db.policies.capCategoryActions();
32759
33430
  writeFileSync4(marker, `${new Date(Date.now()).toISOString()}
@@ -32944,10 +33615,10 @@ function parsed(schema, body, route) {
32944
33615
  }
32945
33616
  function withoutTrailingSlashes(endpoint) {
32946
33617
  let end = endpoint.length;
32947
- while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH) end -= 1;
33618
+ while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH2) end -= 1;
32948
33619
  return endpoint.slice(0, end);
32949
33620
  }
32950
- var SLASH = "/".charCodeAt(0);
33621
+ var SLASH2 = "/".charCodeAt(0);
32951
33622
  function createRemoteClient(options) {
32952
33623
  const base = withoutTrailingSlashes(options.endpoint);
32953
33624
  const url2 = (route) => `${base}${route}`;
@@ -33129,11 +33800,11 @@ function withTimeout(promise2, ms) {
33129
33800
  }
33130
33801
 
33131
33802
  // ../../packages/plugin-runtime/src/attached/forward-drops.ts
33132
- import { readFileSync as readFileSync8 } from "fs";
33133
- import { join as join14 } from "path";
33803
+ import { readFileSync as readFileSync10 } from "fs";
33804
+ import { join as join16 } from "path";
33134
33805
  var FORWARD_DROPS_FILENAME = ATTACHED_FORWARD_DROPS_FILENAME;
33135
33806
  function forwardDropsPath(dataDir2) {
33136
- return join14(dataDir2, FORWARD_DROPS_FILENAME);
33807
+ return join16(dataDir2, FORWARD_DROPS_FILENAME);
33137
33808
  }
33138
33809
  function recordForwardDrops(dataDir2, count, nowMs) {
33139
33810
  if (count <= 0) return;
@@ -33151,7 +33822,7 @@ function recordForwardDrops(dataDir2, count, nowMs) {
33151
33822
  }
33152
33823
  function readForwardDrops(dataDir2) {
33153
33824
  try {
33154
- const parsed2 = JSON.parse(readFileSync8(forwardDropsPath(dataDir2), "utf8"));
33825
+ const parsed2 = JSON.parse(readFileSync10(forwardDropsPath(dataDir2), "utf8"));
33155
33826
  if (typeof parsed2 !== "object" || parsed2 === null) return null;
33156
33827
  const record2 = parsed2;
33157
33828
  if (typeof record2.droppedForwards !== "number" || !Number.isFinite(record2.droppedForwards)) {
@@ -33169,13 +33840,12 @@ function readForwardDrops(dataDir2) {
33169
33840
 
33170
33841
  // ../../packages/plugin-runtime/src/attached/forward-policy.ts
33171
33842
  import { randomUUID as randomUUID15 } from "crypto";
33172
- import { readFileSync as readFileSync15 } from "fs";
33173
33843
  import { readFile, rename, writeFile } from "fs/promises";
33174
- import { join as join24 } from "path";
33844
+ import { join as join26 } from "path";
33175
33845
 
33176
33846
  // ../../packages/plugin-sdk/src/config.ts
33177
33847
  import { existsSync as existsSync8 } from "fs";
33178
- import { join as join15 } from "path";
33848
+ import { join as join17 } from "path";
33179
33849
 
33180
33850
  // ../../packages/plugin-sdk/src/provider-env.ts
33181
33851
  var DEFAULT_ANTHROPIC_HOST = "api.anthropic.com";
@@ -33229,7 +33899,7 @@ function resolveProvider() {
33229
33899
  function loadConfig(base = defaultDataDir(), resolveProviderFn = resolveProvider) {
33230
33900
  try {
33231
33901
  ensureLayoutDirSync(base);
33232
- const settingsFile = join15(settingsDir(base), "settings.json");
33902
+ const settingsFile = join17(settingsDir(base), "settings.json");
33233
33903
  if (existsSync8(settingsFile)) tightenFile(settingsFile);
33234
33904
  } catch {
33235
33905
  }
@@ -33253,9 +33923,9 @@ function resolveProviderSafe(resolveProviderFn) {
33253
33923
  }
33254
33924
 
33255
33925
  // ../../packages/plugin-sdk/src/config-inventory.ts
33256
- import { readdirSync as readdirSync2, readFileSync as readFileSync10, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
33926
+ import { readdirSync as readdirSync2, readFileSync as readFileSync12, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
33257
33927
  import { homedir as homedir2 } from "os";
33258
- import { basename as basename3, join as join17 } from "path";
33928
+ import { basename as basename3, join as join19 } from "path";
33259
33929
 
33260
33930
  // ../../packages/detections/src/egress/registry.ts
33261
33931
  var EXTRACTOR_VERSION = "1";
@@ -36038,8 +36708,8 @@ function bundledDetections() {
36038
36708
  }
36039
36709
 
36040
36710
  // ../../packages/plugin-sdk/src/repo.ts
36041
- import { existsSync as existsSync9, readFileSync as readFileSync9, statSync as statSync6 } from "fs";
36042
- import { basename as basename2, dirname as dirname4, isAbsolute, join as join16, sep as sep2 } from "path";
36711
+ import { existsSync as existsSync9, readFileSync as readFileSync11, statSync as statSync6 } from "fs";
36712
+ import { basename as basename2, dirname as dirname4, isAbsolute, join as join18, sep as sep2 } from "path";
36043
36713
 
36044
36714
  // ../../packages/plugin-sdk/src/events.ts
36045
36715
  import { createHash as createHash5, randomUUID as randomUUID13 } from "crypto";
@@ -36050,8 +36720,8 @@ import { fileURLToPath } from "url";
36050
36720
  import { Worker } from "worker_threads";
36051
36721
 
36052
36722
  // ../../packages/plugin-sdk/src/host-floor.ts
36053
- import { readFileSync as readFileSync12 } from "fs";
36054
- import { join as join19 } from "path";
36723
+ import { readFileSync as readFileSync14 } from "fs";
36724
+ import { join as join21 } from "path";
36055
36725
 
36056
36726
  // ../../packages/plugin-sdk/src/model-governance.ts
36057
36727
  import {
@@ -36059,11 +36729,11 @@ import {
36059
36729
  fstatSync,
36060
36730
  mkdirSync as mkdirSync2,
36061
36731
  openSync as openSync2,
36062
- readFileSync as readFileSync11,
36732
+ readFileSync as readFileSync13,
36063
36733
  readSync,
36064
36734
  writeFileSync as writeFileSync5
36065
36735
  } from "fs";
36066
- import { join as join18 } from "path";
36736
+ import { join as join20 } from "path";
36067
36737
  var TAIL_BYTES = 256 * 1024;
36068
36738
 
36069
36739
  // ../../packages/plugin-sdk/src/host-floor.ts
@@ -36122,7 +36792,7 @@ function hostCompatibilityLines(cache) {
36122
36792
  var HOST_VERSION_MARKER = "host-version.json";
36123
36793
  function readHostVersionCache(dataDir2) {
36124
36794
  try {
36125
- const parsed2 = JSON.parse(readFileSync12(join19(dataDir2, HOST_VERSION_MARKER), "utf8"));
36795
+ const parsed2 = JSON.parse(readFileSync14(join21(dataDir2, HOST_VERSION_MARKER), "utf8"));
36126
36796
  if (typeof parsed2 !== "object" || parsed2 === null) return null;
36127
36797
  const { version: version2, observedAt } = parsed2;
36128
36798
  if (typeof version2 !== "string" || !isParseableBinaryVersion(version2)) return null;
@@ -36135,15 +36805,15 @@ function readHostVersionCache(dataDir2) {
36135
36805
 
36136
36806
  // ../../packages/plugin-sdk/src/ignore-layers.ts
36137
36807
  var import_ignore = __toESM(require_ignore(), 1);
36138
- import { readFileSync as readFileSync13 } from "fs";
36139
- import { join as join20 } from "path";
36808
+ import { readFileSync as readFileSync15 } from "fs";
36809
+ import { join as join22 } from "path";
36140
36810
 
36141
36811
  // ../../packages/plugin-sdk/src/inventory-resolver.ts
36142
36812
  import { arch, hostname as hostname4, platform, release } from "os";
36143
36813
 
36144
36814
  // ../../packages/plugin-sdk/src/nudge.ts
36145
- import { mkdirSync as mkdirSync3, readFileSync as readFileSync14, writeFileSync as writeFileSync6 } from "fs";
36146
- import { join as join21 } from "path";
36815
+ import { mkdirSync as mkdirSync3, readFileSync as readFileSync16, writeFileSync as writeFileSync6 } from "fs";
36816
+ import { join as join23 } from "path";
36147
36817
 
36148
36818
  // ../../packages/plugin-sdk/src/paths.ts
36149
36819
  import { readdirSync as readdirSync3, realpathSync as realpathSync3 } from "fs";
@@ -36151,7 +36821,7 @@ import { basename as basename4, dirname as dirname5, sep as sep3 } from "path";
36151
36821
 
36152
36822
  // ../../packages/plugin-sdk/src/project-files.ts
36153
36823
  import { existsSync as existsSync11, readdirSync as readdirSync4 } from "fs";
36154
- import { basename as basename5, join as join22 } from "path";
36824
+ import { basename as basename5, join as join24 } from "path";
36155
36825
 
36156
36826
  // ../../packages/plugin-sdk/src/provider-env-antigravity.ts
36157
36827
  var optionalBaseUrl2 = external_exports.preprocess((v) => {
@@ -36187,7 +36857,7 @@ var THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1e3;
36187
36857
 
36188
36858
  // ../../packages/plugin-sdk/src/throttle.ts
36189
36859
  import { mkdirSync as mkdirSync4, statSync as statSync8, writeFileSync as writeFileSync7 } from "fs";
36190
- import { join as join23 } from "path";
36860
+ import { join as join25 } from "path";
36191
36861
 
36192
36862
  // ../../packages/plugin-runtime/src/attached/forward-policy.ts
36193
36863
  function isInvalidRequest(err) {
@@ -36203,31 +36873,12 @@ function isServerRejection(err) {
36203
36873
  var FORWARD_BUDGET_MS = 1500;
36204
36874
  var DECISION_PATH_BUDGET_MS = 800;
36205
36875
  var BREAKER_FAILURE_THRESHOLD = 3;
36206
- var BREAKER_COOLDOWN_MS = 3e4;
36207
36876
  var CLOSED = { consecutiveFailures: 0, openedAtMs: null, lastFailure: null };
36208
- var FAILURES = /* @__PURE__ */ new Set([
36209
- "unauthorized",
36210
- "forbidden",
36211
- "unreachable"
36212
- ]);
36213
36877
  var FORWARD_STATE_FILENAME = ATTACHED_FORWARD_STATE_FILENAME;
36214
36878
  var STATE_FILENAME = FORWARD_STATE_FILENAME;
36215
- function parseBreakerState(raw, nowMs) {
36216
- try {
36217
- const parsed2 = JSON.parse(raw);
36218
- if (typeof parsed2 !== "object" || parsed2 === null) return null;
36219
- const record2 = parsed2;
36220
- const failures = typeof record2.consecutiveFailures === "number" && record2.consecutiveFailures >= 0 ? record2.consecutiveFailures : 0;
36221
- const openedAtMs = typeof record2.openedAtMs === "number" && Number.isFinite(record2.openedAtMs) && record2.openedAtMs <= nowMs ? record2.openedAtMs : null;
36222
- const lastFailure = typeof record2.lastFailure === "string" && FAILURES.has(record2.lastFailure) ? record2.lastFailure : null;
36223
- return { consecutiveFailures: failures, openedAtMs, lastFailure };
36224
- } catch {
36225
- return null;
36226
- }
36227
- }
36228
36879
  function createForwardPolicy(deps) {
36229
36880
  const now = deps.now ?? (() => Date.now());
36230
- const file2 = join24(deps.dir, STATE_FILENAME);
36881
+ const file2 = join26(deps.dir, STATE_FILENAME);
36231
36882
  let state = null;
36232
36883
  let loading = null;
36233
36884
  async function readState() {
@@ -36237,7 +36888,7 @@ function createForwardPolicy(deps) {
36237
36888
  } catch {
36238
36889
  return { ...CLOSED };
36239
36890
  }
36240
- return parseBreakerState(raw, now()) ?? { ...CLOSED };
36891
+ return parseForwardHealth(raw, now()) ?? { ...CLOSED };
36241
36892
  }
36242
36893
  async function load() {
36243
36894
  if (state !== null) return state;
@@ -36283,7 +36934,7 @@ function createForwardPolicy(deps) {
36283
36934
  };
36284
36935
  const at = now();
36285
36936
  if (current.openedAtMs !== null) {
36286
- if (at - current.openedAtMs < BREAKER_COOLDOWN_MS) {
36937
+ if (isForwardPaused(current, at)) {
36287
36938
  return { ok: false, reason: "breaker-open" };
36288
36939
  }
36289
36940
  await persist({
@@ -36820,7 +37471,18 @@ var AttachedDataGateway = class {
36820
37471
  // and the spread above would otherwise drop the field silently — which is
36821
37472
  // exactly what it did, leaving the whole control inert on every device
36822
37473
  // while every test around it stayed green.
36823
- prohibitedModels: cached2.prohibitedModels
37474
+ prohibitedModels: cached2.prohibitedModels,
37475
+ // NAMED for the same reason as the line above, and it is the same defect
37476
+ // if it is not: `...local` above spreads the DEVICE's bundle, so a field
37477
+ // only the cache carries is dropped in silence. That is what left
37478
+ // `prohibitedModels` inert on every attached device with every test
37479
+ // around it green.
37480
+ //
37481
+ // Taken from the cache rather than merged here, because merging it needs
37482
+ // the device's own SETTING — which is not a bundle field and is not in
37483
+ // scope at this seam. The runtime does that merge, raise-only, where both
37484
+ // values are in hand (createPluginRuntime's ensureInitialized).
37485
+ redactFallback: cached2.redactFallback
36824
37486
  // ALSO HONOURED FROM THE CACHE, and not a bundle field at all: each
36825
37487
  // merged policy's own `provenance`. `mergeRaiseOnly` spreads the policies
36826
37488
  // it emits, so an 'authored' policy arriving from the control plane
@@ -36948,10 +37610,6 @@ function toolAuditEvent(input2) {
36948
37610
  };
36949
37611
  }
36950
37612
 
36951
- // ../../packages/plugin-runtime/src/attached/history-state.ts
36952
- import { readFileSync as readFileSync16 } from "fs";
36953
- import { join as join25 } from "path";
36954
-
36955
37613
  // ../../packages/plugin-runtime/src/attached/history-sync.ts
36956
37614
  import { createHash as createHash6 } from "crypto";
36957
37615
  import { hostname as hostname5 } from "os";
@@ -36960,6 +37618,10 @@ import { hostname as hostname5 } from "os";
36960
37618
  var CORRELATION_ID = EventMetadata.shape.correlationId;
36961
37619
  var TRACE_ID = EventMetadata.shape.traceId;
36962
37620
  var EXCEPTION_ID = EventMetadata.shape.exceptionIds.unwrap().element;
37621
+ var REDACT_DEGRADED_TO = EventMetadata.shape.redactDegradedTo.unwrap();
37622
+
37623
+ // ../../packages/plugin-runtime/src/attached/history-sync.ts
37624
+ var CAPTURE_BATCH_BYTES = 1024 * 1024;
36963
37625
 
36964
37626
  // ../../packages/plugin-runtime/src/attached/history-sync-trigger.ts
36965
37627
  import { spawn } from "child_process";
@@ -36986,7 +37648,7 @@ function createPluginBlock(build, policyStore) {
36986
37648
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
36987
37649
  import { randomUUID as randomUUID16 } from "crypto";
36988
37650
  import { readFile as readFile2, rm, writeFile as writeFile2 } from "fs/promises";
36989
- import { join as join26 } from "path";
37651
+ import { join as join27 } from "path";
36990
37652
 
36991
37653
  // ../../packages/plugin-runtime/src/attached/atomic-publish.ts
36992
37654
  import { rename as rename2 } from "fs/promises";
@@ -37010,7 +37672,7 @@ async function publishByRename(tmp, file2, move = rename2) {
37010
37672
 
37011
37673
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
37012
37674
  function createPolicyStore(dir = dataDir()) {
37013
- const file2 = join26(dir, "policy-cache.json");
37675
+ const file2 = join27(dir, "policy-cache.json");
37014
37676
  async function read() {
37015
37677
  try {
37016
37678
  const raw = await readFile2(file2, "utf8");
@@ -37241,11 +37903,11 @@ function readStorePosture(dbPath2) {
37241
37903
  // ../../packages/plugin-runtime/src/attached/posture-store.ts
37242
37904
  import { randomUUID as randomUUID17 } from "crypto";
37243
37905
  import { readFile as readFile3, rm as rm2, writeFile as writeFile3 } from "fs/promises";
37244
- import { join as join27 } from "path";
37906
+ import { join as join28 } from "path";
37245
37907
  var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
37246
37908
  function createPostureStore(dir = settingsDir(), legacyDir) {
37247
- const file2 = join27(dir, "posture-state.json");
37248
- const legacyFile = legacyDir === void 0 ? null : join27(legacyDir, "posture-state.json");
37909
+ const file2 = join28(dir, "posture-state.json");
37910
+ const legacyFile = legacyDir === void 0 ? null : join28(legacyDir, "posture-state.json");
37249
37911
  async function persist(state) {
37250
37912
  await ensureDataDir(dir);
37251
37913
  const tmp = `${file2}.${randomUUID17()}.tmp`;
@@ -37314,7 +37976,7 @@ function createPostureStore(dir = settingsDir(), legacyDir) {
37314
37976
 
37315
37977
  // ../../packages/plugin-runtime/src/attached/sync-state.ts
37316
37978
  import { readFileSync as readFileSync18 } from "fs";
37317
- import { join as join28 } from "path";
37979
+ import { join as join29 } from "path";
37318
37980
 
37319
37981
  // ../../packages/plugin-runtime/src/attached/status.ts
37320
37982
  var REFUSAL_LINES = {
@@ -37335,6 +37997,14 @@ import { spawn as spawn2 } from "child_process";
37335
37997
  import { fileURLToPath as fileURLToPath3 } from "url";
37336
37998
  var SYNC_THROTTLE_MS = 15 * 60 * 1e3;
37337
37999
 
38000
+ // ../../packages/plugin-runtime/src/content-retention-pass.ts
38001
+ var MAX_ROWS_PER_SWEEP = 50 * 1e3;
38002
+
38003
+ // ../../packages/plugin-runtime/src/content-retention-trigger.ts
38004
+ import { spawn as spawn3 } from "child_process";
38005
+ import { fileURLToPath as fileURLToPath4 } from "url";
38006
+ var CONTENT_RETENTION_THROTTLE_MS = 60 * 60 * 1e3;
38007
+
37338
38008
  // ../../packages/plugin-runtime/src/attached/factory.ts
37339
38009
  import { hostname as hostname6 } from "os";
37340
38010
 
@@ -37902,7 +38572,7 @@ function fenced(body) {
37902
38572
 
37903
38573
  // ../../packages/setup-wizard/src/remediation/rotation-checklist.ts
37904
38574
  import { writeFileSync as writeFileSync8 } from "fs";
37905
- import { join as join29 } from "path";
38575
+ import { join as join30 } from "path";
37906
38576
 
37907
38577
  // ../../packages/setup-wizard/src/triage/merge.ts
37908
38578
  var RANK = Object.fromEntries(
@@ -37912,7 +38582,7 @@ var RANK = Object.fromEntries(
37912
38582
  // ../../packages/setup-wizard/src/triage/plan-file.ts
37913
38583
  import { mkdtempSync, readFileSync as readFileSync19, rmdirSync, rmSync as rmSync7, writeFileSync as writeFileSync9 } from "fs";
37914
38584
  import { tmpdir } from "os";
37915
- import { basename as basename6, dirname as dirname6, join as join30 } from "path";
38585
+ import { basename as basename6, dirname as dirname6, join as join31 } from "path";
37916
38586
  var SuppressionEntrySchema = external_exports.object({
37917
38587
  ruleId: external_exports.string(),
37918
38588
  category: DetectionCategory,
@@ -37955,8 +38625,8 @@ var PersistedPlanSchema = external_exports.object({
37955
38625
 
37956
38626
  // src/command-registry.ts
37957
38627
  import { readdirSync as readdirSync5 } from "fs";
37958
- import { fileURLToPath as fileURLToPath4 } from "url";
37959
- var COMMANDS_DIR = fileURLToPath4(new URL("../commands", import.meta.url));
38628
+ import { fileURLToPath as fileURLToPath5 } from "url";
38629
+ var COMMANDS_DIR = fileURLToPath5(new URL("../commands", import.meta.url));
37960
38630
 
37961
38631
  // src/render.ts
37962
38632
  var SEVERITY_GLYPH = {
@@ -38066,7 +38736,9 @@ function renderHealth(r) {
38066
38736
  );
38067
38737
  lines.push(indent(`${String(r.weekFindings)} findings in the last 7 days`));
38068
38738
  lines.push("");
38069
- lines.push(indent(`Run /recommend to review ${String(r.recommendCount)} prioritized actions.`));
38739
+ lines.push(
38740
+ indent(`Run /aka:recommend to review ${String(r.recommendCount)} prioritized actions.`)
38741
+ );
38070
38742
  lines.push("");
38071
38743
  lines.push(
38072
38744
  indent(
@@ -38140,7 +38812,7 @@ function renderRecommend(recs, status) {
38140
38812
  lines.push("", indent(`${REC_BODY_INDENT}${r.context} \u2192 ${r.action}`), "");
38141
38813
  });
38142
38814
  lines.push(
38143
- indent("Run /recommend <n> to act on one, or /health for the summary."),
38815
+ indent("Run /aka:recommend <n> to act on one, or /aka:health for the summary."),
38144
38816
  "",
38145
38817
  indent(renderStatusBar(status))
38146
38818
  );