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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -50,7 +50,7 @@ var require_ignore = __commonJS({
50
50
  var REGEX_SPLITALL_CRLF = /\r?\n/g;
51
51
  var REGEX_TEST_INVALID_PATH = /^\.{0,2}\/|^\.{1,2}$/;
52
52
  var REGEX_TEST_TRAILING_SLASH = /\/$/;
53
- var SLASH2 = "/";
53
+ var SLASH3 = "/";
54
54
  var TMP_KEY_IGNORE = "node-ignore";
55
55
  if (typeof Symbol !== "undefined") {
56
56
  TMP_KEY_IGNORE = /* @__PURE__ */ Symbol.for("node-ignore");
@@ -422,11 +422,11 @@ var require_ignore = __commonJS({
422
422
  if (!REGEX_TEST_TRAILING_SLASH.test(path)) {
423
423
  return this.test(path);
424
424
  }
425
- const slices = path.split(SLASH2).filter(Boolean);
425
+ const slices = path.split(SLASH3).filter(Boolean);
426
426
  slices.pop();
427
427
  if (slices.length) {
428
428
  const parent = this._t(
429
- slices.join(SLASH2) + SLASH2,
429
+ slices.join(SLASH3) + SLASH3,
430
430
  this._testCache,
431
431
  true,
432
432
  slices
@@ -442,14 +442,14 @@ var require_ignore = __commonJS({
442
442
  return cache[path];
443
443
  }
444
444
  if (!slices) {
445
- slices = path.split(SLASH2).filter(Boolean);
445
+ slices = path.split(SLASH3).filter(Boolean);
446
446
  }
447
447
  slices.pop();
448
448
  if (!slices.length) {
449
449
  return cache[path] = this._rules.test(path, checkUnignored, MODE_IGNORE);
450
450
  }
451
451
  const parent = this._t(
452
- slices.join(SLASH2) + SLASH2,
452
+ slices.join(SLASH3) + SLASH3,
453
453
  cache,
454
454
  checkUnignored,
455
455
  slices
@@ -492,7 +492,7 @@ var require_ignore = __commonJS({
492
492
  });
493
493
 
494
494
  // src/backfill.ts
495
- import { fileURLToPath as fileURLToPath4 } from "url";
495
+ import { fileURLToPath as fileURLToPath5 } from "url";
496
496
 
497
497
  // ../../packages/persistence/src/attached-derived.ts
498
498
  import { rmSync } from "fs";
@@ -505,6 +505,14 @@ var ATTACHED_FORWARD_DROPS_FILENAME = "attached-forward-drops.json";
505
505
  import { chmodSync as chmodSync2, lstatSync as lstatSync2, readFileSync, rmSync as rmSync3, statSync } from "fs";
506
506
  import { join as join2 } from "path";
507
507
 
508
+ // ../../packages/schema/src/drizzle/deferred-migrations.ts
509
+ var DEFERRED_MIGRATION_TAGS = [
510
+ "0031_audit_capture_by_time_index",
511
+ "0032_audit_capture_by_id_index",
512
+ "0033_audit_capture_location_index",
513
+ "0034_findings_read_indexes"
514
+ ];
515
+
508
516
  // ../../packages/schema/src/drizzle/sqlite-ddl.ts
509
517
  var SQLITE_MIGRATIONS = [
510
518
  {
@@ -622,6 +630,30 @@ var SQLITE_MIGRATIONS = [
622
630
  {
623
631
  tag: "0028_activity_session_probe_indexes",
624
632
  sql: "CREATE INDEX `idx_audit_session_prompt` ON `audit_events` (`root_session_id`) WHERE event_type = 'prompt';--> statement-breakpoint\nCREATE INDEX `idx_audit_session_share` ON `audit_events` (`root_session_id`) WHERE event_type = 'share';--> statement-breakpoint\nCREATE INDEX `idx_audit_ended_at` ON `audit_events` (`ended_at`,`root_session_id`) WHERE ended_at IS NOT NULL;--> statement-breakpoint\nCREATE INDEX `idx_audit_session_ended` ON `audit_events` (`root_session_id`,`ended_at`) WHERE ended_at IS NOT NULL;--> statement-breakpoint\n-- Expression index for the activity list's turns rollup: a live-captured\n-- session's turns are the DISTINCT `run_key` across its `llm_call` leaves, and\n-- carrying the extracted key in the index answers that count from the index\n-- alone instead of parsing every leaf's attribute bag. Written by hand, as\n-- 0013's `idx_audit_code_change_path` was: drizzle-kit cannot emit an\n-- expression containing a comma, so this index is not declared in sqlite.ts.\nCREATE INDEX `idx_audit_session_run_key` ON `audit_events` (`root_session_id`, json_extract(`attributes`, '$.run_key')) WHERE `event_type` = 'llm_call';\n"
633
+ },
634
+ {
635
+ tag: "0029_audit_capture_rollup_index",
636
+ sql: "CREATE INDEX `idx_audit_capture_rollup` ON `audit_events` (`event_type`,`started_at`,`repo`,`id`) WHERE event_type IN ('prompt','response','code_change','tool_use');"
637
+ },
638
+ {
639
+ tag: "0030_audit_content_expiry",
640
+ sql: "ALTER TABLE `audit_events` ADD `content_expired_at` integer;--> statement-breakpoint\nCREATE INDEX `idx_audit_expirable_body` ON `audit_events` (`started_at`) WHERE content IS NOT NULL;"
641
+ },
642
+ {
643
+ tag: "0031_audit_capture_by_time_index",
644
+ sql: "CREATE INDEX `idx_audit_capture_by_time` ON `audit_events` (`started_at`,`id`,`event_type`,`root_session_id`,`source_tool`,`repo`,`file_path`,`tool_name`) WHERE event_type IN ('prompt','response','code_change','tool_use');"
645
+ },
646
+ {
647
+ tag: "0032_audit_capture_by_id_index",
648
+ sql: "CREATE INDEX `idx_audit_capture_by_id` ON `audit_events` (`id`,`started_at`,`event_type`,`root_session_id`,`source_tool`,`repo`,`file_path`,`tool_name`) WHERE event_type IN ('prompt','response','code_change','tool_use');"
649
+ },
650
+ {
651
+ tag: "0033_audit_capture_location_index",
652
+ sql: "CREATE INDEX `idx_audit_capture_location` ON `audit_events` (`repo`,`file_path`,`started_at`,`id`,`event_type`) WHERE event_type IN ('prompt','response','code_change','tool_use');"
653
+ },
654
+ {
655
+ tag: "0034_findings_read_indexes",
656
+ sql: "CREATE INDEX `idx_inspection_definitions_rule` ON `inspection_definitions` (`rule_id`,`severity`,`category`);--> statement-breakpoint\nCREATE INDEX `idx_inspection_findings_def` ON `inspection_findings` (`inspection_definition_id`,`audit_event_id`);--> statement-breakpoint\nCREATE INDEX `idx_inspection_findings_event_cover` ON `inspection_findings` (`audit_event_id`,`inspection_definition_id`,`action_taken`,`finding_key`,`id`);"
625
657
  }
626
658
  ];
627
659
 
@@ -20622,7 +20654,7 @@ var TOOL_TO_HARNESS = {
20622
20654
  [SOURCE_TOOL.ClaudeAi]: HARNESS.ClaudeAi
20623
20655
  };
20624
20656
  function harnessFromTool(tool) {
20625
- return TOOL_TO_HARNESS[tool] ?? tool;
20657
+ return (Object.hasOwn(TOOL_TO_HARNESS, tool) ? TOOL_TO_HARNESS[tool] : void 0) ?? tool;
20626
20658
  }
20627
20659
 
20628
20660
  // ../../packages/schema/src/zod/finding.ts
@@ -20672,6 +20704,15 @@ var FindingCategory = external_exports.enum([
20672
20704
  ]).meta({ id: "FindingCategory" });
20673
20705
  var FindingOrigin = external_exports.enum(["in-flight", "at-rest"]).meta({ id: "FindingOrigin" });
20674
20706
  var FindingStatus = external_exports.enum(["open", "handled", "resolved", "dismissed"]).meta({ id: "FindingStatus" });
20707
+ var SyncFailureReason = external_exports.enum(["deployment_refused", "payload_invalid", "detached_undelivered"]).meta({ id: "SyncFailureReason" });
20708
+ var FindingDeliveryState = external_exports.enum(["sent", "queued", "not_sent", "never_offered", "local_scan"]).meta({ id: "FindingDeliveryState" });
20709
+ var FindingDelivery = external_exports.object({
20710
+ state: FindingDeliveryState,
20711
+ // The delivery time for `sent`; the failure time for `not_sent` when recorded.
20712
+ at: external_exports.iso.datetime().optional(),
20713
+ // Only on `not_sent`, and only when a known reason was recorded.
20714
+ reason: SyncFailureReason.optional()
20715
+ }).meta({ id: "FindingDelivery" });
20675
20716
  var ResolutionMethod = external_exports.enum([
20676
20717
  "enforced-in-flight",
20677
20718
  "fixed-at-source",
@@ -20728,7 +20769,10 @@ var FindingInstance = external_exports.object({
20728
20769
  // The session that event belongs to, when it has one — the seam a
20729
20770
  // per-instance "view session" link needs. Absent for events captured
20730
20771
  // outside a session.
20731
- sessionId: external_exports.string().optional()
20772
+ sessionId: external_exports.string().optional(),
20773
+ // The delivery state of the event above (see FindingDelivery). Optional so
20774
+ // readers that do not project it stay valid.
20775
+ delivery: FindingDelivery.optional()
20732
20776
  }).meta({ id: "FindingInstance" });
20733
20777
  var FindingGroup = external_exports.object({
20734
20778
  id: external_exports.string(),
@@ -20780,7 +20824,10 @@ var FindingFacets = external_exports.object({
20780
20824
  // Host tool (attributes.tool_name). Present only on the instance-level
20781
20825
  // reads, which can filter by it; the type-level read omits the dimension
20782
20826
  // because a group spans tools.
20783
- tool: external_exports.array(FindingFacetItem).optional()
20827
+ tool: external_exports.array(FindingFacetItem).optional(),
20828
+ // Delivery states (FindingDeliveryState). Present only on the
20829
+ // instance-level reads, like `tool`.
20830
+ deployment: external_exports.array(FindingFacetItem).optional()
20784
20831
  }).meta({ id: "FindingFacets" });
20785
20832
  var FindingTypeSummary = FindingGroup.omit({ instances: true, match: true }).meta({
20786
20833
  id: "FindingTypeSummary"
@@ -20891,6 +20938,8 @@ var ListFindingInstancesQuery = external_exports.object({
20891
20938
  // Exact host-tool names (attributes.tool_name, e.g. 'Bash'). A real filter,
20892
20939
  // where the free-text `q` can only match the rendered "via Bash" label.
20893
20940
  tool: external_exports.array(external_exports.string()).optional(),
20941
+ // The delivery state of each finding's event (see FindingDelivery).
20942
+ deployment: external_exports.array(FindingDeliveryState).optional(),
20894
20943
  // Exact repository / file-path matches, for the drill-down out of the
20895
20944
  // locations view. A row whose event carries no repo/file matches neither.
20896
20945
  repo: external_exports.string().optional(),
@@ -20911,6 +20960,10 @@ var ListFindingInstancesResponse = external_exports.object({
20911
20960
  items: external_exports.array(FindingInstanceDetail),
20912
20961
  nextCursor: external_exports.string().nullable()
20913
20962
  }).meta({ id: "ListFindingInstancesResponse" });
20963
+ var ListFindingInstancesPage = external_exports.object({
20964
+ items: external_exports.array(FindingInstanceDetail),
20965
+ nextCursor: external_exports.string().nullable()
20966
+ }).meta({ id: "ListFindingInstancesPage" });
20914
20967
  var FindingLocationSummary = external_exports.object({
20915
20968
  // Opaque, stable, minted from the pair by encodeLocationId. It exists
20916
20969
  // because a location's identity is two values and a URL param carries one:
@@ -20953,6 +21006,8 @@ var ListFindingLocationsQuery = external_exports.object({
20953
21006
  // instances that match, and folds its status from those.
20954
21007
  status: external_exports.array(FindingStatus).optional(),
20955
21008
  tool: external_exports.array(external_exports.string()).optional(),
21009
+ // The delivery state of each finding's event (see FindingDelivery).
21010
+ deployment: external_exports.array(FindingDeliveryState).optional(),
20956
21011
  q: external_exports.string().optional(),
20957
21012
  sessionId: external_exports.string().optional(),
20958
21013
  from: external_exports.iso.datetime().optional(),
@@ -21155,6 +21210,10 @@ var CaptureAttributes = external_exports.object({
21155
21210
  // to 'allow' — the enforcement audit trail's link back to the grant that
21156
21211
  // authorized the bypass.
21157
21212
  exception_ids: external_exports.array(external_exports.guid()).optional(),
21213
+ // The persisted spellings of EventMetadata's messageId/conversationId — the
21214
+ // join back to the `llm_call` leaf for the same assistant turn.
21215
+ message_id: external_exports.string().optional(),
21216
+ conversation_id: external_exports.string().optional(),
21158
21217
  // Whole milliseconds this capture's inspection blocked its caller — the
21159
21218
  // plugin's own added latency (see EventMetadata.inspectionMs, whose value
21160
21219
  // this is). Promoted to the `inspection_ms` generated column so the facet is
@@ -21163,7 +21222,19 @@ var CaptureAttributes = external_exports.object({
21163
21222
  // inline json_extract and is not itself an optimization.
21164
21223
  // ABSENT on replayed captures (backfill / worktree scan) and on rows written
21165
21224
  // before the measurement shipped — never present as a placeholder 0.
21166
- inspection_ms: external_exports.number().int().nonnegative().optional()
21225
+ inspection_ms: external_exports.number().int().nonnegative().optional(),
21226
+ // What a `redact` this capture could not carry out became instead (see
21227
+ // EventMetadata.redactDegradedTo, whose value this is). Present only when a
21228
+ // degrade actually happened, so absence is the ordinary case rather than a
21229
+ // reader having to distinguish it from a zero.
21230
+ //
21231
+ // PER CAPTURE, while `inspection_findings.action_taken` is per finding —
21232
+ // so on a multi-finding row this does not say which finding degraded, and
21233
+ // its presence does not mean the fallback decided the capture's action. A
21234
+ // capture denied by another finding's own Block policy carries `block`
21235
+ // here too. The full statement is on EventMetadata.redactDegradedTo; it is
21236
+ // repeated rather than referenced because a store reader opens this file.
21237
+ redact_degraded_to: ActionTaken.optional()
21167
21238
  }).catchall(external_exports.unknown());
21168
21239
  var ToolCallInspection = external_exports.object({
21169
21240
  ruleId: external_exports.string().min(1),
@@ -21362,7 +21433,17 @@ var AuditEvent = external_exports.object({
21362
21433
  /** `share` to a first-party/internal destination. */
21363
21434
  internal: external_exports.boolean(),
21364
21435
  /** Event needs review (e.g. unverified egress). */
21365
- flagged: external_exports.boolean()
21436
+ flagged: external_exports.boolean(),
21437
+ /**
21438
+ * The body this event's `title` is drawn from was cleared by local body
21439
+ * expiry, so an EMPTY title here means "gone", not "never had one".
21440
+ *
21441
+ * A separate flag rather than a sentinel written into `title`: the title is
21442
+ * rendered text, and a store-layer module that invented display copy for it
21443
+ * would be choosing words the view is supposed to choose. Additive and
21444
+ * defaulted, so an older producer still validates.
21445
+ */
21446
+ bodyExpired: external_exports.boolean().default(false)
21366
21447
  }).meta({ id: "ActivityAuditEvent" });
21367
21448
  var ActivitySessionSummary = external_exports.object({
21368
21449
  id: external_exports.string(),
@@ -22703,6 +22784,12 @@ var EventMetadata = external_exports.object({
22703
22784
  // to 'allow' — the enforcement audit trail's link back to the grant that
22704
22785
  // authorized the bypass. Absent on captures where no exception applied.
22705
22786
  exceptionIds: external_exports.array(external_exports.guid()).optional(),
22787
+ // The assistant message this capture belongs to, and the conversation it sits
22788
+ // in — set by the browser extension's network capture so a stored `response`
22789
+ // row can be joined to the `llm_call` leaf describing the same turn. Absent
22790
+ // on every other capture path, which has no such id.
22791
+ messageId: external_exports.string().optional(),
22792
+ conversationId: external_exports.string().optional(),
22706
22793
  // How long THIS capture's inspection blocked its caller, in whole
22707
22794
  // milliseconds — the plugin's own added latency, NOT the LLM call it sat in
22708
22795
  // front of. Measured inside `capture()` (@akasecurity/plugin-sdk) across
@@ -22715,7 +22802,37 @@ var EventMetadata = external_exports.object({
22715
22802
  // Absent is also what every pre-measurement client writes, and what a
22716
22803
  // clock failure degrades to — a reader must treat absence as "not measured"
22717
22804
  // and never as a zero, which would read as "inspection is free".
22718
- inspectionMs: external_exports.number().int().nonnegative().optional()
22805
+ inspectionMs: external_exports.number().int().nonnegative().optional(),
22806
+ // What a `redact` this capture COULD NOT CARRY OUT became instead — the
22807
+ // workspace's `redactFallback`, applied because the field could not be
22808
+ // masked in place (a shell command, a URL, or any argument on a host whose
22809
+ // hook contract offers no rewrite channel).
22810
+ //
22811
+ // It exists because the action alone cannot say why. A finding recorded as
22812
+ // `warn` reads identically whether its detection was ASSIGNED Warn or was
22813
+ // assigned Redact on a field that could not take one — and those are
22814
+ // different facts about the same row: the first is a policy the user chose,
22815
+ // the second is a masking the host could not perform. Absent means no
22816
+ // degrade happened, which is every ordinary capture.
22817
+ //
22818
+ // TWO LIMITS a reader of a stored row has to know, because the grain here
22819
+ // is the CAPTURE while `actionTaken` is per FINDING:
22820
+ //
22821
+ // - It does not say WHICH finding degraded. A capture carrying a degraded
22822
+ // `redact` alongside a finding ASSIGNED the same action stores both
22823
+ // identically and one reason for the pair; attributing it to both
22824
+ // describes the assigned one wrongly, and to neither loses the degrade.
22825
+ // - PRESENCE IS NOT CAUSATION. The value is the action the lost redact
22826
+ // became, not the reason the capture ended as it did — a capture denied
22827
+ // by some other finding's own Block policy still carries `block` here,
22828
+ // and clearing the workspace's fallback would not have let it through.
22829
+ // Gate on the value against what a fallback can produce; never read the
22830
+ // field's presence as "this was the fallback's doing".
22831
+ //
22832
+ // Both are pinned as behaviour in @akasecurity/plugin-sdk's runtime suite.
22833
+ // Closing either means moving the reason onto the finding row, which
22834
+ // already carries its own action.
22835
+ redactDegradedTo: ActionTaken.optional()
22719
22836
  }).meta({ id: "EventMetadata" });
22720
22837
  var Event = external_exports.object({
22721
22838
  id: external_exports.guid(),
@@ -22825,7 +22942,32 @@ var RotateKeyInput = external_exports.object({
22825
22942
  confirmation: external_exports.string()
22826
22943
  });
22827
22944
 
22945
+ // ../../packages/schema/src/zod/finding-delivery.ts
22946
+ var KNOWN_REASONS = SyncFailureReason.options;
22947
+ function knownReason(value) {
22948
+ return value !== null && KNOWN_REASONS.includes(value) ? value : void 0;
22949
+ }
22950
+ function deriveFindingDelivery(row) {
22951
+ if (row.kind === "code_change") return { state: "local_scan" };
22952
+ if (row.syncedAt !== null && row.syncedAt > 0) {
22953
+ return { state: "sent", at: epochMillisToIso(row.syncedAt) };
22954
+ }
22955
+ if (row.syncedAt !== null) {
22956
+ const reason = knownReason(row.syncFailure);
22957
+ return {
22958
+ state: "not_sent",
22959
+ ...row.syncFailedAt === null ? {} : { at: epochMillisToIso(row.syncFailedAt) },
22960
+ ...reason === void 0 ? {} : { reason }
22961
+ };
22962
+ }
22963
+ if (row.outboxOwed === 1 || row.syncClaimedAt !== null) return { state: "queued" };
22964
+ return { state: "never_offered" };
22965
+ }
22966
+
22828
22967
  // ../../packages/schema/src/zod/findings-group-build.ts
22968
+ function lookupOwn(map2, key) {
22969
+ return Object.hasOwn(map2, key) ? map2[key] : void 0;
22970
+ }
22829
22971
  function toApiAction(dbVal) {
22830
22972
  const map2 = {
22831
22973
  log: "monitored",
@@ -22834,7 +22976,7 @@ function toApiAction(dbVal) {
22834
22976
  warn: "warned",
22835
22977
  allow: "allowed"
22836
22978
  };
22837
- return map2[dbVal] ?? "allowed";
22979
+ return lookupOwn(map2, dbVal) ?? "allowed";
22838
22980
  }
22839
22981
  function toApiCategory(dbVal) {
22840
22982
  if (dbVal === "code_context") return "source_code";
@@ -22842,13 +22984,18 @@ function toApiCategory(dbVal) {
22842
22984
  return parsed2.success ? parsed2.data : "custom";
22843
22985
  }
22844
22986
  function toApiProvider(sourceTool) {
22845
- return TOOL_TO_HARNESS[sourceTool] ?? HARNESS.Api;
22987
+ return lookupOwn(TOOL_TO_HARNESS, sourceTool) ?? HARNESS.Api;
22846
22988
  }
22847
- var STATUS_PRECEDENCE = ["open", "handled", "dismissed", "resolved"];
22989
+ var FINDING_STATUS_PRECEDENCE = [
22990
+ "open",
22991
+ "handled",
22992
+ "dismissed",
22993
+ "resolved"
22994
+ ];
22848
22995
  function foldGroupStatus(instanceStatuses) {
22849
22996
  const statuses = new Set(instanceStatuses.filter((s) => s !== void 0));
22850
22997
  if (statuses.size === 0) return void 0;
22851
- for (const candidate of STATUS_PRECEDENCE) {
22998
+ for (const candidate of FINDING_STATUS_PRECEDENCE) {
22852
22999
  if (statuses.has(candidate)) return candidate;
22853
23000
  }
22854
23001
  return void 0;
@@ -22955,11 +23102,16 @@ function applyFindingFilters(types, opts) {
22955
23102
  }
22956
23103
  return filtered;
22957
23104
  }
22958
- var SEVERITY_ORDER = { critical: 0, high: 1, medium: 2, low: 3 };
22959
- var SEVERITY_RANK = SEVERITY_ORDER;
23105
+ function rankByOrder(members2) {
23106
+ return Object.fromEntries(members2.map((member, index) => [member, index]));
23107
+ }
23108
+ var SEVERITY_RANK = rankByOrder(Severity.options);
23109
+ function severityRank(severity) {
23110
+ return lookupOwn(SEVERITY_RANK, severity);
23111
+ }
22960
23112
  function compareFindingGroupOrder(a, b) {
22961
- const rankA = SEVERITY_RANK[a.severity] ?? -1;
22962
- const rankB = SEVERITY_RANK[b.severity] ?? -1;
23113
+ const rankA = severityRank(a.severity) ?? -1;
23114
+ const rankB = severityRank(b.severity) ?? -1;
22963
23115
  const severityDiff = rankA - rankB;
22964
23116
  if (severityDiff !== 0) return severityDiff;
22965
23117
  const recencyDiff = b.latestDetectedAt.localeCompare(a.latestDetectedAt);
@@ -23034,6 +23186,20 @@ function computeFindingFacets(allTypes, opts) {
23034
23186
  }
23035
23187
 
23036
23188
  // ../../packages/schema/src/zod/findings-flat-build.ts
23189
+ function compareCodePoints(a, b) {
23190
+ const aIter = a[Symbol.iterator]();
23191
+ const bIter = b[Symbol.iterator]();
23192
+ for (; ; ) {
23193
+ const aNext = aIter.next();
23194
+ const bNext = bIter.next();
23195
+ if (aNext.done && bNext.done) return 0;
23196
+ if (aNext.done) return -1;
23197
+ if (bNext.done) return 1;
23198
+ const aPoint = aNext.value.codePointAt(0) ?? 0;
23199
+ const bPoint = bNext.value.codePointAt(0) ?? 0;
23200
+ if (aPoint !== bPoint) return aPoint - bPoint;
23201
+ }
23202
+ }
23037
23203
  function rowHaystack(row) {
23038
23204
  return [
23039
23205
  row.ruleId,
@@ -23058,6 +23224,8 @@ function matchesDimension(row, opts, dimension) {
23058
23224
  return !opts.actions?.length || opts.actions.includes(toApiAction(row.actionTaken));
23059
23225
  case "statuses":
23060
23226
  return !opts.statuses?.length || row.status !== void 0 && opts.statuses.includes(row.status);
23227
+ case "deliveries":
23228
+ return !opts.deliveries?.length || row.delivery !== void 0 && opts.deliveries.includes(row.delivery.state);
23061
23229
  case "tools":
23062
23230
  return !opts.tools?.length || row.toolName !== void 0 && opts.tools.includes(row.toolName);
23063
23231
  // An EMPTY value is a real filter here, not an absent one. The location
@@ -23084,6 +23252,7 @@ var DIMENSIONS = [
23084
23252
  "providers",
23085
23253
  "actions",
23086
23254
  "statuses",
23255
+ "deliveries",
23087
23256
  "tools",
23088
23257
  "repo",
23089
23258
  "file",
@@ -23097,10 +23266,19 @@ function matchesInstanceFilters(row, opts, except) {
23097
23266
  return true;
23098
23267
  }
23099
23268
  function toItems(counts) {
23100
- return [...counts.entries()].map(([value, count]) => ({ value, count })).sort((a, b) => b.count - a.count || a.value.localeCompare(b.value));
23269
+ return [...counts.entries()].map(([value, count]) => ({ value, count })).sort(
23270
+ (a, b) => b.count - a.count || a.value.localeCompare(b.value) || // localeCompare reports canonically-equivalent strings (an NFC and an
23271
+ // NFD spelling of the same text) as equal, so a count tie between
23272
+ // them would otherwise be ordered by whichever the Map iteration
23273
+ // produced. compareCodePoints breaks that tie deterministically, which
23274
+ // makes this a TOTAL order — not one that agrees with SQL collation,
23275
+ // which it need not: foldFacetTuples runs this same sort over grouped
23276
+ // tuples, so both paths order facets identically by construction.
23277
+ compareCodePoints(a.value, b.value)
23278
+ );
23101
23279
  }
23102
- function bump(counts, value) {
23103
- counts.set(value, (counts.get(value) ?? 0) + 1);
23280
+ function bump(counts, value, by = 1) {
23281
+ counts.set(value, (counts.get(value) ?? 0) + by);
23104
23282
  }
23105
23283
  function createInstanceFacetAccumulator(opts) {
23106
23284
  const severity = /* @__PURE__ */ new Map();
@@ -23109,6 +23287,7 @@ function createInstanceFacetAccumulator(opts) {
23109
23287
  const action = /* @__PURE__ */ new Map();
23110
23288
  const status = /* @__PURE__ */ new Map();
23111
23289
  const tool = /* @__PURE__ */ new Map();
23290
+ const deployment = /* @__PURE__ */ new Map();
23112
23291
  return {
23113
23292
  add(row) {
23114
23293
  if (matchesInstanceFilters(row, opts, "severity")) bump(severity, row.severity);
@@ -23123,6 +23302,9 @@ function createInstanceFacetAccumulator(opts) {
23123
23302
  if (row.toolName !== void 0 && matchesInstanceFilters(row, opts, "tools")) {
23124
23303
  bump(tool, row.toolName);
23125
23304
  }
23305
+ if (row.delivery !== void 0 && matchesInstanceFilters(row, opts, "deliveries")) {
23306
+ bump(deployment, row.delivery.state);
23307
+ }
23126
23308
  },
23127
23309
  facets: () => ({
23128
23310
  severity: toItems(severity),
@@ -23130,7 +23312,8 @@ function createInstanceFacetAccumulator(opts) {
23130
23312
  provider: toItems(provider),
23131
23313
  action: toItems(action),
23132
23314
  status: toItems(status),
23133
- tool: toItems(tool)
23315
+ tool: toItems(tool),
23316
+ deployment: toItems(deployment)
23134
23317
  })
23135
23318
  };
23136
23319
  }
@@ -23144,6 +23327,7 @@ function toInstanceDetail(row) {
23144
23327
  ...row.toolName === void 0 ? {} : { toolName: row.toolName },
23145
23328
  eventId: row.eventId,
23146
23329
  ...row.sessionId === void 0 ? {} : { sessionId: row.sessionId },
23330
+ ...row.delivery === void 0 ? {} : { delivery: row.delivery },
23147
23331
  ...row.user === void 0 ? {} : { user: row.user },
23148
23332
  action: toApiAction(row.actionTaken),
23149
23333
  detectedAt: row.occurredAt,
@@ -23158,12 +23342,6 @@ function toInstanceDetail(row) {
23158
23342
  policy: { id: `category:${category}`, name: category }
23159
23343
  };
23160
23344
  }
23161
- var SEVERITY_ORDER2 = {
23162
- critical: 0,
23163
- high: 1,
23164
- medium: 2,
23165
- low: 3
23166
- };
23167
23345
  function newLocationAccumulator() {
23168
23346
  return {
23169
23347
  instanceCount: 0,
@@ -23178,7 +23356,7 @@ function newLocationAccumulator() {
23178
23356
  }
23179
23357
  function addToLocation(acc, row) {
23180
23358
  acc.instanceCount += 1;
23181
- const rank = SEVERITY_ORDER2[row.severity] ?? Number.MAX_SAFE_INTEGER - 1;
23359
+ const rank = severityRank(row.severity) ?? Number.MAX_SAFE_INTEGER - 1;
23182
23360
  if (rank < acc.maxSeverityRank) {
23183
23361
  acc.maxSeverityRank = rank;
23184
23362
  acc.maxSeverity = row.severity;
@@ -23188,15 +23366,15 @@ function addToLocation(acc, row) {
23188
23366
  acc.ruleIds.add(row.ruleId);
23189
23367
  }
23190
23368
  function compareLocationOrder(a, b) {
23191
- const rankA = SEVERITY_ORDER2[a.maxSeverity] ?? -1;
23192
- const rankB = SEVERITY_ORDER2[b.maxSeverity] ?? -1;
23369
+ const rankA = severityRank(a.maxSeverity) ?? -1;
23370
+ const rankB = severityRank(b.maxSeverity) ?? -1;
23193
23371
  if (rankA !== rankB) return rankA - rankB;
23194
23372
  if (a.latestDetectedAt !== b.latestDetectedAt) {
23195
23373
  return a.latestDetectedAt < b.latestDetectedAt ? 1 : -1;
23196
23374
  }
23197
- if (a.repo !== b.repo) return a.repo < b.repo ? -1 : 1;
23198
- if (a.file !== b.file) return a.file < b.file ? -1 : 1;
23199
- return 0;
23375
+ const repoDiff = compareCodePoints(a.repo, b.repo);
23376
+ if (repoDiff !== 0) return repoDiff;
23377
+ return compareCodePoints(a.file, b.file);
23200
23378
  }
23201
23379
  function encodeLocationId(repo, file2) {
23202
23380
  return `${encodePart(repo)}/${encodePart(file2)}`;
@@ -23271,6 +23449,11 @@ var Policy = external_exports.object({
23271
23449
  // test `prohibitedModels` passes and `reversibleRuleIds` fails.
23272
23450
  provenance: PolicyProvenance.optional()
23273
23451
  }).meta({ id: "Policy" });
23452
+ var KNOWN_BUILTIN_IDS = ["monitor", "warn", "redact", "vault", "block"];
23453
+ var BuiltinPolicyId = external_exports.enum(KNOWN_BUILTIN_IDS).meta({ id: "BuiltinPolicyId" });
23454
+ var RedactFallback = BuiltinPolicyId.extract(["monitor", "warn", "block"]).meta({
23455
+ id: "RedactFallback"
23456
+ });
23274
23457
  var PolicyBundle = external_exports.object({
23275
23458
  version: external_exports.string(),
23276
23459
  policies: external_exports.array(Policy),
@@ -23318,6 +23501,16 @@ var PolicyBundle = external_exports.object({
23318
23501
  // control plane), so no name resolution stands between the decision and the
23319
23502
  // comparison.
23320
23503
  prohibitedModels: external_exports.array(external_exports.string()).optional(),
23504
+ // What a resolved `redact` becomes on a field the host cannot rewrite, as
23505
+ // the ORGANIZATION would have it. Merged raise-only against the device's own
23506
+ // `WorkspaceSettings.redactFallback` (see strongerRedactFallback below), so
23507
+ // a control plane can tighten a machine and never loosen one — the same
23508
+ // direction `mergeRaiseOnly` enforces for policies.
23509
+ //
23510
+ // Optional so an older backend, and an older on-disk cache, still parses;
23511
+ // absent leaves the device's own setting in force, which is the behaviour
23512
+ // that predates the field and the safe direction to default.
23513
+ redactFallback: RedactFallback.optional(),
23321
23514
  customKeywords: external_exports.array(external_exports.string()),
23322
23515
  fetchedAt: external_exports.iso.datetime()
23323
23516
  }).meta({ id: "PolicyBundle" });
@@ -23347,11 +23540,6 @@ function severityFloorPolicy(category) {
23347
23540
  const peak = CATEGORY_PEAK_SEVERITY[category];
23348
23541
  return peak === "critical" || peak === "high" ? "warn" : "monitor";
23349
23542
  }
23350
- var KNOWN_BUILTIN_IDS = ["monitor", "warn", "redact", "vault", "block"];
23351
- var BuiltinPolicyId = external_exports.enum(KNOWN_BUILTIN_IDS).meta({ id: "BuiltinPolicyId" });
23352
- var RedactFallback = BuiltinPolicyId.extract(["monitor", "warn", "block"]).meta({
23353
- id: "RedactFallback"
23354
- });
23355
23543
  var BUILTIN_ORDER = KNOWN_BUILTIN_IDS;
23356
23544
  var BUILTIN_POLICY_SPECS = {
23357
23545
  monitor: {
@@ -23407,6 +23595,11 @@ function isActionAtLeast(action, floor) {
23407
23595
  function strongerAction(a, b) {
23408
23596
  return actionRank(a) >= actionRank(b) ? a : b;
23409
23597
  }
23598
+ function strongerRedactFallback(local, remote) {
23599
+ if (remote === void 0) return local;
23600
+ const localAction = builtinPolicyToAction(local);
23601
+ return localAction === strongerAction(localAction, builtinPolicyToAction(remote)) ? local : remote;
23602
+ }
23410
23603
  function weakestBuiltinAtLeast(floor) {
23411
23604
  return KNOWN_BUILTIN_IDS.find((id) => isActionAtLeast(builtinPolicyToAction(id), floor)) ?? "block";
23412
23605
  }
@@ -23654,7 +23847,7 @@ function isVaultConsentValid(consent) {
23654
23847
  }
23655
23848
 
23656
23849
  // ../../packages/schema/src/zod/local.ts
23657
- var WORKSPACE_SETTINGS_SPEC_VERSION = 7;
23850
+ var WORKSPACE_SETTINGS_SPEC_VERSION = 8;
23658
23851
  var MODEL_JUDGE_PAYLOAD_VERSION = 1;
23659
23852
  var RunMode = external_exports.enum(["standalone", "attached"]);
23660
23853
  var ControlPlaneConnection = external_exports.object({
@@ -23674,6 +23867,15 @@ var HistorySyncConsent = external_exports.object({
23674
23867
  payloadVersion: external_exports.number().int().positive(),
23675
23868
  endpoint: external_exports.string()
23676
23869
  });
23870
+ var BODY_RETENTION_DEFAULT_DAYS = 30;
23871
+ var BodyRetention = external_exports.object({
23872
+ enabled: external_exports.boolean().default(false),
23873
+ // Never 0, and the ceiling is a fat-finger guard rather than a policy
23874
+ // limit — `enabled` is the real gate. A low value cannot reach a row the
23875
+ // sync ledger still owes: the sweep's age filter only ever NARROWS a
23876
+ // candidate set that is already bounded by "delivered, or never owed".
23877
+ retainDays: external_exports.number().int().min(1).max(3650).default(BODY_RETENTION_DEFAULT_DAYS)
23878
+ }).meta({ id: "BodyRetention" });
23677
23879
  var WorkspaceSettings = external_exports.object({
23678
23880
  specVersion: external_exports.number().int().positive().default(WORKSPACE_SETTINGS_SPEC_VERSION),
23679
23881
  runMode: RunMode.default("standalone"),
@@ -23722,7 +23924,13 @@ var WorkspaceSettings = external_exports.object({
23722
23924
  // carry prompt/reply/tool-output text in `content`; the key name predates
23723
23925
  // both widenings. Absent until granted, and a grant for a different endpoint
23724
23926
  // or an older payload no longer counts.
23725
- historySyncConsent: HistorySyncConsent.optional()
23927
+ historySyncConsent: HistorySyncConsent.optional(),
23928
+ // Local body expiry (see BodyRetention). Off until switched on; expiring a
23929
+ // body never removes the row or its findings.
23930
+ bodyRetention: BodyRetention.default({
23931
+ enabled: false,
23932
+ retainDays: BODY_RETENTION_DEFAULT_DAYS
23933
+ })
23726
23934
  });
23727
23935
  function defaultWorkspaceSettings() {
23728
23936
  return WorkspaceSettings.parse({});
@@ -23817,12 +24025,15 @@ function toCaptureAttributes(event) {
23817
24025
  ...metadata?.traceId !== void 0 ? { trace_id: metadata.traceId } : {},
23818
24026
  ...metadata?.exceptionIds !== void 0 ? { exception_ids: metadata.exceptionIds } : {},
23819
24027
  ...metadata?.inspectionMs !== void 0 ? { inspection_ms: metadata.inspectionMs } : {},
24028
+ ...metadata?.redactDegradedTo !== void 0 ? { redact_degraded_to: metadata.redactDegradedTo } : {},
23820
24029
  // `model`/`turnIndex` have no dedicated CaptureAttributes field (no writer
23821
24030
  // has ever populated either), but every legacy metadata key still rides
23822
24031
  // the bag rather than being silently dropped — CaptureAttributes'
23823
24032
  // `.catchall(z.unknown())` carries the long tail.
23824
24033
  ...metadata?.model !== void 0 ? { model: metadata.model } : {},
23825
- ...metadata?.turnIndex !== void 0 ? { turn_index: metadata.turnIndex } : {}
24034
+ ...metadata?.turnIndex !== void 0 ? { turn_index: metadata.turnIndex } : {},
24035
+ ...metadata?.messageId !== void 0 ? { message_id: metadata.messageId } : {},
24036
+ ...metadata?.conversationId !== void 0 ? { conversation_id: metadata.conversationId } : {}
23826
24037
  };
23827
24038
  }
23828
24039
  function captureDefinitionVersion(finding) {
@@ -23850,13 +24061,22 @@ var ManagedSettingKey = external_exports.enum([
23850
24061
  "vaultInlineReveal",
23851
24062
  "modelJudgeConsent",
23852
24063
  "dataSharesInPlace",
23853
- "redactFallback"
24064
+ "redactFallback",
24065
+ // Pins the toggle and the day count together — see BodyRetention on why the
24066
+ // two are one unit. An administrator mandating a window wants the count
24067
+ // enforced with it, not one a user can widen while the toggle stays on.
24068
+ "bodyRetention"
23854
24069
  ]).meta({ id: "ManagedSettingKey" });
23855
24070
  function isManagedSettingKey(value) {
23856
24071
  return ManagedSettingKey.safeParse(value).success;
23857
24072
  }
23858
24073
  var ManagedSettingsValues = external_exports.object({
23859
24074
  runMode: external_exports.enum(["standalone", "attached"]).optional(),
24075
+ // `controlPlane` and `bodyRetention` are the two nested values, and both are
24076
+ // plain, non-strict objects: a key under either that this build does not know
24077
+ // is stripped and nothing reports it. The unknown-value split in
24078
+ // ManagedSettings below classifies top-level names only, so it stops at
24079
+ // these boundaries.
23860
24080
  controlPlane: external_exports.object({
23861
24081
  endpoint: external_exports.string().min(1),
23862
24082
  label: external_exports.string().min(1).optional()
@@ -23867,7 +24087,8 @@ var ManagedSettingsValues = external_exports.object({
23867
24087
  vaultInlineReveal: external_exports.enum(["masked", "full", "off"]).optional(),
23868
24088
  modelJudgeConsent: external_exports.boolean().optional(),
23869
24089
  dataSharesInPlace: external_exports.boolean().optional(),
23870
- redactFallback: RedactFallback.optional()
24090
+ redactFallback: RedactFallback.optional(),
24091
+ bodyRetention: BodyRetention.optional()
23871
24092
  }).meta({ id: "ManagedSettingsValues" });
23872
24093
  var ManagedSettings = external_exports.object({
23873
24094
  specVersion: external_exports.number().int().positive().default(MANAGED_SETTINGS_SPEC_VERSION),
@@ -23875,7 +24096,21 @@ var ManagedSettings = external_exports.object({
23875
24096
  // decision from a bug. Absent renders as a generic "your organization".
23876
24097
  organization: external_exports.string().min(1).optional(),
23877
24098
  // What the administrator pinned.
23878
- values: ManagedSettingsValues.default({}),
24099
+ //
24100
+ // Parsed as a RECORD rather than as the nested schema, and split below for
24101
+ // the same reason `lockedFields` is parsed as names: a plain `z.object`
24102
+ // drops an unrecognised key and succeeds, so a pin this build does not know
24103
+ // vanished and nothing anywhere said so. A pin with no lock is a supported
24104
+ // shape — it is a DEFAULT the user may still change — so that silence hit
24105
+ // exactly the file an administrator is most likely to write while a fleet
24106
+ // is mid-upgrade.
24107
+ //
24108
+ // Splitting here rather than calling `.strict()`: strict would REFUSE the
24109
+ // file, which is the outcome the lock half already rejected — an older
24110
+ // build then runs entirely unmanaged, every pin and lock gone. A bad KNOWN
24111
+ // value still fails, because the nested schema is re-run over the known
24112
+ // subset and its issues are re-raised on this parse.
24113
+ values: external_exports.record(external_exports.string(), external_exports.unknown()).default({}),
23879
24114
  // Which of those the user may not change. A key here with no matching value
23880
24115
  // freezes whatever the user last chose; a value with no lock is a DEFAULT
23881
24116
  // the user may still override. The two are separable on purpose.
@@ -23888,17 +24123,31 @@ var ManagedSettings = external_exports.object({
23888
24123
  // the fleets most likely to carry a version skew. A name outside the enum
23889
24124
  // is still never HONOURED: the lockable set stays explicit above.
23890
24125
  lockedFields: external_exports.array(external_exports.string()).default([])
23891
- }).transform(({ lockedFields, ...rest }) => {
24126
+ }).transform(({ lockedFields, values, ...rest }, ctx) => {
23892
24127
  const known = [];
23893
24128
  const unknown2 = [];
23894
24129
  for (const name of lockedFields) {
23895
24130
  if (isManagedSettingKey(name)) known.push(name);
23896
24131
  else unknown2.push(name);
23897
24132
  }
24133
+ const knownValues = /* @__PURE__ */ Object.create(null);
24134
+ const unknownValues = [];
24135
+ for (const [name, value] of Object.entries(values)) {
24136
+ if (Object.hasOwn(ManagedSettingsValues.shape, name)) knownValues[name] = value;
24137
+ else unknownValues.push(name);
24138
+ }
24139
+ const pinned = ManagedSettingsValues.safeParse(knownValues);
24140
+ if (!pinned.success) {
24141
+ for (const issue2 of pinned.error.issues)
24142
+ ctx.addIssue({ ...issue2, path: ["values", ...issue2.path] });
24143
+ return external_exports.NEVER;
24144
+ }
23898
24145
  return {
23899
24146
  ...rest,
24147
+ values: pinned.data,
23900
24148
  lockedFields: known,
23901
- ...unknown2.length > 0 ? { unknownLockedFields: unknown2 } : {}
24149
+ ...unknown2.length > 0 ? { unknownLockedFields: unknown2 } : {},
24150
+ ...unknownValues.length > 0 ? { unknownValueFields: unknownValues } : {}
23902
24151
  };
23903
24152
  }).meta({ id: "ManagedSettings" });
23904
24153
 
@@ -24162,7 +24411,23 @@ var SaveSettingsInput = external_exports.object({
24162
24411
  modelJudgeConsent: ModelJudgeConsentChoice,
24163
24412
  historySyncConsent: HistorySyncConsentChoice,
24164
24413
  vaultConsent: external_exports.string(),
24165
- vaultInlineReveal: external_exports.string()
24414
+ vaultInlineReveal: external_exports.string(),
24415
+ // Widened to `string` like its neighbours rather than typed as
24416
+ // `RedactFallback`, on this module's own layering rule: shape here, VALUE at
24417
+ // the call site, so the domain check receives the type it was written for.
24418
+ //
24419
+ // NOT because a narrower schema would reject differently. `parseActionInput`
24420
+ // is a `safeParse` wrapper and throws for no field schema, so either spelling
24421
+ // reaches a recoverable `{ ok: false }` and there is no rejected promise to
24422
+ // trade against. The real cost runs the other way and is the part worth
24423
+ // knowing: a value this schema admits and the domain enum then rejects lands
24424
+ // on the action's shared refusal, which names NO field, where a shape
24425
+ // rejection reaches `malformedInput` and names the schema key.
24426
+ redactFallback: external_exports.string(),
24427
+ // Shape only, the way the enum fields above are strings only: the RANGE is
24428
+ // `BodyRetention`'s and the action checks it there, so there is one place
24429
+ // that decides what a legal horizon is rather than two that can drift.
24430
+ bodyRetention: external_exports.object({ enabled: external_exports.boolean(), retainDays: external_exports.number() })
24166
24431
  });
24167
24432
  var AttachInput = external_exports.object({
24168
24433
  endpoint: external_exports.string(),
@@ -24334,6 +24599,52 @@ function reviewSeverityRank(reasons) {
24334
24599
  return Math.min(...reasons.map((r) => REVIEW_SEVERITY_RANK[r]));
24335
24600
  }
24336
24601
 
24602
+ // ../../packages/schema/src/zod/web-capture.ts
24603
+ var WebUsageSource = external_exports.enum(["site", "estimated", "none"]);
24604
+ var WebUsage = external_exports.object({
24605
+ inputTokens: external_exports.number().int().nonnegative().optional(),
24606
+ outputTokens: external_exports.number().int().nonnegative().optional(),
24607
+ cacheReadInputTokens: external_exports.number().int().nonnegative().optional(),
24608
+ cacheCreationInputTokens: external_exports.number().int().nonnegative().optional()
24609
+ });
24610
+ var WebToolCall = external_exports.object({
24611
+ toolUseId: external_exports.string().min(1),
24612
+ toolName: external_exports.string().min(1),
24613
+ target: external_exports.string().optional(),
24614
+ isError: external_exports.boolean().optional(),
24615
+ inputSize: external_exports.number().int().nonnegative().optional(),
24616
+ outputSize: external_exports.number().int().nonnegative().optional()
24617
+ });
24618
+ var WebExchange = external_exports.object({
24619
+ messageId: external_exports.string().min(1),
24620
+ startedAt: external_exports.iso.datetime(),
24621
+ model: external_exports.string().optional(),
24622
+ usage: WebUsage.optional(),
24623
+ usageSource: WebUsageSource,
24624
+ stopReason: external_exports.string().optional(),
24625
+ conversationId: external_exports.string().optional(),
24626
+ turnIndex: external_exports.number().int().nonnegative().optional(),
24627
+ toolCalls: external_exports.array(WebToolCall).default([]),
24628
+ // Absent when the adapter recovered no text. Capped by the caller at
24629
+ // RESPONSE_TEXT_MAX_BYTES; `truncated` records that the cap was reached, so a
24630
+ // short capture is never mistaken for a short reply.
24631
+ responseText: external_exports.string().optional(),
24632
+ truncated: external_exports.boolean().default(false)
24633
+ });
24634
+ var RESPONSE_TEXT_MAX_BYTES = 2 * 1024 * 1024;
24635
+ var WebCaptureStatus = external_exports.object({
24636
+ patched: external_exports.boolean(),
24637
+ live: external_exports.boolean(),
24638
+ blind: external_exports.boolean(),
24639
+ sendsSeenDom: external_exports.number().int().nonnegative(),
24640
+ exchangesSeenNet: external_exports.number().int().nonnegative(),
24641
+ parseFailures: external_exports.number().int().nonnegative(),
24642
+ unparsedBodies: external_exports.number().int().nonnegative(),
24643
+ // The adapter-declared JSON key paths that were absent from a real payload —
24644
+ // the earliest signal that a site's contract moved.
24645
+ shapeMisses: external_exports.array(external_exports.string()).default([])
24646
+ });
24647
+
24337
24648
  // ../../packages/persistence/src/paths.ts
24338
24649
  import {
24339
24650
  chmodSync,
@@ -24694,6 +25005,22 @@ function discardStore(file2, backup) {
24694
25005
  }
24695
25006
  }
24696
25007
 
25008
+ // ../../packages/persistence/src/internal/sql-functions.ts
25009
+ var utf8 = new TextDecoder();
25010
+ function akaLower(value) {
25011
+ if (value === null) return null;
25012
+ if (typeof value === "string") return value.toLowerCase();
25013
+ if (typeof value === "number" || typeof value === "bigint") return String(value).toLowerCase();
25014
+ return utf8.decode(value).toLowerCase();
25015
+ }
25016
+ function registerSqlFunctions(db) {
25017
+ db.function(
25018
+ "aka_lower",
25019
+ { deterministic: true, directOnly: true, useBigIntArguments: true },
25020
+ akaLower
25021
+ );
25022
+ }
25023
+
24697
25024
  // ../../packages/persistence/src/internal/sql-text.ts
24698
25025
  function escapeLikePattern(s) {
24699
25026
  return s.replace(/\\/g, "\\\\").replace(/%/g, "\\%").replace(/_/g, "\\_");
@@ -24778,6 +25105,11 @@ function schemaObjectExists(db, kind, name) {
24778
25105
  function indexExists(db, name) {
24779
25106
  return schemaObjectExists(db, "index", name);
24780
25107
  }
25108
+ function indexColumns(db, name) {
25109
+ if (!indexExists(db, name)) return [];
25110
+ const columns = db.prepare(`PRAGMA index_info(${name})`).all();
25111
+ return columns.map((c) => c.name).filter((c) => c !== null);
25112
+ }
24781
25113
  function columnNames(db, table, opts) {
24782
25114
  const pragma = opts?.includeGenerated ? "table_xinfo" : "table_info";
24783
25115
  const columns = db.prepare(`PRAGMA ${pragma}(${table})`).all();
@@ -24839,176 +25171,818 @@ function mapRowsTolerant(rows, map2) {
24839
25171
  return out;
24840
25172
  }
24841
25173
 
24842
- // ../../packages/persistence/src/migrations.ts
24843
- function describeObject(object2) {
24844
- return object2.kind === "column" ? `column ${object2.table}.${object2.name}` : `table ${object2.name}`;
24845
- }
24846
- function splitStatements(sql) {
24847
- return sql.split(/-->\s*statement-breakpoint/).map((s) => s.trim()).filter((s) => s.length > 0);
24848
- }
24849
- function createdIndexName(statement) {
24850
- const body = statement.replace(/^(?:\s*--[^\n]*\n?)+/, "").trimStart();
24851
- return /^CREATE (?:UNIQUE )?INDEX (?:IF NOT EXISTS )?`([^`]+)`/.exec(body)?.[1];
25174
+ // ../../packages/persistence/src/internal/outbox-lane.ts
25175
+ var OUTBOX_CAPTURE_EVENT_TYPES = ["prompt", "response", "tool_use"];
25176
+ var OUTBOX_CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25177
+
25178
+ // ../../packages/persistence/src/sync-failure.ts
25179
+ var SYNC_FAILURE_REASONS = SyncFailureReason.options;
25180
+ function syncFailureRejectCondition(column = "sync_failure") {
25181
+ const members2 = SYNC_FAILURE_REASONS.map((r) => `'${r}'`).join(", ");
25182
+ return `NEW.${column} IS NOT NULL AND NEW.${column} NOT IN (${members2})`;
24852
25183
  }
24853
- var LEGACY_DROP_MIGRATION_TAG = "0014_drop_legacy_events_findings";
24854
- function applyMigrations(db, file2) {
24855
- const legacyCount = db.prepare("PRAGMA user_version").get().user_version;
24856
- db.exec(
24857
- "CREATE TABLE IF NOT EXISTS migration_ledger (tag TEXT PRIMARY KEY, applied_at INTEGER NOT NULL)"
24858
- );
24859
- const applied = new Set(
24860
- db.prepare("SELECT tag FROM migration_ledger").all().map((r) => r.tag)
24861
- );
24862
- const preLedgerStore = applied.size === 0 && legacyCount > 0;
24863
- const record2 = db.prepare(
24864
- "INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)"
24865
- );
24866
- for (const [index, migration] of SQLITE_MIGRATIONS.entries()) {
24867
- if (applied.has(migration.tag)) continue;
24868
- if (migration.tag === LEGACY_DROP_MIGRATION_TAG) continue;
24869
- const evidence = evidenceObjects(migration.sql);
24870
- const present = evidence.filter((o) => evidenceExists(db, o));
24871
- if (present.length > 0 && present.length < evidence.length) {
24872
- const missing = evidence.filter((o) => !present.includes(o));
24873
- 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.`;
24874
- akaWarn(message);
24875
- throw new Error(`[aka] ${message}`);
24876
- }
24877
- const alreadyApplied = evidence.length > 0 ? present.length === evidence.length : preLedgerStore && index < legacyCount;
24878
- const wantsFkOff = /PRAGMA foreign_keys\s*=\s*OFF/i.test(migration.sql);
24879
- const statements = splitStatements(migration.sql);
24880
- if (wantsFkOff) db.exec("PRAGMA foreign_keys = OFF");
24881
- try {
24882
- withTransaction(
24883
- db,
24884
- () => {
24885
- for (const statement of statements) {
24886
- const indexName = createdIndexName(statement);
24887
- if (indexName === void 0) {
24888
- if (alreadyApplied) continue;
24889
- } else if (indexExists(db, indexName)) {
24890
- continue;
24891
- }
24892
- db.exec(statement);
24893
- }
24894
- if (wantsFkOff && !alreadyApplied) {
24895
- const violations = db.prepare("PRAGMA foreign_key_check").all();
24896
- if (violations.length > 0) {
24897
- throw new Error(
24898
- `[aka] sqlite migration ${migration.tag} left ${String(violations.length)} foreign-key violation(s); rolling back.`
24899
- );
24900
- }
24901
- }
24902
- record2.run(migration.tag, Date.now());
24903
- },
24904
- "IMMEDIATE"
24905
- );
24906
- } finally {
24907
- if (wantsFkOff) db.exec("PRAGMA foreign_keys = ON");
24908
- }
25184
+
25185
+ // ../../packages/persistence/src/repositories/history-sync.ts
25186
+ var STRUCTURAL_EVENT_TYPES = ["session", "llm_call", "tool_call"];
25187
+ var TYPE_LIST = STRUCTURAL_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25188
+ var CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_TYPE_LIST;
25189
+ var COUNTED_EVENT_TYPES = [
25190
+ ...STRUCTURAL_EVENT_TYPES,
25191
+ ...OUTBOX_CAPTURE_EVENT_TYPES
25192
+ ];
25193
+ var COUNTED_TYPE_LIST = COUNTED_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25194
+ var PARTITION_BUCKETS = `
25195
+ SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NULL THEN 1 ELSE 0 END) AS queued,
25196
+ SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NOT NULL THEN 1 ELSE 0 END) AS inProgress,
25197
+ SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS synced,
25198
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25199
+ AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
25200
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25201
+ AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached,
25202
+ -- Spelled as what it INCLUDES rather than what it excludes, so a reason
25203
+ -- added later lands in no bucket and fails the sum assertion, instead
25204
+ -- of silently joining this one.
25205
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25206
+ AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
25207
+ THEN 1 ELSE 0 END) AS failed,
25208
+ COUNT(*) AS total`;
25209
+ var COUNTED_SCOPE = `
25210
+ WHERE event_type IN (${COUNTED_TYPE_LIST})
25211
+ AND (
25212
+ event_type IN (${TYPE_LIST})
25213
+ OR synced_at IS NOT NULL
25214
+ OR outbox_owed = 1
25215
+ )`;
25216
+ var SKIPPED = -1;
25217
+ var ROW_COLUMNS = `id,
25218
+ parent_id AS parentId,
25219
+ root_session_id AS rootSessionId,
25220
+ event_type AS eventType,
25221
+ host_id AS hostId,
25222
+ harness_id AS harnessId,
25223
+ source_project_id AS sourceProjectId,
25224
+ started_at AS startedAt,
25225
+ ended_at AS endedAt,
25226
+ severity,
25227
+ priority,
25228
+ content,
25229
+ content_hash AS contentHash,
25230
+ attributes`;
25231
+ var SqliteHistorySyncRepository = class {
25232
+ constructor(db) {
25233
+ this.db = db;
25234
+ this.ensureRowStmt = db.prepare(`INSERT OR IGNORE INTO history_sync (id) VALUES (1)`);
25235
+ this.sessionsStmt = db.prepare(
25236
+ `SELECT COALESCE(root_session_id, id) AS sessionId, MIN(started_at) AS earliest
25237
+ FROM audit_events
25238
+ WHERE synced_at IS NULL
25239
+ AND event_type IN (${TYPE_LIST})
25240
+ AND started_at < :before
25241
+ GROUP BY sessionId
25242
+ ORDER BY earliest
25243
+ LIMIT :limit`
25244
+ );
25245
+ this.rowsStmt = db.prepare(
25246
+ `SELECT ${ROW_COLUMNS}
25247
+ FROM audit_events
25248
+ WHERE synced_at IS NULL
25249
+ AND event_type IN (${TYPE_LIST})
25250
+ AND started_at < :before
25251
+ AND COALESCE(root_session_id, id) = :sessionId
25252
+ ORDER BY (event_type = 'session') DESC, started_at
25253
+ LIMIT :limit`
25254
+ );
25255
+ this.captureRowsStmt = db.prepare(
25256
+ `SELECT ${ROW_COLUMNS}
25257
+ FROM audit_events
25258
+ WHERE synced_at IS NULL
25259
+ AND sync_claimed_at IS NULL
25260
+ AND outbox_owed = 1
25261
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25262
+ AND started_at < :before
25263
+ ORDER BY started_at
25264
+ LIMIT :limit`
25265
+ );
25266
+ this.markOwedStmt = db.prepare(
25267
+ `UPDATE audit_events SET outbox_owed = 1 WHERE id = :id AND synced_at IS NULL`
25268
+ );
25269
+ this.markCaptureBacklogOwedStmt = db.prepare(
25270
+ `UPDATE audit_events SET outbox_owed = 1
25271
+ WHERE synced_at IS NULL
25272
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25273
+ AND started_at < :before`
25274
+ );
25275
+ this.stampStmt = db.prepare(
25276
+ `UPDATE audit_events
25277
+ SET synced_at = :at,
25278
+ sync_claimed_at = NULL,
25279
+ sync_failed_at = :failedAt,
25280
+ sync_failure = :failure
25281
+ WHERE id = :id`
25282
+ );
25283
+ this.claimRowStmt = db.prepare(
25284
+ `UPDATE audit_events SET sync_claimed_at = :at WHERE id = :id AND synced_at IS NULL`
25285
+ );
25286
+ this.releaseRowStmt = db.prepare(
25287
+ `UPDATE audit_events SET sync_claimed_at = NULL WHERE id = :id`
25288
+ );
25289
+ this.releaseStaleClaimsStmt = db.prepare(
25290
+ `UPDATE audit_events SET sync_claimed_at = NULL
25291
+ WHERE sync_claimed_at IS NOT NULL AND sync_claimed_at < :staleBefore`
25292
+ );
25293
+ this.partitionStmt = db.prepare(`SELECT${PARTITION_BUCKETS}
25294
+ FROM audit_events${COUNTED_SCOPE}`);
25295
+ this.partitionByKindStmt = db.prepare(
25296
+ `SELECT event_type AS kind,${PARTITION_BUCKETS}
25297
+ FROM audit_events INDEXED BY idx_audit_events_sync${COUNTED_SCOPE}
25298
+ GROUP BY event_type`
25299
+ );
25300
+ this.countsStmt = db.prepare(
25301
+ `SELECT
25302
+ SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
25303
+ SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
25304
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25305
+ AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
25306
+ THEN 1 ELSE 0 END) AS skipped,
25307
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25308
+ AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
25309
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25310
+ AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached
25311
+ FROM audit_events
25312
+ WHERE event_type IN (${TYPE_LIST})`
25313
+ );
25314
+ this.captureSkipCountStmt = db.prepare(
25315
+ // EVERY sentinel capture, whatever the reason — deliberately NOT split the
25316
+ // way the structural totals are. The split exists because a refusal is
25317
+ // terminal only against the deployment that gave it, and the structural
25318
+ // re-arm frees it on a change of deployment. The capture lane has no such
25319
+ // escape: re-arming a capture would offer one deployment's undelivered
25320
+ // prompts, with their text, to a deployment that never saw them, which is
25321
+ // exactly what disownCapturesStmt exists to prevent. So on this lane both
25322
+ // reasons mean the same thing — this row will not be sent — and splitting
25323
+ // them would put refused captures in a bucket nothing reads and nothing
25324
+ // frees.
25325
+ `SELECT COUNT(*) AS skipped
25326
+ FROM audit_events
25327
+ WHERE synced_at = ${String(SKIPPED)}
25328
+ AND event_type IN (${CAPTURE_TYPE_LIST})`
25329
+ );
25330
+ this.fingerprintStmt = db.prepare(
25331
+ `SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
25332
+ FROM history_sync WHERE id = 1`
25333
+ );
25334
+ this.setFingerprintStmt = db.prepare(
25335
+ `UPDATE history_sync
25336
+ SET endpoint_fingerprint = :fingerprint, backlog_before = :backlogBefore
25337
+ WHERE id = 1`
25338
+ );
25339
+ this.disownCapturesStmt = db.prepare(
25340
+ `UPDATE audit_events SET outbox_owed = NULL
25341
+ WHERE outbox_owed IS NOT NULL
25342
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25343
+ AND started_at < :attachedAt`
25344
+ );
25345
+ this.rearmStmt = db.prepare(
25346
+ `UPDATE audit_events
25347
+ SET synced_at = NULL, sync_failed_at = NULL, sync_failure = NULL
25348
+ WHERE (synced_at > 0
25349
+ OR sync_failure IN ('deployment_refused', 'detached_undelivered'))
25350
+ AND event_type IN (${TYPE_LIST})`
25351
+ );
25352
+ this.claimStmt = db.prepare(
25353
+ `UPDATE history_sync
25354
+ SET owner_pid = :pid, owner_host = :host, acquired_at = :now, heartbeat_at = :now
25355
+ WHERE id = 1
25356
+ AND (owner_pid IS NULL
25357
+ OR heartbeat_at IS NULL
25358
+ OR heartbeat_at < :staleBefore
25359
+ OR heartbeat_at > :now)`
25360
+ );
25361
+ this.heartbeatStmt = db.prepare(
25362
+ `UPDATE history_sync SET heartbeat_at = :now WHERE id = 1 AND owner_pid = :pid`
25363
+ );
25364
+ this.releaseStmt = db.prepare(
25365
+ `UPDATE history_sync
25366
+ SET owner_pid = NULL, owner_host = NULL, acquired_at = NULL, heartbeat_at = NULL
25367
+ WHERE id = 1 AND owner_pid = :pid`
25368
+ );
25369
+ this.closeWindowStmt = db.prepare(
25370
+ `UPDATE audit_events
25371
+ SET synced_at = ${String(SKIPPED)},
25372
+ sync_failed_at = :at,
25373
+ sync_failure = 'detached_undelivered'
25374
+ WHERE synced_at IS NULL
25375
+ AND event_type IN (${TYPE_LIST})
25376
+ AND started_at >= :attachedAt`
25377
+ );
25378
+ this.releaseBoundaryStmt = db.prepare(
25379
+ `UPDATE history_sync SET backlog_before = NULL WHERE id = 1`
25380
+ );
25381
+ this.freezeBoundaryStmt = db.prepare(
25382
+ `UPDATE history_sync SET backlog_before = :backlogBefore WHERE id = 1`
25383
+ );
25384
+ this.leaseStmt = db.prepare(
25385
+ `SELECT owner_pid AS ownerPid, owner_host AS ownerHost,
25386
+ acquired_at AS acquiredAt, heartbeat_at AS heartbeatAt
25387
+ FROM history_sync WHERE id = 1`
25388
+ );
25389
+ this.inspectionsStmt = db.prepare(
25390
+ `SELECT d.rule_id AS ruleId,
25391
+ d.name AS ruleName,
25392
+ d.version AS ruleVersion,
25393
+ d.category AS category,
25394
+ d.severity AS severity,
25395
+ f.span_start AS spanStart,
25396
+ f.span_end AS spanEnd,
25397
+ f.masked_match AS maskedMatch,
25398
+ f.action_taken AS actionTaken,
25399
+ f.confidence AS confidence
25400
+ FROM inspection_findings f
25401
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
25402
+ WHERE f.audit_event_id = :auditEventId
25403
+ ORDER BY f.span_start, f.id`
25404
+ );
24909
25405
  }
24910
- if (legacyCount < SQLITE_MIGRATIONS.length) {
24911
- db.exec(`PRAGMA user_version = ${String(SQLITE_MIGRATIONS.length)}`);
25406
+ db;
25407
+ ensureRowStmt;
25408
+ sessionsStmt;
25409
+ rowsStmt;
25410
+ stampStmt;
25411
+ countsStmt;
25412
+ fingerprintStmt;
25413
+ setFingerprintStmt;
25414
+ rearmStmt;
25415
+ claimStmt;
25416
+ heartbeatStmt;
25417
+ releaseStmt;
25418
+ leaseStmt;
25419
+ inspectionsStmt;
25420
+ closeWindowStmt;
25421
+ releaseBoundaryStmt;
25422
+ freezeBoundaryStmt;
25423
+ captureRowsStmt;
25424
+ markOwedStmt;
25425
+ markCaptureBacklogOwedStmt;
25426
+ captureSkipCountStmt;
25427
+ disownCapturesStmt;
25428
+ partitionStmt;
25429
+ partitionByKindStmt;
25430
+ claimRowStmt;
25431
+ releaseRowStmt;
25432
+ releaseStaleClaimsStmt;
25433
+ /**
25434
+ * The masked detections recorded against one tool call.
25435
+ *
25436
+ * These travel with the event because a tool call's target is not
25437
+ * re-inspectable from the event alone — unlike a capture, where the text
25438
+ * itself is re-scannable. What crosses is the masked match and the rule that
25439
+ * produced it, never the value.
25440
+ */
25441
+ inspectionsFor(auditEventId) {
25442
+ return allRows(this.inspectionsStmt, { auditEventId });
24912
25443
  }
24913
- ensureSyncedAtColumn(db, "audit_events");
24914
- ensureScanLedgerTable(db);
24915
- ensureHistorySyncTable(db);
24916
- ensureBlockedDetectionsTable(db);
24917
- ensureRuleProbeCacheTable(db);
24918
- ensureWriteGateTrigger(db);
24919
- ensureTokenUsageColumns(db);
24920
- reconcileSourceProjectIds(db);
24921
- if (!applied.has(LEGACY_DROP_MIGRATION_TAG)) {
24922
- const drained = runLegacyHistoryBackfill(db);
24923
- if (drained) applyLegacyDropMigration(db, file2);
25444
+ /**
25445
+ * Sessions with structural rows still to send, oldest first.
25446
+ *
25447
+ * BOUNDED BY THE BACKLOG BOUNDARY, which is the whole correctness of this
25448
+ * read. Anything recorded after the machine attached is the live forward
25449
+ * path's to deliver; this drain exists for what was recorded before it, and a
25450
+ * row both paths send is at best a duplicate request and at worst — for a
25451
+ * session root — an overwrite of the inventory ids the live path resolved.
25452
+ */
25453
+ pendingSessions(limit, before) {
25454
+ return allRows(this.sessionsStmt, { limit, before }).map(
25455
+ (r) => r.sessionId
25456
+ );
24924
25457
  }
24925
- }
24926
- function readLegacyTables(db) {
24927
- let holdsRows = false;
24928
- const marks = [];
24929
- for (const table of ["events", "findings"]) {
24930
- try {
24931
- const row = db.prepare(`SELECT count(*) AS n, ifnull(max(rowid), -1) AS hi FROM ${table}`).get();
24932
- if (row === void 0) {
24933
- holdsRows = true;
24934
- marks.push(`${table}:unreadable`);
24935
- continue;
24936
- }
24937
- if (row.n > 0) holdsRows = true;
24938
- marks.push(`${table}:${String(row.n)}:${String(row.hi)}`);
24939
- } catch {
24940
- holdsRows = true;
24941
- marks.push(`${table}:unreadable`);
24942
- }
25458
+ /** One session's undelivered structural rows within the backlog, root first. */
25459
+ pendingRows(sessionId, limit, before) {
25460
+ return allRows(this.rowsStmt, { sessionId, limit, before });
24943
25461
  }
24944
- return { holdsRows, mark: marks.join("|") };
24945
- }
24946
- function applyLegacyDropMigration(db, file2) {
24947
- const migration = SQLITE_MIGRATIONS.find((m) => m.tag === LEGACY_DROP_MIGRATION_TAG);
24948
- if (!migration) return;
24949
- const before = file2 === void 0 ? void 0 : readLegacyTables(db);
24950
- if (file2 !== void 0 && before?.holdsRows === true) {
24951
- try {
24952
- backupBeforeLegacyDrop(db, file2);
24953
- } catch (error61) {
24954
- akaWarn(`legacy events/findings backup failed; deferring the drop: ${String(error61)}`);
24955
- return;
24956
- }
25462
+ /**
25463
+ * Captures this machine still owes the deployment, oldest first.
25464
+ *
25465
+ * Selected by the `outbox_owed` marker the attached forward path writes, not
25466
+ * by a time window — see captureRowsStmt for why a window could not express
25467
+ * this. `before` is the grace window that leaves a just-recorded capture to
25468
+ * the live path.
25469
+ */
25470
+ pendingCaptureRows(limit, before) {
25471
+ return allRows(this.captureRowsStmt, { limit, before });
24957
25472
  }
24958
- try {
25473
+ /**
25474
+ * Record that a capture is OWED to the deployment.
25475
+ *
25476
+ * Written by the attached forward path when a live send did not confirm
25477
+ * delivery, and read by the drain as the whole of its eligibility test. It is
25478
+ * a fact rather than an inference: the machine was attached, the send did not
25479
+ * land, so the row is owed — which no time window can state, because the same
25480
+ * window that holds the rows a past attachment left owed also holds every
25481
+ * capture recorded while the machine was DETACHED, and those were never
25482
+ * offered to anyone.
25483
+ *
25484
+ * Idempotent, and never un-set: `markSynced` settling the row is what takes it
25485
+ * out of the drain's read.
25486
+ */
25487
+ markCaptureOwed(id) {
25488
+ this.markOwedStmt.run({ id });
25489
+ }
25490
+ /**
25491
+ * Mark every capture already on disk as owed, as of `before`.
25492
+ *
25493
+ * The consent-time backfill, called once from `aka attach` when a human
25494
+ * grants existing-history consent — never from an ongoing drain pass, and
25495
+ * never inferred from a boundary that could later move. `before` is the
25496
+ * caller's own "now" at the moment consent was granted, so what this marks
25497
+ * is exactly the backlog the consent prompt already counted, not whatever a
25498
+ * later re-attach or key rotation might widen it to.
25499
+ *
25500
+ * Returns how many rows matched, for the caller to log or test against. Not a
25501
+ * count of NEWLY marked rows — a row still unsynced from an earlier call
25502
+ * matches again and is counted again, the same as `UPDATE`'s own `changes`.
25503
+ */
25504
+ markCaptureBacklogOwed(before) {
25505
+ return Number(this.markCaptureBacklogOwedStmt.run({ before }).changes);
25506
+ }
25507
+ /**
25508
+ * Record delivery. Called only AFTER the far side has accepted the rows.
25509
+ *
25510
+ * CLEARS any failure reason in the same statement. A row that failed against
25511
+ * one deployment and then landed is delivered, and leaving the reason behind
25512
+ * would leave the store holding two contradictory answers about one row —
25513
+ * with the surface free to render either.
25514
+ */
25515
+ markSynced(ids, atMs) {
25516
+ this.stampAll(ids, atMs, null);
25517
+ }
25518
+ /**
25519
+ * Record that THIS MACHINE cannot express the row on the wire.
25520
+ *
25521
+ * Reserved for a local defect — a row that cannot be rebuilt into a valid
25522
+ * payload, or a body the client itself refused to send. It fails identically
25523
+ * against every deployment, so it is terminal everywhere and the re-arm leaves
25524
+ * it alone. A row that merely failed to REACH the deployment stays NULL, so it
25525
+ * is retried; marking those would turn one outage into permanent data loss.
25526
+ */
25527
+ markSkipped(ids, atMs) {
25528
+ this.stampAll(ids, SKIPPED, "payload_invalid", atMs);
25529
+ }
25530
+ /**
25531
+ * Record that THIS DEPLOYMENT refused the row.
25532
+ *
25533
+ * The same sentinel as `markSkipped`, and deliberately so: both stop the row
25534
+ * being re-offered on this lane, and `synced_at` goes on answering whether a
25535
+ * row is outstanding rather than why. What separates them is the reason, and
25536
+ * what the reason buys is the re-arm — a refusal is one deployment's verdict
25537
+ * on one body, so it is terminal only for as long as this machine points at
25538
+ * that deployment, and `rearmFor` clears it when the deployment changes.
25539
+ *
25540
+ * Leaving such a row NULL instead would be worse than the loss it replaces:
25541
+ * these reads carry no cursor, so an unstamped row the deployment refuses is
25542
+ * the head of every subsequent page, and the lane stalls behind it for ever.
25543
+ */
25544
+ markRefused(ids, atMs) {
25545
+ this.stampAll(ids, SKIPPED, "deployment_refused", atMs);
25546
+ }
25547
+ eachInTransaction(ids, run) {
25548
+ if (ids.length === 0) return;
24959
25549
  withTransaction(
24960
- db,
25550
+ this.db,
24961
25551
  () => {
24962
- const alreadyDropped = db.prepare("SELECT 1 FROM migration_ledger WHERE tag = ?").get(migration.tag);
24963
- if (alreadyDropped) return;
24964
- if (before !== void 0 && readLegacyTables(db).mark !== before.mark) {
24965
- akaWarn(
24966
- "legacy events/findings rows changed after the pre-drop snapshot decision; deferring the drop so the next open can copy them first."
24967
- );
24968
- return;
24969
- }
24970
- for (const statement of splitStatements(migration.sql)) {
24971
- db.exec(statement);
24972
- }
24973
- db.prepare("INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)").run(
24974
- migration.tag,
24975
- Date.now()
24976
- );
25552
+ for (const id of ids) run(id);
24977
25553
  },
24978
25554
  "IMMEDIATE"
24979
25555
  );
24980
- } catch (error61) {
24981
- akaWarn(`legacy events/findings drop failed; deferring: ${String(error61)}`);
24982
25556
  }
24983
- }
24984
- function backupBeforeLegacyDrop(db, file2) {
24985
- reapStalePartials(file2);
24986
- const backup = backupPath(file2, "pre-drop");
24987
- snapshotStore(db, backup);
24988
- return backup;
24989
- }
24990
- var TOKEN_USAGE_COLUMNS = [
24991
- {
24992
- name: "input_tokens",
24993
- ddl: "ALTER TABLE audit_events ADD COLUMN input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.input_tokens')) VIRTUAL"
24994
- },
24995
- {
24996
- name: "output_tokens",
24997
- ddl: "ALTER TABLE audit_events ADD COLUMN output_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.output_tokens')) VIRTUAL"
24998
- },
24999
- {
25000
- name: "cache_creation_input_tokens",
25001
- ddl: "ALTER TABLE audit_events ADD COLUMN cache_creation_input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.cache_creation_input_tokens')) VIRTUAL"
25002
- },
25003
- {
25004
- name: "cache_read_input_tokens",
25005
- ddl: "ALTER TABLE audit_events ADD COLUMN cache_read_input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.cache_read_input_tokens')) VIRTUAL"
25006
- },
25007
- {
25008
- name: "model",
25009
- ddl: "ALTER TABLE audit_events ADD COLUMN model text GENERATED ALWAYS AS (json_extract(attributes, '$.model')) VIRTUAL"
25010
- },
25011
- {
25557
+ stampAll(ids, value, failure, failedAtMs) {
25558
+ if (ids.length === 0) return;
25559
+ const failedAt = failure === null ? null : failedAtMs ?? null;
25560
+ withTransaction(
25561
+ this.db,
25562
+ () => {
25563
+ for (const id of ids) this.stampStmt.run({ at: value, failedAt, failure, id });
25564
+ },
25565
+ "IMMEDIATE"
25566
+ );
25567
+ }
25568
+ /**
25569
+ * Claim rows as in-flight.
25570
+ *
25571
+ * Advisory in exactly the sense the lease is: it records that a send is in
25572
+ * progress so a surface can say so, and a lost claim costs a row showing as
25573
+ * queued while it is actually being sent. It is not exclusion — the far side
25574
+ * settles a duplicate on the row id.
25575
+ */
25576
+ claimRows(ids, atMs) {
25577
+ this.eachInTransaction(ids, (id) => this.claimRowStmt.run({ at: atMs, id }));
25578
+ }
25579
+ /** Give back a claim without settling — the send failed, the row is queued again. */
25580
+ releaseRows(ids) {
25581
+ this.eachInTransaction(ids, (id) => this.releaseRowStmt.run({ id }));
25582
+ }
25583
+ /**
25584
+ * Clear claims older than `staleBefore`, and report how many were cleared.
25585
+ *
25586
+ * A process killed between claiming and settling leaves rows claimed with
25587
+ * nothing left to settle them. Without this they read as "sending" for ever.
25588
+ */
25589
+ releaseStaleClaims(staleBefore) {
25590
+ return Number(this.releaseStaleClaimsStmt.run({ staleBefore }).changes);
25591
+ }
25592
+ /**
25593
+ * Every tracked row in exactly one delivery state.
25594
+ *
25595
+ * Takes no boundary on purpose. The boundary answers "what should the drain
25596
+ * pick up now", which is a different question from "what state is this row
25597
+ * in" — and a machine that has never attached has no boundary to pass, so
25598
+ * requiring one would force a caller to invent one and report the whole store
25599
+ * as queued.
25600
+ */
25601
+ /**
25602
+ * The same partition, one row per kind that a lane carries.
25603
+ *
25604
+ * A kind with nothing to report is ABSENT rather than a row of zeros: the
25605
+ * scope decides which rows exist at all, so a kind that has never been
25606
+ * recorded — or whose captures nobody ever owed — produces no group. A caller
25607
+ * rendering a fixed list of kinds must therefore treat a missing one as "no
25608
+ * rows", never as "zero sent"; the two look identical in a bar and mean
25609
+ * different things.
25610
+ */
25611
+ partitionByKind() {
25612
+ return allRows(
25613
+ this.partitionByKindStmt,
25614
+ {}
25615
+ ).map((row) => ({
25616
+ kind: row.kind,
25617
+ queued: row.queued ?? 0,
25618
+ inProgress: row.inProgress ?? 0,
25619
+ synced: row.synced ?? 0,
25620
+ failed: row.failed ?? 0,
25621
+ refused: row.refused ?? 0,
25622
+ detached: row.detached ?? 0,
25623
+ total: row.total ?? 0
25624
+ }));
25625
+ }
25626
+ partition() {
25627
+ const row = getRow(this.partitionStmt, {});
25628
+ return {
25629
+ queued: row?.queued ?? 0,
25630
+ inProgress: row?.inProgress ?? 0,
25631
+ synced: row?.synced ?? 0,
25632
+ failed: row?.failed ?? 0,
25633
+ refused: row?.refused ?? 0,
25634
+ detached: row?.detached ?? 0,
25635
+ total: row?.total ?? 0
25636
+ };
25637
+ }
25638
+ /** `pending` counts only what is inside the backlog; sent and skipped are totals. */
25639
+ counts(before) {
25640
+ const row = getRow(this.countsStmt, { before });
25641
+ const captures = getRow(this.captureSkipCountStmt);
25642
+ return {
25643
+ pending: row?.pending ?? 0,
25644
+ sent: row?.sent ?? 0,
25645
+ skipped: row?.skipped ?? 0,
25646
+ refused: row?.refused ?? 0,
25647
+ detached: row?.detached ?? 0,
25648
+ capturesSkipped: captures?.skipped ?? 0
25649
+ };
25650
+ }
25651
+ /**
25652
+ * The deployment the current stamps were made against, and where its backlog
25653
+ * ends.
25654
+ *
25655
+ * READ-ONLY. An absent row reads as an absent deployment, which is what a
25656
+ * machine that has never drained is — and every writer below seeds the row
25657
+ * before it needs one, so nothing depends on this creating it. Keeping the
25658
+ * write off the gate path matters because the gate runs on every pass while a
25659
+ * write has to take the database's write lock.
25660
+ */
25661
+ deployment() {
25662
+ const row = getRow(
25663
+ this.fingerprintStmt
25664
+ );
25665
+ return {
25666
+ fingerprint: row?.fingerprint ?? void 0,
25667
+ backlogBefore: row?.backlogBefore ?? void 0
25668
+ };
25669
+ }
25670
+ /**
25671
+ * Point the ledger at a different deployment, discarding what it recorded
25672
+ * about the previous one.
25673
+ *
25674
+ * Delivery is a fact about ONE recipient: rows sent to the deployment a
25675
+ * machine has just left are undelivered as far as the new one is concerned.
25676
+ * All four in one transaction, so a crash between them cannot leave stamps
25677
+ * attributed to the wrong deployment, a boundary that belongs to another, or
25678
+ * a disown with no re-mark to follow it.
25679
+ *
25680
+ * The boundary is written HERE and only here, which is what freezes it: a
25681
+ * re-attach to the SAME deployment (a key rotation) leaves the fingerprint
25682
+ * unchanged, so this never runs and the backlog does not widen back over rows
25683
+ * the live path has since delivered.
25684
+ *
25685
+ * `backfillCapturesBefore` is the caller's OWN "now" at the instant a human
25686
+ * granted existing-history consent for the deployment this call is arming —
25687
+ * a DIFFERENT instant from `backlogBefore`: the re-mark boundary is the GRANT
25688
+ * instant, `backlogBefore` is the ATTACH instant, and the two can be far
25689
+ * apart. Passed only when that grant is valid, since this method has no way
25690
+ * to check consent itself and must not mark a row owed for a machine that
25691
+ * never agreed to it. Applied AFTER the disown above, in the SAME
25692
+ * transaction: what the disown clears is every marker below `backlogBefore`,
25693
+ * which includes this deployment's OWN pre-attach rows — `aka attach` calls
25694
+ * `seedCaptureBacklogOwed` at the attach instant, so every row it marks sits
25695
+ * on the cleared side of that bound — and the re-mark in the same
25696
+ * transaction is what puts those rows back. A crash between the two cannot
25697
+ * strand the ledger disowned with nothing re-marked — the transaction either
25698
+ * lands whole or not at all, and a fingerprint mismatch that has not yet
25699
+ * committed re-enters this method on the very next pass. Omit it (the
25700
+ * structural-only tests do) to exercise the disown in isolation.
25701
+ *
25702
+ * The disown is bounded by `backlogBefore`, which is what keeps it from
25703
+ * touching a marker the NEW deployment's OWN live path has already set: B's
25704
+ * live path can mark a capture owed from the moment `aka attach` writes the
25705
+ * descriptor, before the drain's first pass ever reaches this method, and
25706
+ * such a row sits at or after the bound rather than below it. What keeps the
25707
+ * disown from eating THIS SAME CALL's own re-mark is the order, not the
25708
+ * bound — disown runs first, re-mark second, both inside the one
25709
+ * transaction above.
25710
+ */
25711
+ rearmFor(fingerprint, backlogBefore, backfillCapturesBefore) {
25712
+ this.ensureRowStmt.run();
25713
+ withTransaction(
25714
+ this.db,
25715
+ () => {
25716
+ const previous = getRow(this.fingerprintStmt)?.fingerprint;
25717
+ this.rearmStmt.run();
25718
+ if (previous !== null && previous !== void 0 && previous !== fingerprint) {
25719
+ this.disownCapturesStmt.run({ attachedAt: backlogBefore });
25720
+ }
25721
+ if (backfillCapturesBefore !== void 0) {
25722
+ this.markCaptureBacklogOwedStmt.run({ before: backfillCapturesBefore });
25723
+ }
25724
+ this.setFingerprintStmt.run({ fingerprint, backlogBefore });
25725
+ },
25726
+ "IMMEDIATE"
25727
+ );
25728
+ }
25729
+ /**
25730
+ * End the attached period: hand its rows to the live path, and release the
25731
+ * boundary so the next attachment can freeze a new one.
25732
+ *
25733
+ * WITHOUT THIS, a detach and a re-attach to the same deployment leave a window
25734
+ * nothing delivers. The fingerprint is unchanged, so the boundary is never
25735
+ * re-frozen and stays at the FIRST attachment — while nothing forwards at all
25736
+ * during the detached period, because the machine is not attached. Rows
25737
+ * recorded in that window sit after the boundary and before the re-attach, so
25738
+ * neither path takes them, and the pending count reports none outstanding.
25739
+ *
25740
+ * WHAT IT RECORDS, and what it deliberately does not. These rows were the
25741
+ * closing attachment's to deliver and are no longer outstanding — that is what
25742
+ * lets the boundary move. It is NOT a claim that any of them arrived, and the
25743
+ * distinction is not academic: this used to write a delivery TIME, which every
25744
+ * read treats as delivery, so one detach turned a window of undelivered rows
25745
+ * into a window of delivered ones and no surface could tell. It writes the
25746
+ * skip sentinel and a reason of its own instead, so "no longer owed" and
25747
+ * "received" stop being the same fact.
25748
+ *
25749
+ * A change of deployment still frees them (see the re-arm), because the next
25750
+ * deployment has seen none of this machine's history — so the rows reach it
25751
+ * exactly as they did when this wrote a delivery time.
25752
+ *
25753
+ * ONE TRANSACTION, so a crash cannot release the boundary while leaving the
25754
+ * window unstamped — that half-state would re-send the whole attached period
25755
+ * on the next attach, which is the failure the boundary exists to prevent.
25756
+ */
25757
+ closeAttachedWindow(attachedAtMs, atMs) {
25758
+ this.ensureRowStmt.run();
25759
+ withTransaction(
25760
+ this.db,
25761
+ () => {
25762
+ const row = getRow(this.fingerprintStmt);
25763
+ const from = row?.backlogBefore ?? attachedAtMs;
25764
+ this.closeWindowStmt.run({ at: atMs, attachedAt: from });
25765
+ this.releaseBoundaryStmt.run();
25766
+ },
25767
+ "IMMEDIATE"
25768
+ );
25769
+ }
25770
+ /**
25771
+ * Freeze a boundary for the deployment already on file, KEEPING the stamps.
25772
+ *
25773
+ * The re-attach half of the above. Distinct from `rearmFor`, which is for a
25774
+ * different deployment and therefore discards what was delivered to the old
25775
+ * one: here the recipient is the same, so everything already sent to it stays
25776
+ * sent.
25777
+ */
25778
+ freezeBoundary(backlogBefore) {
25779
+ this.ensureRowStmt.run();
25780
+ this.freezeBoundaryStmt.run({ backlogBefore });
25781
+ }
25782
+ /** Take the claim, or report that someone live already holds it. */
25783
+ claim(pid, host, nowMs, staleAfterMs) {
25784
+ this.ensureRowStmt.run();
25785
+ let taken = false;
25786
+ withTransaction(
25787
+ this.db,
25788
+ () => {
25789
+ const result = this.claimStmt.run({
25790
+ pid,
25791
+ host,
25792
+ now: nowMs,
25793
+ staleBefore: nowMs - staleAfterMs
25794
+ });
25795
+ taken = result.changes === 1;
25796
+ },
25797
+ "IMMEDIATE"
25798
+ );
25799
+ return taken;
25800
+ }
25801
+ /** Say the holder is still alive. A no-op once the claim has moved on. */
25802
+ heartbeat(pid, nowMs) {
25803
+ this.heartbeatStmt.run({ now: nowMs, pid });
25804
+ }
25805
+ /** Give the claim up. Scoped to this holder, so a taken-over claim is left be. */
25806
+ release(pid) {
25807
+ this.releaseStmt.run({ pid });
25808
+ }
25809
+ /** Who holds the claim, if anyone. Read-only, for the same reason as above. */
25810
+ lease() {
25811
+ return getRow(this.leaseStmt);
25812
+ }
25813
+ };
25814
+
25815
+ // ../../packages/persistence/src/migrations.ts
25816
+ function describeObject(object2) {
25817
+ return object2.kind === "column" ? `column ${object2.table}.${object2.name}` : `table ${object2.name}`;
25818
+ }
25819
+ function splitStatements(sql) {
25820
+ return sql.split(/-->\s*statement-breakpoint/).map((s) => s.trim()).filter((s) => s.length > 0);
25821
+ }
25822
+ function createdIndexName(statement) {
25823
+ const body = statement.replace(/^(?:\s*--[^\n]*\n?)+/, "").trimStart();
25824
+ return /^CREATE (?:UNIQUE )?INDEX (?:IF NOT EXISTS )?`([^`]+)`/.exec(body)?.[1];
25825
+ }
25826
+ var LEGACY_DROP_MIGRATION_TAG = "0014_drop_legacy_events_findings";
25827
+ function applyMigrations(db, file2, options = {}) {
25828
+ const legacyCount = db.prepare("PRAGMA user_version").get().user_version;
25829
+ db.exec(
25830
+ "CREATE TABLE IF NOT EXISTS migration_ledger (tag TEXT PRIMARY KEY, applied_at INTEGER NOT NULL)"
25831
+ );
25832
+ const applied = new Set(
25833
+ db.prepare("SELECT tag FROM migration_ledger").all().map((r) => r.tag)
25834
+ );
25835
+ const preLedgerStore = applied.size === 0 && legacyCount > 0;
25836
+ const record2 = db.prepare(
25837
+ "INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)"
25838
+ );
25839
+ for (const [index, migration] of SQLITE_MIGRATIONS.entries()) {
25840
+ if (applied.has(migration.tag)) continue;
25841
+ if (options.skipTags?.has(migration.tag) === true) continue;
25842
+ if (migration.tag === LEGACY_DROP_MIGRATION_TAG) continue;
25843
+ const evidence = evidenceObjects(migration.sql);
25844
+ const present = evidence.filter((o) => evidenceExists(db, o));
25845
+ if (present.length > 0 && present.length < evidence.length) {
25846
+ const missing = evidence.filter((o) => !present.includes(o));
25847
+ 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.`;
25848
+ akaWarn(message);
25849
+ throw new Error(`[aka] ${message}`);
25850
+ }
25851
+ const alreadyApplied = evidence.length > 0 ? present.length === evidence.length : preLedgerStore && index < legacyCount;
25852
+ const wantsFkOff = /PRAGMA foreign_keys\s*=\s*OFF/i.test(migration.sql);
25853
+ const statements = splitStatements(migration.sql);
25854
+ if (wantsFkOff) db.exec("PRAGMA foreign_keys = OFF");
25855
+ try {
25856
+ withTransaction(
25857
+ db,
25858
+ () => {
25859
+ for (const statement of statements) {
25860
+ const indexName = createdIndexName(statement);
25861
+ if (indexName === void 0) {
25862
+ if (alreadyApplied) continue;
25863
+ } else if (indexExists(db, indexName)) {
25864
+ continue;
25865
+ }
25866
+ db.exec(statement);
25867
+ }
25868
+ if (wantsFkOff && !alreadyApplied) {
25869
+ const violations = db.prepare("PRAGMA foreign_key_check").all();
25870
+ if (violations.length > 0) {
25871
+ throw new Error(
25872
+ `[aka] sqlite migration ${migration.tag} left ${String(violations.length)} foreign-key violation(s); rolling back.`
25873
+ );
25874
+ }
25875
+ }
25876
+ record2.run(migration.tag, Date.now());
25877
+ },
25878
+ "IMMEDIATE"
25879
+ );
25880
+ } finally {
25881
+ if (wantsFkOff) db.exec("PRAGMA foreign_keys = ON");
25882
+ }
25883
+ }
25884
+ if (legacyCount < SQLITE_MIGRATIONS.length) {
25885
+ db.exec(`PRAGMA user_version = ${String(SQLITE_MIGRATIONS.length)}`);
25886
+ }
25887
+ ensureSyncedAtColumn(db, "audit_events");
25888
+ ensureScanLedgerTable(db);
25889
+ ensureHistorySyncTable(db);
25890
+ ensureBlockedDetectionsTable(db);
25891
+ ensureRuleProbeCacheTable(db);
25892
+ ensureWriteGateTrigger(db);
25893
+ ensureTokenUsageColumns(db);
25894
+ reconcileSourceProjectIds(db);
25895
+ if (!applied.has(LEGACY_DROP_MIGRATION_TAG)) {
25896
+ const drained = runLegacyHistoryBackfill(db);
25897
+ if (drained) applyLegacyDropMigration(db, file2);
25898
+ }
25899
+ }
25900
+ function readLegacyTables(db) {
25901
+ let holdsRows = false;
25902
+ const marks = [];
25903
+ for (const table of ["events", "findings"]) {
25904
+ try {
25905
+ const row = db.prepare(`SELECT count(*) AS n, ifnull(max(rowid), -1) AS hi FROM ${table}`).get();
25906
+ if (row === void 0) {
25907
+ holdsRows = true;
25908
+ marks.push(`${table}:unreadable`);
25909
+ continue;
25910
+ }
25911
+ if (row.n > 0) holdsRows = true;
25912
+ marks.push(`${table}:${String(row.n)}:${String(row.hi)}`);
25913
+ } catch {
25914
+ holdsRows = true;
25915
+ marks.push(`${table}:unreadable`);
25916
+ }
25917
+ }
25918
+ return { holdsRows, mark: marks.join("|") };
25919
+ }
25920
+ function applyLegacyDropMigration(db, file2) {
25921
+ const migration = SQLITE_MIGRATIONS.find((m) => m.tag === LEGACY_DROP_MIGRATION_TAG);
25922
+ if (!migration) return;
25923
+ const before = file2 === void 0 ? void 0 : readLegacyTables(db);
25924
+ if (file2 !== void 0 && before?.holdsRows === true) {
25925
+ try {
25926
+ backupBeforeLegacyDrop(db, file2);
25927
+ } catch (error61) {
25928
+ akaWarn(`legacy events/findings backup failed; deferring the drop: ${String(error61)}`);
25929
+ return;
25930
+ }
25931
+ }
25932
+ try {
25933
+ withTransaction(
25934
+ db,
25935
+ () => {
25936
+ const alreadyDropped = db.prepare("SELECT 1 FROM migration_ledger WHERE tag = ?").get(migration.tag);
25937
+ if (alreadyDropped) return;
25938
+ if (before !== void 0 && readLegacyTables(db).mark !== before.mark) {
25939
+ akaWarn(
25940
+ "legacy events/findings rows changed after the pre-drop snapshot decision; deferring the drop so the next open can copy them first."
25941
+ );
25942
+ return;
25943
+ }
25944
+ for (const statement of splitStatements(migration.sql)) {
25945
+ db.exec(statement);
25946
+ }
25947
+ db.prepare("INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)").run(
25948
+ migration.tag,
25949
+ Date.now()
25950
+ );
25951
+ },
25952
+ "IMMEDIATE"
25953
+ );
25954
+ } catch (error61) {
25955
+ akaWarn(`legacy events/findings drop failed; deferring: ${String(error61)}`);
25956
+ }
25957
+ }
25958
+ function backupBeforeLegacyDrop(db, file2) {
25959
+ reapStalePartials(file2);
25960
+ const backup = backupPath(file2, "pre-drop");
25961
+ snapshotStore(db, backup);
25962
+ return backup;
25963
+ }
25964
+ var TOKEN_USAGE_COLUMNS = [
25965
+ {
25966
+ name: "input_tokens",
25967
+ ddl: "ALTER TABLE audit_events ADD COLUMN input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.input_tokens')) VIRTUAL"
25968
+ },
25969
+ {
25970
+ name: "output_tokens",
25971
+ ddl: "ALTER TABLE audit_events ADD COLUMN output_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.output_tokens')) VIRTUAL"
25972
+ },
25973
+ {
25974
+ name: "cache_creation_input_tokens",
25975
+ ddl: "ALTER TABLE audit_events ADD COLUMN cache_creation_input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.cache_creation_input_tokens')) VIRTUAL"
25976
+ },
25977
+ {
25978
+ name: "cache_read_input_tokens",
25979
+ ddl: "ALTER TABLE audit_events ADD COLUMN cache_read_input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.cache_read_input_tokens')) VIRTUAL"
25980
+ },
25981
+ {
25982
+ name: "model",
25983
+ ddl: "ALTER TABLE audit_events ADD COLUMN model text GENERATED ALWAYS AS (json_extract(attributes, '$.model')) VIRTUAL"
25984
+ },
25985
+ {
25012
25986
  name: "provider",
25013
25987
  ddl: "ALTER TABLE audit_events ADD COLUMN provider text GENERATED ALWAYS AS (json_extract(attributes, '$.provider')) VIRTUAL"
25014
25988
  }
@@ -25271,10 +26245,62 @@ function ensureSyncedAtColumn(db, table) {
25271
26245
  if (!columns.includes("outbox_owed")) {
25272
26246
  db.exec(`ALTER TABLE ${table} ADD COLUMN outbox_owed integer`);
25273
26247
  }
26248
+ if (!columns.includes("sync_failed_at")) {
26249
+ db.exec(`ALTER TABLE ${table} ADD COLUMN sync_failed_at integer`);
26250
+ }
26251
+ if (!columns.includes("sync_failure")) {
26252
+ withTransaction(
26253
+ db,
26254
+ () => {
26255
+ db.exec(`ALTER TABLE ${table} ADD COLUMN sync_failure text`);
26256
+ db.exec(
26257
+ `UPDATE ${table} SET synced_at = NULL
26258
+ WHERE synced_at = -1
26259
+ AND event_type IN (${COUNTED_EVENT_TYPES.map((t) => `'${t}'`).join(", ")})`
26260
+ );
26261
+ },
26262
+ "IMMEDIATE"
26263
+ );
26264
+ }
25274
26265
  db.exec(
25275
- `CREATE INDEX IF NOT EXISTS idx_audit_events_sync
25276
- ON audit_events (event_type, synced_at, sync_claimed_at, started_at)`
26266
+ `CREATE TRIGGER IF NOT EXISTS aka_sync_failure_guard
26267
+ BEFORE UPDATE OF sync_failure ON ${table}
26268
+ WHEN ${syncFailureRejectCondition()}
26269
+ BEGIN SELECT RAISE(ABORT, 'sync_failure is not one of the recorded reasons'); END`
25277
26270
  );
26271
+ const syncIndexColumns = [
26272
+ "event_type",
26273
+ "synced_at",
26274
+ "sync_claimed_at",
26275
+ "started_at",
26276
+ // Appended LAST on purpose. The delivery-state read now projects it, so it
26277
+ // has to be in the index for the read to stay covered — but putting it
26278
+ // ahead of `started_at` would reorder the prefix the structural drain's
26279
+ // reads match on.
26280
+ "sync_failure"
26281
+ // `outbox_owed` is DELIBERATELY ABSENT, and it was measured both ways.
26282
+ //
26283
+ // The delivery-state read tests it — a capture's state depends on whether a
26284
+ // live forward marked it owed — so carrying it here makes that read covering
26285
+ // rather than a row fetch per row: 16 ms against 40 ms on a real 6 GB store.
26286
+ // But a sixth column changes what the planner charges for this index, and
26287
+ // with no ANALYZE statistics it plans from schema shape alone: measured, it
26288
+ // then stops choosing the per-session index for the token rollup and walks
26289
+ // every `llm_call` in the store through the event-type index instead. That
26290
+ // read grows with the store; this one does not.
26291
+ //
26292
+ // 40 ms on the largest store measured, once per render, is a cost worth
26293
+ // paying to leave every other read's plan where it was.
26294
+ ];
26295
+ const currentSyncIndex = indexColumns(db, "idx_audit_events_sync");
26296
+ const syncIndexMatches = currentSyncIndex.length === syncIndexColumns.length && currentSyncIndex.every((column, i) => column === syncIndexColumns[i]);
26297
+ if (!syncIndexMatches) {
26298
+ db.exec("DROP INDEX IF EXISTS idx_audit_events_sync");
26299
+ db.exec(
26300
+ `CREATE INDEX idx_audit_events_sync
26301
+ ON audit_events (${syncIndexColumns.join(", ")})`
26302
+ );
26303
+ }
25278
26304
  db.exec(
25279
26305
  `CREATE INDEX IF NOT EXISTS idx_audit_outbox_owed
25280
26306
  ON audit_events (event_type, synced_at, sync_claimed_at, started_at) WHERE outbox_owed = 1`
@@ -25496,7 +26522,11 @@ function buildAuditEvent(row) {
25496
26522
  link: linkParsed?.success ? linkParsed.data : null,
25497
26523
  targetId: row.target_id,
25498
26524
  internal: intToBool(row.internal),
25499
- flagged: intToBool(row.flagged)
26525
+ flagged: intToBool(row.flagged),
26526
+ // Only meaningful when the title came out empty — a row whose body was
26527
+ // expired but whose title fell back to `tool_name` still has something to
26528
+ // render, and flagging it would make the view apologise for nothing.
26529
+ bodyExpired: row.content_expired_at !== null && (row.title ?? "") === ""
25500
26530
  };
25501
26531
  }
25502
26532
  var TIMELINE_COLUMNS = `
@@ -25504,6 +26534,7 @@ var TIMELINE_COLUMNS = `
25504
26534
  event_type,
25505
26535
  started_at,
25506
26536
  coalesce(content, json_extract(attributes, '$.tool_name')) AS title,
26537
+ content_expired_at,
25507
26538
  coalesce(json_extract(attributes, '$.detail'), json_extract(attributes, '$.target')) AS detail,
25508
26539
  coalesce(json_extract(attributes, '$.tool_name'), json_extract(attributes, '$.tool')) AS tool,
25509
26540
  json_extract(attributes, '$.severity') AS severity,
@@ -26169,6 +27200,88 @@ var SqliteAuditEventsRepository = class {
26169
27200
  }
26170
27201
  };
26171
27202
 
27203
+ // ../../packages/persistence/src/repositories/body-retention.ts
27204
+ var DEFAULT_BATCH_SIZE = 500;
27205
+ var DEFAULT_MAX_ROWS = 5e4;
27206
+ var SYNC_LANE_TYPES_SQL = OUTBOX_CAPTURE_TYPE_LIST;
27207
+ var SqliteBodyRetentionRepository = class {
27208
+ constructor(db) {
27209
+ this.db = db;
27210
+ const select = (laneClause) => `
27211
+ SELECT id, LENGTH(CAST(content AS BLOB)) AS bytes
27212
+ FROM audit_events
27213
+ WHERE content IS NOT NULL
27214
+ AND started_at < :cutoff
27215
+ AND event_type IN (${CAPTURE_EVENT_TYPES_SQL})
27216
+ ${laneClause}
27217
+ ORDER BY started_at
27218
+ LIMIT :limit`;
27219
+ this.candidatesStmt = this.db.prepare(select(""));
27220
+ this.candidatesSyncSafeStmt = this.db.prepare(
27221
+ select(`AND (event_type NOT IN (${SYNC_LANE_TYPES_SQL}) OR synced_at IS NOT NULL)`)
27222
+ );
27223
+ this.heldBySyncStmt = this.db.prepare(`
27224
+ SELECT COUNT(*) AS n
27225
+ FROM audit_events
27226
+ WHERE content IS NOT NULL
27227
+ AND started_at < :cutoff
27228
+ AND event_type IN (${SYNC_LANE_TYPES_SQL})
27229
+ AND synced_at IS NULL`);
27230
+ this.expireStmt = this.db.prepare(
27231
+ `UPDATE audit_events SET content = NULL, content_expired_at = :now WHERE id = :id`
27232
+ );
27233
+ }
27234
+ db;
27235
+ candidatesStmt;
27236
+ candidatesSyncSafeStmt;
27237
+ heldBySyncStmt;
27238
+ expireStmt;
27239
+ /** How many bytes a pass with these options would free, changing nothing. */
27240
+ preview(opts) {
27241
+ const limit = opts.maxRows ?? DEFAULT_MAX_ROWS;
27242
+ const stmt = opts.sweepSyncLane ? this.candidatesStmt : this.candidatesSyncSafeStmt;
27243
+ const rows = stmt.all({ cutoff: opts.cutoff, limit });
27244
+ return {
27245
+ rowsExpired: rows.length,
27246
+ bytesFreed: rows.reduce((sum, r) => sum + r.bytes, 0),
27247
+ rowsHeldBySync: this.countHeldBySync(opts)
27248
+ };
27249
+ }
27250
+ /** Clear eligible bodies, in bounded batches. */
27251
+ expire(opts) {
27252
+ const batchSize = opts.batchSize ?? DEFAULT_BATCH_SIZE;
27253
+ const maxRows = opts.maxRows ?? DEFAULT_MAX_ROWS;
27254
+ const stmt = opts.sweepSyncLane ? this.candidatesStmt : this.candidatesSyncSafeStmt;
27255
+ let rowsExpired = 0;
27256
+ let bytesFreed = 0;
27257
+ let done = true;
27258
+ while (rowsExpired < maxRows) {
27259
+ const remaining = Math.min(batchSize, maxRows - rowsExpired);
27260
+ const batch = stmt.all({ cutoff: opts.cutoff, limit: remaining });
27261
+ if (batch.length === 0) break;
27262
+ withTransaction(
27263
+ this.db,
27264
+ () => {
27265
+ for (const row of batch) this.expireStmt.run({ id: row.id, now: opts.now });
27266
+ },
27267
+ "IMMEDIATE"
27268
+ );
27269
+ rowsExpired += batch.length;
27270
+ bytesFreed += batch.reduce((sum, r) => sum + r.bytes, 0);
27271
+ if (batch.length < remaining) break;
27272
+ if (rowsExpired >= maxRows) {
27273
+ done = stmt.all({ cutoff: opts.cutoff, limit: 1 }).length === 0;
27274
+ }
27275
+ }
27276
+ return { rowsExpired, bytesFreed, rowsHeldBySync: this.countHeldBySync(opts), done };
27277
+ }
27278
+ countHeldBySync(opts) {
27279
+ if (opts.sweepSyncLane) return 0;
27280
+ const row = this.heldBySyncStmt.get({ cutoff: opts.cutoff });
27281
+ return row.n;
27282
+ }
27283
+ };
27284
+
26172
27285
  // ../../packages/persistence/src/repositories/classified-data.ts
26173
27286
  var SqliteClassifiedDataRepository = class {
26174
27287
  constructor(db) {
@@ -26997,7 +28110,15 @@ function toFlatFindingRow(r) {
26997
28110
  ...r.tool_name === null ? {} : { toolName: r.tool_name },
26998
28111
  eventId: r.event_id,
26999
28112
  ...r.session_id === null ? {} : { sessionId: r.session_id },
27000
- status: deriveInstanceStatus(r)
28113
+ status: deriveInstanceStatus(r),
28114
+ delivery: deriveFindingDelivery({
28115
+ kind: r.kind,
28116
+ syncedAt: r.synced_at,
28117
+ syncClaimedAt: r.sync_claimed_at,
28118
+ syncFailedAt: r.sync_failed_at,
28119
+ syncFailure: r.sync_failure,
28120
+ outboxOwed: r.outbox_owed
28121
+ })
27001
28122
  };
27002
28123
  }
27003
28124
  function encodeGroupCursor(group) {
@@ -27061,7 +28182,10 @@ var FINDING_ROW_COLUMNS_SQL = `f.id AS id, d.rule_id AS rule_id, d.category AS c
27061
28182
  e.tool_name AS tool_name,
27062
28183
  f.audit_event_id AS event_id, e.root_session_id AS session_id,
27063
28184
  e.event_type AS kind, f.finding_key AS finding_key,
27064
- ${latestResolutionStatusSql("f")} AS latest_status`;
28185
+ ${latestResolutionStatusSql("f")} AS latest_status,
28186
+ e.synced_at AS synced_at, e.sync_claimed_at AS sync_claimed_at,
28187
+ e.sync_failed_at AS sync_failed_at, e.sync_failure AS sync_failure,
28188
+ e.outbox_owed AS outbox_owed`;
27065
28189
  var DAY_MS3 = 864e5;
27066
28190
  var SqliteFindingsRepository = class {
27067
28191
  constructor(db) {
@@ -27306,6 +28430,7 @@ var SqliteFindingsRepository = class {
27306
28430
  providers: query.provider,
27307
28431
  actions: query.action,
27308
28432
  statuses: query.status,
28433
+ deliveries: query.deployment,
27309
28434
  tools: query.tool,
27310
28435
  repo: query.repo,
27311
28436
  file: query.file,
@@ -27373,6 +28498,7 @@ var SqliteFindingsRepository = class {
27373
28498
  providers: query.provider,
27374
28499
  actions: query.action,
27375
28500
  statuses: query.status,
28501
+ deliveries: query.deployment,
27376
28502
  tools: query.tool,
27377
28503
  q: query.q
27378
28504
  };
@@ -27636,7 +28762,9 @@ var SqliteFindingsRepository = class {
27636
28762
  )
27637
28763
  );
27638
28764
  for (const row of grouped) {
27639
- if (row.action_taken in byAction) byAction[row.action_taken] = row.c;
28765
+ if (Object.hasOwn(byAction, row.action_taken)) {
28766
+ byAction[row.action_taken] = row.c;
28767
+ }
27640
28768
  }
27641
28769
  const bySeverity = { critical: 0, high: 0, medium: 0, low: 0 };
27642
28770
  const sevRows = allRows(
@@ -27653,7 +28781,9 @@ var SqliteFindingsRepository = class {
27653
28781
  )
27654
28782
  );
27655
28783
  for (const row of sevRows) {
27656
- if (row.severity in bySeverity) bySeverity[row.severity] = row.c;
28784
+ if (Object.hasOwn(bySeverity, row.severity)) {
28785
+ bySeverity[row.severity] = row.c;
28786
+ }
27657
28787
  }
27658
28788
  const categories = ENFORCEABLE_CATEGORIES;
27659
28789
  const enabledRows = allRows(
@@ -27702,525 +28832,6 @@ function isoDay(ms) {
27702
28832
  return new Date(ms).toISOString().slice(0, 10);
27703
28833
  }
27704
28834
 
27705
- // ../../packages/persistence/src/repositories/history-sync.ts
27706
- var STRUCTURAL_EVENT_TYPES = ["session", "llm_call", "tool_call"];
27707
- var TYPE_LIST = STRUCTURAL_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
27708
- var OUTBOX_CAPTURE_EVENT_TYPES = ["prompt", "response", "tool_use"];
27709
- var CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
27710
- var SKIPPED = -1;
27711
- var ROW_COLUMNS = `id,
27712
- parent_id AS parentId,
27713
- root_session_id AS rootSessionId,
27714
- event_type AS eventType,
27715
- host_id AS hostId,
27716
- harness_id AS harnessId,
27717
- source_project_id AS sourceProjectId,
27718
- started_at AS startedAt,
27719
- ended_at AS endedAt,
27720
- severity,
27721
- priority,
27722
- content,
27723
- content_hash AS contentHash,
27724
- attributes`;
27725
- var SqliteHistorySyncRepository = class {
27726
- constructor(db) {
27727
- this.db = db;
27728
- this.ensureRowStmt = db.prepare(`INSERT OR IGNORE INTO history_sync (id) VALUES (1)`);
27729
- this.sessionsStmt = db.prepare(
27730
- `SELECT COALESCE(root_session_id, id) AS sessionId, MIN(started_at) AS earliest
27731
- FROM audit_events
27732
- WHERE synced_at IS NULL
27733
- AND event_type IN (${TYPE_LIST})
27734
- AND started_at < :before
27735
- GROUP BY sessionId
27736
- ORDER BY earliest
27737
- LIMIT :limit`
27738
- );
27739
- this.rowsStmt = db.prepare(
27740
- `SELECT ${ROW_COLUMNS}
27741
- FROM audit_events
27742
- WHERE synced_at IS NULL
27743
- AND event_type IN (${TYPE_LIST})
27744
- AND started_at < :before
27745
- AND COALESCE(root_session_id, id) = :sessionId
27746
- ORDER BY (event_type = 'session') DESC, started_at
27747
- LIMIT :limit`
27748
- );
27749
- this.captureRowsStmt = db.prepare(
27750
- `SELECT ${ROW_COLUMNS}
27751
- FROM audit_events
27752
- WHERE synced_at IS NULL
27753
- AND sync_claimed_at IS NULL
27754
- AND outbox_owed = 1
27755
- AND event_type IN (${CAPTURE_TYPE_LIST})
27756
- AND started_at < :before
27757
- ORDER BY started_at
27758
- LIMIT :limit`
27759
- );
27760
- this.markOwedStmt = db.prepare(
27761
- `UPDATE audit_events SET outbox_owed = 1 WHERE id = :id AND synced_at IS NULL`
27762
- );
27763
- this.markCaptureBacklogOwedStmt = db.prepare(
27764
- `UPDATE audit_events SET outbox_owed = 1
27765
- WHERE synced_at IS NULL
27766
- AND event_type IN (${CAPTURE_TYPE_LIST})
27767
- AND started_at < :before`
27768
- );
27769
- this.stampStmt = db.prepare(
27770
- `UPDATE audit_events SET synced_at = :at, sync_claimed_at = NULL WHERE id = :id`
27771
- );
27772
- this.claimRowStmt = db.prepare(
27773
- `UPDATE audit_events SET sync_claimed_at = :at WHERE id = :id AND synced_at IS NULL`
27774
- );
27775
- this.releaseRowStmt = db.prepare(
27776
- `UPDATE audit_events SET sync_claimed_at = NULL WHERE id = :id`
27777
- );
27778
- this.releaseStaleClaimsStmt = db.prepare(
27779
- `UPDATE audit_events SET sync_claimed_at = NULL
27780
- WHERE sync_claimed_at IS NOT NULL AND sync_claimed_at < :staleBefore`
27781
- );
27782
- this.partitionStmt = db.prepare(
27783
- `SELECT
27784
- SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NULL THEN 1 ELSE 0 END) AS queued,
27785
- SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NOT NULL THEN 1 ELSE 0 END) AS inProgress,
27786
- SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS synced,
27787
- SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0 THEN 1 ELSE 0 END) AS failed,
27788
- COUNT(*) AS total
27789
- FROM audit_events
27790
- WHERE event_type IN (${TYPE_LIST})`
27791
- );
27792
- this.countsStmt = db.prepare(
27793
- `SELECT
27794
- SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
27795
- SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
27796
- SUM(CASE WHEN synced_at = ${String(SKIPPED)} THEN 1 ELSE 0 END) AS skipped
27797
- FROM audit_events
27798
- WHERE event_type IN (${TYPE_LIST})`
27799
- );
27800
- this.captureSkipCountStmt = db.prepare(
27801
- `SELECT COUNT(*) AS skipped
27802
- FROM audit_events
27803
- WHERE synced_at = ${String(SKIPPED)}
27804
- AND event_type IN (${CAPTURE_TYPE_LIST})`
27805
- );
27806
- this.fingerprintStmt = db.prepare(
27807
- `SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
27808
- FROM history_sync WHERE id = 1`
27809
- );
27810
- this.setFingerprintStmt = db.prepare(
27811
- `UPDATE history_sync
27812
- SET endpoint_fingerprint = :fingerprint, backlog_before = :backlogBefore
27813
- WHERE id = 1`
27814
- );
27815
- this.disownCapturesStmt = db.prepare(
27816
- `UPDATE audit_events SET outbox_owed = NULL
27817
- WHERE outbox_owed IS NOT NULL
27818
- AND event_type IN (${CAPTURE_TYPE_LIST})
27819
- AND started_at < :attachedAt`
27820
- );
27821
- this.rearmStmt = db.prepare(
27822
- `UPDATE audit_events SET synced_at = NULL
27823
- WHERE synced_at > 0 AND event_type IN (${TYPE_LIST})`
27824
- );
27825
- this.claimStmt = db.prepare(
27826
- `UPDATE history_sync
27827
- SET owner_pid = :pid, owner_host = :host, acquired_at = :now, heartbeat_at = :now
27828
- WHERE id = 1
27829
- AND (owner_pid IS NULL
27830
- OR heartbeat_at IS NULL
27831
- OR heartbeat_at < :staleBefore
27832
- OR heartbeat_at > :now)`
27833
- );
27834
- this.heartbeatStmt = db.prepare(
27835
- `UPDATE history_sync SET heartbeat_at = :now WHERE id = 1 AND owner_pid = :pid`
27836
- );
27837
- this.releaseStmt = db.prepare(
27838
- `UPDATE history_sync
27839
- SET owner_pid = NULL, owner_host = NULL, acquired_at = NULL, heartbeat_at = NULL
27840
- WHERE id = 1 AND owner_pid = :pid`
27841
- );
27842
- this.closeWindowStmt = db.prepare(
27843
- `UPDATE audit_events SET synced_at = :at
27844
- WHERE synced_at IS NULL
27845
- AND event_type IN (${TYPE_LIST})
27846
- AND started_at >= :attachedAt`
27847
- );
27848
- this.releaseBoundaryStmt = db.prepare(
27849
- `UPDATE history_sync SET backlog_before = NULL WHERE id = 1`
27850
- );
27851
- this.freezeBoundaryStmt = db.prepare(
27852
- `UPDATE history_sync SET backlog_before = :backlogBefore WHERE id = 1`
27853
- );
27854
- this.leaseStmt = db.prepare(
27855
- `SELECT owner_pid AS ownerPid, owner_host AS ownerHost,
27856
- acquired_at AS acquiredAt, heartbeat_at AS heartbeatAt
27857
- FROM history_sync WHERE id = 1`
27858
- );
27859
- this.inspectionsStmt = db.prepare(
27860
- `SELECT d.rule_id AS ruleId,
27861
- d.name AS ruleName,
27862
- d.version AS ruleVersion,
27863
- d.category AS category,
27864
- d.severity AS severity,
27865
- f.span_start AS spanStart,
27866
- f.span_end AS spanEnd,
27867
- f.masked_match AS maskedMatch,
27868
- f.action_taken AS actionTaken,
27869
- f.confidence AS confidence
27870
- FROM inspection_findings f
27871
- JOIN inspection_definitions d ON d.id = f.inspection_definition_id
27872
- WHERE f.audit_event_id = :auditEventId
27873
- ORDER BY f.span_start, f.id`
27874
- );
27875
- }
27876
- db;
27877
- ensureRowStmt;
27878
- sessionsStmt;
27879
- rowsStmt;
27880
- stampStmt;
27881
- countsStmt;
27882
- fingerprintStmt;
27883
- setFingerprintStmt;
27884
- rearmStmt;
27885
- claimStmt;
27886
- heartbeatStmt;
27887
- releaseStmt;
27888
- leaseStmt;
27889
- inspectionsStmt;
27890
- closeWindowStmt;
27891
- releaseBoundaryStmt;
27892
- freezeBoundaryStmt;
27893
- captureRowsStmt;
27894
- markOwedStmt;
27895
- markCaptureBacklogOwedStmt;
27896
- captureSkipCountStmt;
27897
- disownCapturesStmt;
27898
- partitionStmt;
27899
- claimRowStmt;
27900
- releaseRowStmt;
27901
- releaseStaleClaimsStmt;
27902
- /**
27903
- * The masked detections recorded against one tool call.
27904
- *
27905
- * These travel with the event because a tool call's target is not
27906
- * re-inspectable from the event alone — unlike a capture, where the text
27907
- * itself is re-scannable. What crosses is the masked match and the rule that
27908
- * produced it, never the value.
27909
- */
27910
- inspectionsFor(auditEventId) {
27911
- return allRows(this.inspectionsStmt, { auditEventId });
27912
- }
27913
- /**
27914
- * Sessions with structural rows still to send, oldest first.
27915
- *
27916
- * BOUNDED BY THE BACKLOG BOUNDARY, which is the whole correctness of this
27917
- * read. Anything recorded after the machine attached is the live forward
27918
- * path's to deliver; this drain exists for what was recorded before it, and a
27919
- * row both paths send is at best a duplicate request and at worst — for a
27920
- * session root — an overwrite of the inventory ids the live path resolved.
27921
- */
27922
- pendingSessions(limit, before) {
27923
- return allRows(this.sessionsStmt, { limit, before }).map(
27924
- (r) => r.sessionId
27925
- );
27926
- }
27927
- /** One session's undelivered structural rows within the backlog, root first. */
27928
- pendingRows(sessionId, limit, before) {
27929
- return allRows(this.rowsStmt, { sessionId, limit, before });
27930
- }
27931
- /**
27932
- * Captures this machine still owes the deployment, oldest first.
27933
- *
27934
- * Selected by the `outbox_owed` marker the attached forward path writes, not
27935
- * by a time window — see captureRowsStmt for why a window could not express
27936
- * this. `before` is the grace window that leaves a just-recorded capture to
27937
- * the live path.
27938
- */
27939
- pendingCaptureRows(limit, before) {
27940
- return allRows(this.captureRowsStmt, { limit, before });
27941
- }
27942
- /**
27943
- * Record that a capture is OWED to the deployment.
27944
- *
27945
- * Written by the attached forward path when a live send did not confirm
27946
- * delivery, and read by the drain as the whole of its eligibility test. It is
27947
- * a fact rather than an inference: the machine was attached, the send did not
27948
- * land, so the row is owed — which no time window can state, because the same
27949
- * window that holds the rows a past attachment left owed also holds every
27950
- * capture recorded while the machine was DETACHED, and those were never
27951
- * offered to anyone.
27952
- *
27953
- * Idempotent, and never un-set: `markSynced` settling the row is what takes it
27954
- * out of the drain's read.
27955
- */
27956
- markCaptureOwed(id) {
27957
- this.markOwedStmt.run({ id });
27958
- }
27959
- /**
27960
- * Mark every capture already on disk as owed, as of `before`.
27961
- *
27962
- * The consent-time backfill, called once from `aka attach` when a human
27963
- * grants existing-history consent — never from an ongoing drain pass, and
27964
- * never inferred from a boundary that could later move. `before` is the
27965
- * caller's own "now" at the moment consent was granted, so what this marks
27966
- * is exactly the backlog the consent prompt already counted, not whatever a
27967
- * later re-attach or key rotation might widen it to.
27968
- *
27969
- * Returns how many rows matched, for the caller to log or test against. Not a
27970
- * count of NEWLY marked rows — a row still unsynced from an earlier call
27971
- * matches again and is counted again, the same as `UPDATE`'s own `changes`.
27972
- */
27973
- markCaptureBacklogOwed(before) {
27974
- return Number(this.markCaptureBacklogOwedStmt.run({ before }).changes);
27975
- }
27976
- /** Record delivery. Called only AFTER the far side has accepted the rows. */
27977
- markSynced(ids, atMs) {
27978
- this.stampAll(ids, atMs);
27979
- }
27980
- /**
27981
- * Record that a row will never be sent.
27982
- *
27983
- * Reserved for a local defect — a row that cannot be rebuilt into a valid
27984
- * payload. A row that merely failed to reach the deployment stays NULL, so it
27985
- * is retried; marking those would turn one outage into permanent data loss.
27986
- */
27987
- markSkipped(ids) {
27988
- this.stampAll(ids, SKIPPED);
27989
- }
27990
- eachInTransaction(ids, run) {
27991
- if (ids.length === 0) return;
27992
- withTransaction(
27993
- this.db,
27994
- () => {
27995
- for (const id of ids) run(id);
27996
- },
27997
- "IMMEDIATE"
27998
- );
27999
- }
28000
- stampAll(ids, value) {
28001
- if (ids.length === 0) return;
28002
- withTransaction(
28003
- this.db,
28004
- () => {
28005
- for (const id of ids) this.stampStmt.run({ at: value, id });
28006
- },
28007
- "IMMEDIATE"
28008
- );
28009
- }
28010
- /**
28011
- * Claim rows as in-flight.
28012
- *
28013
- * Advisory in exactly the sense the lease is: it records that a send is in
28014
- * progress so a surface can say so, and a lost claim costs a row showing as
28015
- * queued while it is actually being sent. It is not exclusion — the far side
28016
- * settles a duplicate on the row id.
28017
- */
28018
- claimRows(ids, atMs) {
28019
- this.eachInTransaction(ids, (id) => this.claimRowStmt.run({ at: atMs, id }));
28020
- }
28021
- /** Give back a claim without settling — the send failed, the row is queued again. */
28022
- releaseRows(ids) {
28023
- this.eachInTransaction(ids, (id) => this.releaseRowStmt.run({ id }));
28024
- }
28025
- /**
28026
- * Clear claims older than `staleBefore`, and report how many were cleared.
28027
- *
28028
- * A process killed between claiming and settling leaves rows claimed with
28029
- * nothing left to settle them. Without this they read as "sending" for ever.
28030
- */
28031
- releaseStaleClaims(staleBefore) {
28032
- return Number(this.releaseStaleClaimsStmt.run({ staleBefore }).changes);
28033
- }
28034
- /**
28035
- * Every tracked row in exactly one delivery state.
28036
- *
28037
- * Takes no boundary on purpose. The boundary answers "what should the drain
28038
- * pick up now", which is a different question from "what state is this row
28039
- * in" — and a machine that has never attached has no boundary to pass, so
28040
- * requiring one would force a caller to invent one and report the whole store
28041
- * as queued.
28042
- */
28043
- partition() {
28044
- const row = getRow(this.partitionStmt, {});
28045
- return {
28046
- queued: row?.queued ?? 0,
28047
- inProgress: row?.inProgress ?? 0,
28048
- synced: row?.synced ?? 0,
28049
- failed: row?.failed ?? 0,
28050
- total: row?.total ?? 0
28051
- };
28052
- }
28053
- /** `pending` counts only what is inside the backlog; sent and skipped are totals. */
28054
- counts(before) {
28055
- const row = getRow(
28056
- this.countsStmt,
28057
- { before }
28058
- );
28059
- const captures = getRow(this.captureSkipCountStmt);
28060
- return {
28061
- pending: row?.pending ?? 0,
28062
- sent: row?.sent ?? 0,
28063
- skipped: row?.skipped ?? 0,
28064
- capturesSkipped: captures?.skipped ?? 0
28065
- };
28066
- }
28067
- /**
28068
- * The deployment the current stamps were made against, and where its backlog
28069
- * ends.
28070
- *
28071
- * READ-ONLY. An absent row reads as an absent deployment, which is what a
28072
- * machine that has never drained is — and every writer below seeds the row
28073
- * before it needs one, so nothing depends on this creating it. Keeping the
28074
- * write off the gate path matters because the gate runs on every pass while a
28075
- * write has to take the database's write lock.
28076
- */
28077
- deployment() {
28078
- const row = getRow(
28079
- this.fingerprintStmt
28080
- );
28081
- return {
28082
- fingerprint: row?.fingerprint ?? void 0,
28083
- backlogBefore: row?.backlogBefore ?? void 0
28084
- };
28085
- }
28086
- /**
28087
- * Point the ledger at a different deployment, discarding what it recorded
28088
- * about the previous one.
28089
- *
28090
- * Delivery is a fact about ONE recipient: rows sent to the deployment a
28091
- * machine has just left are undelivered as far as the new one is concerned.
28092
- * All four in one transaction, so a crash between them cannot leave stamps
28093
- * attributed to the wrong deployment, a boundary that belongs to another, or
28094
- * a disown with no re-mark to follow it.
28095
- *
28096
- * The boundary is written HERE and only here, which is what freezes it: a
28097
- * re-attach to the SAME deployment (a key rotation) leaves the fingerprint
28098
- * unchanged, so this never runs and the backlog does not widen back over rows
28099
- * the live path has since delivered.
28100
- *
28101
- * `backfillCapturesBefore` is the caller's OWN "now" at the instant a human
28102
- * granted existing-history consent for the deployment this call is arming —
28103
- * a DIFFERENT instant from `backlogBefore`: the re-mark boundary is the GRANT
28104
- * instant, `backlogBefore` is the ATTACH instant, and the two can be far
28105
- * apart. Passed only when that grant is valid, since this method has no way
28106
- * to check consent itself and must not mark a row owed for a machine that
28107
- * never agreed to it. Applied AFTER the disown above, in the SAME
28108
- * transaction: what the disown clears is every marker below `backlogBefore`,
28109
- * which includes this deployment's OWN pre-attach rows — `aka attach` calls
28110
- * `seedCaptureBacklogOwed` at the attach instant, so every row it marks sits
28111
- * on the cleared side of that bound — and the re-mark in the same
28112
- * transaction is what puts those rows back. A crash between the two cannot
28113
- * strand the ledger disowned with nothing re-marked — the transaction either
28114
- * lands whole or not at all, and a fingerprint mismatch that has not yet
28115
- * committed re-enters this method on the very next pass. Omit it (the
28116
- * structural-only tests do) to exercise the disown in isolation.
28117
- *
28118
- * The disown is bounded by `backlogBefore`, which is what keeps it from
28119
- * touching a marker the NEW deployment's OWN live path has already set: B's
28120
- * live path can mark a capture owed from the moment `aka attach` writes the
28121
- * descriptor, before the drain's first pass ever reaches this method, and
28122
- * such a row sits at or after the bound rather than below it. What keeps the
28123
- * disown from eating THIS SAME CALL's own re-mark is the order, not the
28124
- * bound — disown runs first, re-mark second, both inside the one
28125
- * transaction above.
28126
- */
28127
- rearmFor(fingerprint, backlogBefore, backfillCapturesBefore) {
28128
- this.ensureRowStmt.run();
28129
- withTransaction(
28130
- this.db,
28131
- () => {
28132
- const previous = getRow(this.fingerprintStmt)?.fingerprint;
28133
- this.rearmStmt.run();
28134
- if (previous !== null && previous !== void 0 && previous !== fingerprint) {
28135
- this.disownCapturesStmt.run({ attachedAt: backlogBefore });
28136
- }
28137
- if (backfillCapturesBefore !== void 0) {
28138
- this.markCaptureBacklogOwedStmt.run({ before: backfillCapturesBefore });
28139
- }
28140
- this.setFingerprintStmt.run({ fingerprint, backlogBefore });
28141
- },
28142
- "IMMEDIATE"
28143
- );
28144
- }
28145
- /**
28146
- * End the attached period: hand its rows to the live path, and release the
28147
- * boundary so the next attachment can freeze a new one.
28148
- *
28149
- * WITHOUT THIS, a detach and a re-attach to the same deployment leave a window
28150
- * nothing delivers. The fingerprint is unchanged, so the boundary is never
28151
- * re-frozen and stays at the FIRST attachment — while nothing forwards at all
28152
- * during the detached period, because the machine is not attached. Rows
28153
- * recorded in that window sit after the boundary and before the re-attach, so
28154
- * neither path takes them, and the pending count reports none outstanding.
28155
- *
28156
- * Stamping the attached window is not a claim that every one of those rows
28157
- * reached the deployment — the live path drops on failure and says so
28158
- * elsewhere. It records that they were ITS to deliver, which is exactly the
28159
- * status quo: they sit outside the frozen boundary today and are equally never
28160
- * re-sent. Making it explicit is what lets the boundary move.
28161
- *
28162
- * ONE TRANSACTION, so a crash cannot release the boundary while leaving the
28163
- * window unstamped — that half-state would re-send the whole attached period
28164
- * on the next attach, which is the failure the boundary exists to prevent.
28165
- */
28166
- closeAttachedWindow(attachedAtMs, atMs) {
28167
- this.ensureRowStmt.run();
28168
- withTransaction(
28169
- this.db,
28170
- () => {
28171
- const row = getRow(this.fingerprintStmt);
28172
- const from = row?.backlogBefore ?? attachedAtMs;
28173
- this.closeWindowStmt.run({ at: atMs, attachedAt: from });
28174
- this.releaseBoundaryStmt.run();
28175
- },
28176
- "IMMEDIATE"
28177
- );
28178
- }
28179
- /**
28180
- * Freeze a boundary for the deployment already on file, KEEPING the stamps.
28181
- *
28182
- * The re-attach half of the above. Distinct from `rearmFor`, which is for a
28183
- * different deployment and therefore discards what was delivered to the old
28184
- * one: here the recipient is the same, so everything already sent to it stays
28185
- * sent.
28186
- */
28187
- freezeBoundary(backlogBefore) {
28188
- this.ensureRowStmt.run();
28189
- this.freezeBoundaryStmt.run({ backlogBefore });
28190
- }
28191
- /** Take the claim, or report that someone live already holds it. */
28192
- claim(pid, host, nowMs, staleAfterMs) {
28193
- this.ensureRowStmt.run();
28194
- let taken = false;
28195
- withTransaction(
28196
- this.db,
28197
- () => {
28198
- const result = this.claimStmt.run({
28199
- pid,
28200
- host,
28201
- now: nowMs,
28202
- staleBefore: nowMs - staleAfterMs
28203
- });
28204
- taken = result.changes === 1;
28205
- },
28206
- "IMMEDIATE"
28207
- );
28208
- return taken;
28209
- }
28210
- /** Say the holder is still alive. A no-op once the claim has moved on. */
28211
- heartbeat(pid, nowMs) {
28212
- this.heartbeatStmt.run({ now: nowMs, pid });
28213
- }
28214
- /** Give the claim up. Scoped to this holder, so a taken-over claim is left be. */
28215
- release(pid) {
28216
- this.releaseStmt.run({ pid });
28217
- }
28218
- /** Who holds the claim, if anyone. Read-only, for the same reason as above. */
28219
- lease() {
28220
- return getRow(this.leaseStmt);
28221
- }
28222
- };
28223
-
28224
28835
  // ../../packages/persistence/src/repositories/inspection-definitions.ts
28225
28836
  var SqliteInspectionDefinitionsRepository = class {
28226
28837
  constructor(db) {
@@ -28451,6 +29062,7 @@ function overlayManagedSettings(settings, managed, now = () => /* @__PURE__ */ n
28451
29062
  if (values.vaultInlineReveal !== void 0) merged.vaultInlineReveal = values.vaultInlineReveal;
28452
29063
  if (values.dataSharesInPlace !== void 0) merged.dataSharesInPlace = values.dataSharesInPlace;
28453
29064
  if (values.redactFallback !== void 0) merged.redactFallback = values.redactFallback;
29065
+ if (values.bodyRetention !== void 0) merged.bodyRetention = values.bodyRetention;
28454
29066
  if (values.vaultConsent !== void 0) {
28455
29067
  merged.vaultConsent = values.vaultConsent ? (
28456
29068
  // Keep an existing valid grant so its acknowledgedAt survives; mint one
@@ -30958,7 +31570,7 @@ var SqliteSecurityRepository = class {
30958
31570
  ELSE 0
30959
31571
  END) AS open_at_rest
30960
31572
  FROM inspection_findings f
30961
- JOIN audit_events e ON e.id = f.audit_event_id
31573
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
30962
31574
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
30963
31575
  LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
30964
31576
  ON latest.finding_key = f.finding_key
@@ -31184,7 +31796,7 @@ var SqliteSecurityRepository = class {
31184
31796
  this.db.prepare(
31185
31797
  `SELECT e.repo AS repo, count(*) AS c
31186
31798
  FROM inspection_findings f
31187
- JOIN audit_events e ON e.id = f.audit_event_id
31799
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31188
31800
  WHERE e.started_at >= :from AND e.started_at < :to
31189
31801
  AND e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
31190
31802
  AND e.repo IS NOT NULL
@@ -31308,7 +31920,7 @@ var SqliteSecurityRepository = class {
31308
31920
  d.severity AS severity,
31309
31921
  COUNT(*) AS count
31310
31922
  FROM inspection_findings f
31311
- JOIN audit_events e ON e.id = f.audit_event_id
31923
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31312
31924
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
31313
31925
  LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
31314
31926
  ON latest.finding_key = f.finding_key
@@ -31343,7 +31955,7 @@ var SqliteSecurityRepository = class {
31343
31955
  `SELECT e.started_at AS occurred_at, d.severity AS severity, f.action_taken AS action_taken,
31344
31956
  d.rule_id AS rule_id, d.category AS category
31345
31957
  FROM inspection_findings f
31346
- JOIN audit_events e ON e.id = f.audit_event_id
31958
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31347
31959
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
31348
31960
  WHERE e.started_at >= :from AND e.started_at < :to
31349
31961
  AND e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
@@ -32184,6 +32796,7 @@ function openWithPragmas(file2) {
32184
32796
  db.exec("PRAGMA journal_mode = WAL");
32185
32797
  db.exec("PRAGMA busy_timeout = 2000");
32186
32798
  db.exec("PRAGMA foreign_keys = ON");
32799
+ registerSqlFunctions(db);
32187
32800
  } catch (err) {
32188
32801
  closeQuietly(db);
32189
32802
  throw err;
@@ -32213,7 +32826,7 @@ function backupLegacyStore(db, file2) {
32213
32826
  discardStore(file2, backup);
32214
32827
  return backup;
32215
32828
  }
32216
- function openAndInitialize(file2, base) {
32829
+ function openAndInitialize(file2, base, skipTags) {
32217
32830
  let db = openWithPragmas(file2);
32218
32831
  try {
32219
32832
  if (isForeignSqliteLineage(db)) {
@@ -32223,7 +32836,7 @@ function openAndInitialize(file2, base) {
32223
32836
  `Detected an older, incompatible (tenant-bearing) ${DB_FILENAME}; backed it up to ${backup} and created a fresh store.`
32224
32837
  );
32225
32838
  }
32226
- applyMigrations(db, file2);
32839
+ applyMigrations(db, file2, { skipTags });
32227
32840
  tightenPerms(file2);
32228
32841
  const policies = new SqlitePoliciesRepository(db);
32229
32842
  const installedPacks = new SqliteInstalledPacksRepository(db, base);
@@ -32238,6 +32851,7 @@ function openAndInitialize(file2, base) {
32238
32851
  exceptions: new SqliteExceptionsRepository(db),
32239
32852
  resolutions: new SqliteResolutionsRepository(db),
32240
32853
  ruleProbeCache: new SqliteRuleProbeCacheRepository(db),
32854
+ bodyRetention: new SqliteBodyRetentionRepository(db),
32241
32855
  security: new SqliteSecurityRepository(db),
32242
32856
  detections: new SqliteDetectionsRepository(db),
32243
32857
  shares: new SqliteSharesRepository(db),
@@ -32260,7 +32874,8 @@ function openAndInitialize(file2, base) {
32260
32874
  throw err;
32261
32875
  }
32262
32876
  }
32263
- function openLocalDatabase(dir) {
32877
+ var DEFERRED_TAGS = new Set(DEFERRED_MIGRATION_TAGS);
32878
+ function openLocalDatabase(dir, options = {}) {
32264
32879
  ensureDataDirSync(dir);
32265
32880
  const file2 = join7(dir, DB_FILENAME);
32266
32881
  reapStalePartials(file2);
@@ -32272,6 +32887,7 @@ function openLocalDatabase(dir) {
32272
32887
  installedPacks,
32273
32888
  scanLedger,
32274
32889
  historySync,
32890
+ bodyRetention,
32275
32891
  secretVault,
32276
32892
  exceptions,
32277
32893
  resolutions,
@@ -32295,7 +32911,8 @@ function openLocalDatabase(dir) {
32295
32911
  // `dir` is always `<base>/data` — every caller resolves it through
32296
32912
  // `dataDir()` — so its parent is the `~/.aka` base the layout splits into
32297
32913
  // settings/ and data/, and the pack-policy floor needs both halves.
32298
- dirname2(dir)
32914
+ dirname2(dir),
32915
+ options.applyDeferredMigrations === true ? void 0 : DEFERRED_TAGS
32299
32916
  );
32300
32917
  function captureRowId(event) {
32301
32918
  return captureId(
@@ -32488,6 +33105,7 @@ function openLocalDatabase(dir) {
32488
33105
  installedPacks,
32489
33106
  scanLedger,
32490
33107
  historySync,
33108
+ bodyRetention,
32491
33109
  secretVault,
32492
33110
  exceptions,
32493
33111
  resolutions,
@@ -32528,8 +33146,35 @@ function openLocalDatabase(dir) {
32528
33146
 
32529
33147
  // ../../packages/persistence/src/egress-wire.ts
32530
33148
  import { createHash as createHash3 } from "crypto";
33149
+ var PROJECT_KEY_DIGEST_VERSION = "v2";
33150
+ var SCP_FORM = /^(?:[^@/]+@)?([^/:]+):(.+)$/;
33151
+ var DOS_DRIVE = /^[A-Za-z]:[\\/]/;
33152
+ var FILE_URL = /^file:\/\//i;
33153
+ var SCHEME_FORM = /^[a-z][a-z0-9+.-]*:\/\/(?:[^@/]+@)?([^/:]+)(?::\d+)?(\/.*)?$/i;
33154
+ var SLASH = "/".charCodeAt(0);
33155
+ var GIT_SUFFIX = ".git";
33156
+ function trimSlashes(path) {
33157
+ let start = 0;
33158
+ let end = path.length;
33159
+ while (start < end && path.charCodeAt(start) === SLASH) start += 1;
33160
+ while (end > start && path.charCodeAt(end - 1) === SLASH) end -= 1;
33161
+ return path.slice(start, end);
33162
+ }
33163
+ function canonicalGitUrl(url2) {
33164
+ const trimmed = url2.trim();
33165
+ if (DOS_DRIVE.test(trimmed) || FILE_URL.test(trimmed)) return trimmed;
33166
+ const scheme = SCHEME_FORM.exec(trimmed);
33167
+ const scp = scheme === null ? SCP_FORM.exec(trimmed) : null;
33168
+ const host = (scheme?.[1] ?? scp?.[1])?.toLowerCase();
33169
+ if (host === void 0) return trimmed;
33170
+ const path = (scheme === null ? scp?.[2] : scheme[2]) ?? "";
33171
+ const bare = trimSlashes(path);
33172
+ const cleaned = bare.endsWith(GIT_SUFFIX) ? bare.slice(0, -GIT_SUFFIX.length) : bare;
33173
+ return cleaned === "" ? host : `${host}/${cleaned}`;
33174
+ }
32531
33175
  function hashProjectKey(projectKey) {
32532
- return createHash3("sha256").update(projectKey, "utf8").digest("hex");
33176
+ const canonical = projectKey.startsWith("git:") ? `git:${canonicalGitUrl(projectKey.slice("git:".length))}` : projectKey;
33177
+ return createHash3("sha256").update(`${PROJECT_KEY_DIGEST_VERSION}:${canonical}`, "utf8").digest("hex");
32533
33178
  }
32534
33179
  function toIngestHit(hit) {
32535
33180
  return {
@@ -32716,18 +33361,50 @@ function fingerprintValue(key, raw) {
32716
33361
  return createHmac("sha256", key.material).update(raw, "utf8").digest("hex");
32717
33362
  }
32718
33363
 
33364
+ // ../../packages/persistence/src/forward-health.ts
33365
+ import { readFileSync as readFileSync7 } from "fs";
33366
+ import { join as join9 } from "path";
33367
+ var FAILURES = /* @__PURE__ */ new Set([
33368
+ "unauthorized",
33369
+ "forbidden",
33370
+ "unreachable"
33371
+ ]);
33372
+ var BREAKER_COOLDOWN_MS = 3e4;
33373
+ function parseForwardHealth(raw, nowMs) {
33374
+ try {
33375
+ const parsed2 = JSON.parse(raw);
33376
+ if (typeof parsed2 !== "object" || parsed2 === null) return null;
33377
+ const record2 = parsed2;
33378
+ const failures = typeof record2.consecutiveFailures === "number" && record2.consecutiveFailures >= 0 ? record2.consecutiveFailures : 0;
33379
+ const openedAtMs = typeof record2.openedAtMs === "number" && Number.isFinite(record2.openedAtMs) && record2.openedAtMs <= nowMs ? record2.openedAtMs : null;
33380
+ const lastFailure = typeof record2.lastFailure === "string" && FAILURES.has(record2.lastFailure) ? record2.lastFailure : null;
33381
+ return { consecutiveFailures: failures, openedAtMs, lastFailure };
33382
+ } catch {
33383
+ return null;
33384
+ }
33385
+ }
33386
+ function isForwardPaused(health, nowMs) {
33387
+ const openedAtMs = health?.openedAtMs ?? null;
33388
+ if (openedAtMs === null) return false;
33389
+ return nowMs - openedAtMs < BREAKER_COOLDOWN_MS;
33390
+ }
33391
+
32719
33392
  // ../../packages/persistence/src/history-backfill.ts
32720
33393
  import { existsSync as existsSync4 } from "fs";
32721
- import { join as join9 } from "path";
33394
+ import { join as join10 } from "path";
32722
33395
 
32723
33396
  // ../../packages/persistence/src/history-preview.ts
32724
33397
  import { existsSync as existsSync5 } from "fs";
32725
- import { join as join10 } from "path";
33398
+ import { join as join11 } from "path";
32726
33399
  import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
32727
33400
 
33401
+ // ../../packages/persistence/src/history-sync-state.ts
33402
+ import { readFileSync as readFileSync8 } from "fs";
33403
+ import { join as join12 } from "path";
33404
+
32728
33405
  // ../../packages/persistence/src/store-symlinks.ts
32729
33406
  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";
33407
+ import { dirname as dirname3, join as join13, resolve } from "path";
32731
33408
 
32732
33409
  // ../../packages/persistence/src/vault/crypto.ts
32733
33410
  import {
@@ -32840,8 +33517,8 @@ function formatPointer(category, keyVersion, pointerId, tag) {
32840
33517
  // ../../packages/persistence/src/vault/key-provider.ts
32841
33518
  import { execFileSync } from "child_process";
32842
33519
  import { randomBytes as randomBytes2 } from "crypto";
32843
- import { chmodSync as chmodSync3, readFileSync as readFileSync7, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
32844
- import { join as join12 } from "path";
33520
+ import { chmodSync as chmodSync3, readFileSync as readFileSync9, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
33521
+ import { join as join14 } from "path";
32845
33522
  var VAULT_OCCUPANT_REASON = {
32846
33523
  symlink: "the path is a symlink; remove it so a keyring can be created",
32847
33524
  gone: "the path was occupied but holds no keyring (removed while it was being created)",
@@ -32940,7 +33617,7 @@ function claimRotationLock(lock, owner) {
32940
33617
  throw asError(err);
32941
33618
  }
32942
33619
  try {
32943
- writeFileSync3(join12(lock, LOCK_OWNER_FILE), `${owner}
33620
+ writeFileSync3(join14(lock, LOCK_OWNER_FILE), `${owner}
32944
33621
  `, { mode: DATA_FILE_MODE });
32945
33622
  return true;
32946
33623
  } catch (err) {
@@ -32949,7 +33626,7 @@ function claimRotationLock(lock, owner) {
32949
33626
  }
32950
33627
  }
32951
33628
  function acquireRotationLock(keysDir2) {
32952
- const lock = join12(keysDir2, `${VAULT_KEY_FILENAME}.lock`);
33629
+ const lock = join14(keysDir2, `${VAULT_KEY_FILENAME}.lock`);
32953
33630
  const owner = randomBytes2(16).toString("hex");
32954
33631
  if (claimRotationLock(lock, owner)) return { lock, owner };
32955
33632
  let held;
@@ -32976,7 +33653,7 @@ function acquireRotationLock(keysDir2) {
32976
33653
  }
32977
33654
  function releaseRotationLock(lease) {
32978
33655
  try {
32979
- if (readFileSync7(join12(lease.lock, LOCK_OWNER_FILE), "utf8").trim() !== lease.owner) return;
33656
+ if (readFileSync9(join14(lease.lock, LOCK_OWNER_FILE), "utf8").trim() !== lease.owner) return;
32980
33657
  } catch {
32981
33658
  return;
32982
33659
  }
@@ -32997,7 +33674,7 @@ var FileKeyProvider = class {
32997
33674
  this.#keysDir = keysDir2;
32998
33675
  }
32999
33676
  get filePath() {
33000
- return join12(this.#keysDir, VAULT_KEY_FILENAME);
33677
+ return join14(this.#keysDir, VAULT_KEY_FILENAME);
33001
33678
  }
33002
33679
  loadOrCreate() {
33003
33680
  return asAsync(() => {
@@ -33027,7 +33704,7 @@ var FileKeyProvider = class {
33027
33704
  #read() {
33028
33705
  let raw;
33029
33706
  try {
33030
- raw = readFileSync7(this.filePath, "utf8");
33707
+ raw = readFileSync9(this.filePath, "utf8");
33031
33708
  } catch (err) {
33032
33709
  if (err.code === "ENOENT") return null;
33033
33710
  throw err instanceof Error ? err : new Error(String(err));
@@ -33663,11 +34340,11 @@ var SecretVault = class {
33663
34340
 
33664
34341
  // ../../packages/persistence/src/warn-era-cap.ts
33665
34342
  import { existsSync as existsSync7, writeFileSync as writeFileSync4 } from "fs";
33666
- import { join as join13 } from "path";
34343
+ import { join as join15 } from "path";
33667
34344
  var MARKER = "warn-era-capped";
33668
34345
  function capWarnEraEnforcementOnce(db, policyMode, dataDir2) {
33669
34346
  if (policyMode !== "warn") return { capped: 0, skipped: "not-warn" };
33670
- const marker = join13(dataDir2, MARKER);
34347
+ const marker = join15(dataDir2, MARKER);
33671
34348
  if (existsSync7(marker)) return { capped: 0, skipped: "already-run" };
33672
34349
  const capped = db.policies.capCategoryActions();
33673
34350
  writeFileSync4(marker, `${new Date(Date.now()).toISOString()}
@@ -33858,10 +34535,10 @@ function parsed(schema, body, route) {
33858
34535
  }
33859
34536
  function withoutTrailingSlashes(endpoint) {
33860
34537
  let end = endpoint.length;
33861
- while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH) end -= 1;
34538
+ while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH2) end -= 1;
33862
34539
  return endpoint.slice(0, end);
33863
34540
  }
33864
- var SLASH = "/".charCodeAt(0);
34541
+ var SLASH2 = "/".charCodeAt(0);
33865
34542
  function createRemoteClient(options) {
33866
34543
  const base = withoutTrailingSlashes(options.endpoint);
33867
34544
  const url2 = (route) => `${base}${route}`;
@@ -34043,11 +34720,11 @@ function withTimeout(promise2, ms) {
34043
34720
  }
34044
34721
 
34045
34722
  // ../../packages/plugin-runtime/src/attached/forward-drops.ts
34046
- import { readFileSync as readFileSync8 } from "fs";
34047
- import { join as join14 } from "path";
34723
+ import { readFileSync as readFileSync10 } from "fs";
34724
+ import { join as join16 } from "path";
34048
34725
  var FORWARD_DROPS_FILENAME = ATTACHED_FORWARD_DROPS_FILENAME;
34049
34726
  function forwardDropsPath(dataDir2) {
34050
- return join14(dataDir2, FORWARD_DROPS_FILENAME);
34727
+ return join16(dataDir2, FORWARD_DROPS_FILENAME);
34051
34728
  }
34052
34729
  function recordForwardDrops(dataDir2, count, nowMs) {
34053
34730
  if (count <= 0) return;
@@ -34065,7 +34742,7 @@ function recordForwardDrops(dataDir2, count, nowMs) {
34065
34742
  }
34066
34743
  function readForwardDrops(dataDir2) {
34067
34744
  try {
34068
- const parsed2 = JSON.parse(readFileSync8(forwardDropsPath(dataDir2), "utf8"));
34745
+ const parsed2 = JSON.parse(readFileSync10(forwardDropsPath(dataDir2), "utf8"));
34069
34746
  if (typeof parsed2 !== "object" || parsed2 === null) return null;
34070
34747
  const record2 = parsed2;
34071
34748
  if (typeof record2.droppedForwards !== "number" || !Number.isFinite(record2.droppedForwards)) {
@@ -34083,13 +34760,12 @@ function readForwardDrops(dataDir2) {
34083
34760
 
34084
34761
  // ../../packages/plugin-runtime/src/attached/forward-policy.ts
34085
34762
  import { randomUUID as randomUUID15 } from "crypto";
34086
- import { readFileSync as readFileSync15 } from "fs";
34087
34763
  import { readFile, rename, writeFile } from "fs/promises";
34088
- import { join as join24 } from "path";
34764
+ import { join as join26 } from "path";
34089
34765
 
34090
34766
  // ../../packages/plugin-sdk/src/config.ts
34091
34767
  import { existsSync as existsSync8 } from "fs";
34092
- import { join as join15 } from "path";
34768
+ import { join as join17 } from "path";
34093
34769
 
34094
34770
  // ../../packages/plugin-sdk/src/provider-env.ts
34095
34771
  var DEFAULT_ANTHROPIC_HOST = "api.anthropic.com";
@@ -34153,7 +34829,7 @@ function providerFromModelId(modelId) {
34153
34829
  function loadConfig(base = defaultDataDir(), resolveProviderFn = resolveProvider) {
34154
34830
  try {
34155
34831
  ensureLayoutDirSync(base);
34156
- const settingsFile = join15(settingsDir(base), "settings.json");
34832
+ const settingsFile = join17(settingsDir(base), "settings.json");
34157
34833
  if (existsSync8(settingsFile)) tightenFile(settingsFile);
34158
34834
  } catch {
34159
34835
  }
@@ -34177,9 +34853,9 @@ function resolveProviderSafe(resolveProviderFn) {
34177
34853
  }
34178
34854
 
34179
34855
  // ../../packages/plugin-sdk/src/config-inventory.ts
34180
- import { readdirSync as readdirSync2, readFileSync as readFileSync10, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
34856
+ import { readdirSync as readdirSync2, readFileSync as readFileSync12, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
34181
34857
  import { homedir as homedir2 } from "os";
34182
- import { basename as basename3, join as join17 } from "path";
34858
+ import { basename as basename3, join as join19 } from "path";
34183
34859
 
34184
34860
  // ../../packages/detections/src/egress/registry.ts
34185
34861
  var EXTRACTOR_VERSION = "1";
@@ -37310,8 +37986,8 @@ function scanText(text, ruleVersions) {
37310
37986
  }
37311
37987
 
37312
37988
  // ../../packages/plugin-sdk/src/repo.ts
37313
- import { existsSync as existsSync9, readFileSync as readFileSync9, statSync as statSync6 } from "fs";
37314
- import { basename as basename2, dirname as dirname4, isAbsolute, join as join16, sep as sep2 } from "path";
37989
+ import { existsSync as existsSync9, readFileSync as readFileSync11, statSync as statSync6 } from "fs";
37990
+ import { basename as basename2, dirname as dirname4, isAbsolute, join as join18, sep as sep2 } from "path";
37315
37991
  function resolveRepoIdentity(cwd) {
37316
37992
  try {
37317
37993
  const root = findGitRoot(cwd);
@@ -37344,36 +38020,36 @@ function resolveRepoNwo(cwd) {
37344
38020
  function findGitRoot(start) {
37345
38021
  let dir = start;
37346
38022
  for (; ; ) {
37347
- if (existsSync9(join16(dir, ".git"))) return dir;
38023
+ if (existsSync9(join18(dir, ".git"))) return dir;
37348
38024
  const parent = dirname4(dir);
37349
38025
  if (parent === dir) return void 0;
37350
38026
  dir = parent;
37351
38027
  }
37352
38028
  }
37353
38029
  function resolveGitContext(root) {
37354
- const dotGit = join16(root, ".git");
38030
+ const dotGit = join18(root, ".git");
37355
38031
  try {
37356
38032
  if (statSync6(dotGit).isDirectory()) {
37357
- return { configPath: join16(dotGit, "config"), headRoot: root };
38033
+ return { configPath: join18(dotGit, "config"), headRoot: root };
37358
38034
  }
37359
38035
  } catch {
37360
38036
  return void 0;
37361
38037
  }
37362
38038
  const target = /^gitdir:\s*(.+?)\s*$/m.exec(safeRead(dotGit) ?? "")?.[1];
37363
38039
  if (!target) return void 0;
37364
- const gitdir = isAbsolute(target) ? target : join16(root, target);
37365
- if (existsSync9(join16(gitdir, "config"))) {
37366
- return { configPath: join16(gitdir, "config"), headRoot: root };
38040
+ const gitdir = isAbsolute(target) ? target : join18(root, target);
38041
+ if (existsSync9(join18(gitdir, "config"))) {
38042
+ return { configPath: join18(gitdir, "config"), headRoot: root };
37367
38043
  }
37368
- const commonRaw = safeRead(join16(gitdir, "commondir"))?.trim();
38044
+ const commonRaw = safeRead(join18(gitdir, "commondir"))?.trim();
37369
38045
  if (!commonRaw) return void 0;
37370
- const commonGitDir = isAbsolute(commonRaw) ? commonRaw : join16(gitdir, commonRaw);
38046
+ const commonGitDir = isAbsolute(commonRaw) ? commonRaw : join18(gitdir, commonRaw);
37371
38047
  const headRoot = basename2(commonGitDir) === ".git" ? dirname4(commonGitDir) : root;
37372
- return { configPath: join16(commonGitDir, "config"), headRoot };
38048
+ return { configPath: join18(commonGitDir, "config"), headRoot };
37373
38049
  }
37374
38050
  function safeRead(path) {
37375
38051
  try {
37376
- return readFileSync9(path, "utf8");
38052
+ return readFileSync11(path, "utf8");
37377
38053
  } catch {
37378
38054
  return void 0;
37379
38055
  }
@@ -37930,8 +38606,8 @@ function createGuardedScanner(partition, gateway, opts) {
37930
38606
  }
37931
38607
 
37932
38608
  // ../../packages/plugin-sdk/src/host-floor.ts
37933
- import { readFileSync as readFileSync12 } from "fs";
37934
- import { join as join19 } from "path";
38609
+ import { readFileSync as readFileSync14 } from "fs";
38610
+ import { join as join21 } from "path";
37935
38611
 
37936
38612
  // ../../packages/plugin-sdk/src/model-governance.ts
37937
38613
  import {
@@ -37939,11 +38615,11 @@ import {
37939
38615
  fstatSync,
37940
38616
  mkdirSync as mkdirSync2,
37941
38617
  openSync as openSync2,
37942
- readFileSync as readFileSync11,
38618
+ readFileSync as readFileSync13,
37943
38619
  readSync,
37944
38620
  writeFileSync as writeFileSync5
37945
38621
  } from "fs";
37946
- import { join as join18 } from "path";
38622
+ import { join as join20 } from "path";
37947
38623
  var TAIL_BYTES = 256 * 1024;
37948
38624
 
37949
38625
  // ../../packages/plugin-sdk/src/host-floor.ts
@@ -37966,8 +38642,8 @@ var HOST_FLOORS = {
37966
38642
 
37967
38643
  // ../../packages/plugin-sdk/src/ignore-layers.ts
37968
38644
  var import_ignore = __toESM(require_ignore(), 1);
37969
- import { readFileSync as readFileSync13 } from "fs";
37970
- import { join as join20 } from "path";
38645
+ import { readFileSync as readFileSync15 } from "fs";
38646
+ import { join as join22 } from "path";
37971
38647
 
37972
38648
  // ../../packages/plugin-sdk/src/inventory-resolver.ts
37973
38649
  import { arch, hostname as hostname4, platform, release } from "os";
@@ -37999,8 +38675,8 @@ function resolveInventoryContext(input2) {
37999
38675
  }
38000
38676
 
38001
38677
  // ../../packages/plugin-sdk/src/nudge.ts
38002
- import { mkdirSync as mkdirSync3, readFileSync as readFileSync14, writeFileSync as writeFileSync6 } from "fs";
38003
- import { join as join21 } from "path";
38678
+ import { mkdirSync as mkdirSync3, readFileSync as readFileSync16, writeFileSync as writeFileSync6 } from "fs";
38679
+ import { join as join23 } from "path";
38004
38680
 
38005
38681
  // ../../packages/plugin-sdk/src/paths.ts
38006
38682
  import { readdirSync as readdirSync3, realpathSync as realpathSync3 } from "fs";
@@ -38043,7 +38719,7 @@ function createPolicyResolver(bundle) {
38043
38719
 
38044
38720
  // ../../packages/plugin-sdk/src/project-files.ts
38045
38721
  import { existsSync as existsSync11, readdirSync as readdirSync4 } from "fs";
38046
- import { basename as basename5, join as join22 } from "path";
38722
+ import { basename as basename5, join as join24 } from "path";
38047
38723
 
38048
38724
  // ../../packages/plugin-sdk/src/provider-env-antigravity.ts
38049
38725
  var optionalBaseUrl2 = external_exports.preprocess((v) => {
@@ -38158,7 +38834,7 @@ function createPluginRuntime(gateway, settings, opts) {
38158
38834
  bundlesPacked = true;
38159
38835
  }
38160
38836
  const policyMode = settings.policy;
38161
- const redactFallback = settings.redactFallback;
38837
+ let redactFallback = settings.redactFallback;
38162
38838
  const dataDir2 = opts?.dataDir;
38163
38839
  let rules = [];
38164
38840
  let scanner;
@@ -38202,6 +38878,7 @@ function createPluginRuntime(gateway, settings, opts) {
38202
38878
  rules = [...verified, ...unverified];
38203
38879
  scanner = createGuardedScanner({ verified, unverified }, gateway, opts?.scanIsolation);
38204
38880
  bundleExceptions = bundle.exceptions ?? [];
38881
+ redactFallback = strongerRedactFallback(settings.redactFallback, bundle.redactFallback);
38205
38882
  initialized = true;
38206
38883
  }
38207
38884
  let cachedKey;
@@ -38240,11 +38917,13 @@ function createPluginRuntime(gateway, settings, opts) {
38240
38917
  function decide(findings, text, excepted, rewritable = true) {
38241
38918
  if (findings.length === 0) return { action: "log", text, findings: [] };
38242
38919
  const actionFor = (finding) => actionForFinding(finding, excepted, rewritable);
38920
+ const degradedActions = rewritable ? [] : findings.filter((f) => actionForFinding(f, excepted, true) === "redact").map(actionFor);
38921
+ const degraded = degradedActions.length === 0 ? {} : { redactDegradedTo: degradedActions.reduce((a, b) => strongerAction(a, b)) };
38243
38922
  let worst = "log";
38244
38923
  for (const finding of findings) {
38245
38924
  worst = strongerAction(worst, actionFor(finding));
38246
38925
  }
38247
- if (worst === "block") return { action: "block", text: null, findings };
38926
+ if (worst === "block") return { action: "block", text: null, findings, ...degraded };
38248
38927
  if (worst === "redact") {
38249
38928
  const redactFindings = findings.filter((f) => actionFor(f) === "redact");
38250
38929
  const reversibleFindings = redactFindings.filter((f) => resolver.isReversible(f.ruleId));
@@ -38254,9 +38933,13 @@ function createPluginRuntime(gateway, settings, opts) {
38254
38933
  findings,
38255
38934
  enforcedFindings: redactFindings,
38256
38935
  reversibleFindings
38936
+ // No `degraded` here, and it is not an omission: `rewritable` is per
38937
+ // CAPTURE, so on an unrewritable field every redact has already become
38938
+ // the fallback and this branch is unreachable. Spreading it would read
38939
+ // as a case that can happen.
38257
38940
  };
38258
38941
  }
38259
- return { action: worst, text, findings };
38942
+ return { action: worst, text, findings, ...degraded };
38260
38943
  }
38261
38944
  function fingerprintOf(key, finding, cache) {
38262
38945
  let fp = cache.get(finding);
@@ -38385,8 +39068,8 @@ function createPluginRuntime(gateway, settings, opts) {
38385
39068
  };
38386
39069
  }
38387
39070
  }
38388
- async function processText(text, context) {
38389
- return (await evaluate(text, context, {})).decision;
39071
+ async function processText(text, context, opts2 = {}) {
39072
+ return (await evaluate(text, context, {}, opts2.rewritable)).decision;
38390
39073
  }
38391
39074
  async function capture(input2, opts2 = {}) {
38392
39075
  const timingStartedAt = input2.occurredAt === void 0 ? startTiming() : void 0;
@@ -38409,10 +39092,12 @@ function createPluginRuntime(gateway, settings, opts) {
38409
39092
  );
38410
39093
  const storedContent = maskedFindings.length > 0 ? redact(input2.text, maskedFindings) : input2.text;
38411
39094
  const inspectionMs = elapsedMs(timingStartedAt);
38412
- const metadata = exceptionIds.length > 0 || inspectionMs !== void 0 ? {
39095
+ const redactDegradedTo = decision.redactDegradedTo;
39096
+ const metadata = exceptionIds.length > 0 || inspectionMs !== void 0 || redactDegradedTo !== void 0 ? {
38413
39097
  ...input2.metadata,
38414
39098
  ...exceptionIds.length > 0 ? { exceptionIds } : {},
38415
- ...inspectionMs !== void 0 ? { inspectionMs } : {}
39099
+ ...inspectionMs !== void 0 ? { inspectionMs } : {},
39100
+ ...redactDegradedTo !== void 0 ? { redactDegradedTo } : {}
38416
39101
  } : input2.metadata;
38417
39102
  const event = buildIngestEvent({
38418
39103
  kind: input2.kind,
@@ -38484,7 +39169,7 @@ var THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1e3;
38484
39169
 
38485
39170
  // ../../packages/plugin-sdk/src/throttle.ts
38486
39171
  import { mkdirSync as mkdirSync4, statSync as statSync8, writeFileSync as writeFileSync7 } from "fs";
38487
- import { join as join23 } from "path";
39172
+ import { join as join25 } from "path";
38488
39173
 
38489
39174
  // ../../packages/plugin-sdk/src/tokenize.ts
38490
39175
  function redactedPlaceholder(category) {
@@ -38813,31 +39498,12 @@ function isServerRejection(err) {
38813
39498
  var FORWARD_BUDGET_MS = 1500;
38814
39499
  var DECISION_PATH_BUDGET_MS = 800;
38815
39500
  var BREAKER_FAILURE_THRESHOLD = 3;
38816
- var BREAKER_COOLDOWN_MS = 3e4;
38817
39501
  var CLOSED = { consecutiveFailures: 0, openedAtMs: null, lastFailure: null };
38818
- var FAILURES = /* @__PURE__ */ new Set([
38819
- "unauthorized",
38820
- "forbidden",
38821
- "unreachable"
38822
- ]);
38823
39502
  var FORWARD_STATE_FILENAME = ATTACHED_FORWARD_STATE_FILENAME;
38824
39503
  var STATE_FILENAME = FORWARD_STATE_FILENAME;
38825
- function parseBreakerState(raw, nowMs) {
38826
- try {
38827
- const parsed2 = JSON.parse(raw);
38828
- if (typeof parsed2 !== "object" || parsed2 === null) return null;
38829
- const record2 = parsed2;
38830
- const failures = typeof record2.consecutiveFailures === "number" && record2.consecutiveFailures >= 0 ? record2.consecutiveFailures : 0;
38831
- const openedAtMs = typeof record2.openedAtMs === "number" && Number.isFinite(record2.openedAtMs) && record2.openedAtMs <= nowMs ? record2.openedAtMs : null;
38832
- const lastFailure = typeof record2.lastFailure === "string" && FAILURES.has(record2.lastFailure) ? record2.lastFailure : null;
38833
- return { consecutiveFailures: failures, openedAtMs, lastFailure };
38834
- } catch {
38835
- return null;
38836
- }
38837
- }
38838
39504
  function createForwardPolicy(deps) {
38839
39505
  const now = deps.now ?? (() => Date.now());
38840
- const file2 = join24(deps.dir, STATE_FILENAME);
39506
+ const file2 = join26(deps.dir, STATE_FILENAME);
38841
39507
  let state = null;
38842
39508
  let loading = null;
38843
39509
  async function readState() {
@@ -38847,7 +39513,7 @@ function createForwardPolicy(deps) {
38847
39513
  } catch {
38848
39514
  return { ...CLOSED };
38849
39515
  }
38850
- return parseBreakerState(raw, now()) ?? { ...CLOSED };
39516
+ return parseForwardHealth(raw, now()) ?? { ...CLOSED };
38851
39517
  }
38852
39518
  async function load() {
38853
39519
  if (state !== null) return state;
@@ -38893,7 +39559,7 @@ function createForwardPolicy(deps) {
38893
39559
  };
38894
39560
  const at = now();
38895
39561
  if (current.openedAtMs !== null) {
38896
- if (at - current.openedAtMs < BREAKER_COOLDOWN_MS) {
39562
+ if (isForwardPaused(current, at)) {
38897
39563
  return { ok: false, reason: "breaker-open" };
38898
39564
  }
38899
39565
  await persist({
@@ -39430,7 +40096,18 @@ var AttachedDataGateway = class {
39430
40096
  // and the spread above would otherwise drop the field silently — which is
39431
40097
  // exactly what it did, leaving the whole control inert on every device
39432
40098
  // while every test around it stayed green.
39433
- prohibitedModels: cached2.prohibitedModels
40099
+ prohibitedModels: cached2.prohibitedModels,
40100
+ // NAMED for the same reason as the line above, and it is the same defect
40101
+ // if it is not: `...local` above spreads the DEVICE's bundle, so a field
40102
+ // only the cache carries is dropped in silence. That is what left
40103
+ // `prohibitedModels` inert on every attached device with every test
40104
+ // around it green.
40105
+ //
40106
+ // Taken from the cache rather than merged here, because merging it needs
40107
+ // the device's own SETTING — which is not a bundle field and is not in
40108
+ // scope at this seam. The runtime does that merge, raise-only, where both
40109
+ // values are in hand (createPluginRuntime's ensureInitialized).
40110
+ redactFallback: cached2.redactFallback
39434
40111
  // ALSO HONOURED FROM THE CACHE, and not a bundle field at all: each
39435
40112
  // merged policy's own `provenance`. `mergeRaiseOnly` spreads the policies
39436
40113
  // it emits, so an 'authored' policy arriving from the control plane
@@ -39558,10 +40235,6 @@ function toolAuditEvent(input2) {
39558
40235
  };
39559
40236
  }
39560
40237
 
39561
- // ../../packages/plugin-runtime/src/attached/history-state.ts
39562
- import { readFileSync as readFileSync16 } from "fs";
39563
- import { join as join25 } from "path";
39564
-
39565
40238
  // ../../packages/plugin-runtime/src/attached/history-sync.ts
39566
40239
  import { createHash as createHash6 } from "crypto";
39567
40240
  import { hostname as hostname5 } from "os";
@@ -39570,6 +40243,10 @@ import { hostname as hostname5 } from "os";
39570
40243
  var CORRELATION_ID = EventMetadata.shape.correlationId;
39571
40244
  var TRACE_ID = EventMetadata.shape.traceId;
39572
40245
  var EXCEPTION_ID = EventMetadata.shape.exceptionIds.unwrap().element;
40246
+ var REDACT_DEGRADED_TO = EventMetadata.shape.redactDegradedTo.unwrap();
40247
+
40248
+ // ../../packages/plugin-runtime/src/attached/history-sync.ts
40249
+ var CAPTURE_BATCH_BYTES = 1024 * 1024;
39573
40250
 
39574
40251
  // ../../packages/plugin-runtime/src/attached/history-sync-trigger.ts
39575
40252
  import { spawn } from "child_process";
@@ -39611,7 +40288,7 @@ function createPluginBlock(build, policyStore) {
39611
40288
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
39612
40289
  import { randomUUID as randomUUID16 } from "crypto";
39613
40290
  import { readFile as readFile2, rm, writeFile as writeFile2 } from "fs/promises";
39614
- import { join as join26 } from "path";
40291
+ import { join as join27 } from "path";
39615
40292
 
39616
40293
  // ../../packages/plugin-runtime/src/attached/atomic-publish.ts
39617
40294
  import { rename as rename2 } from "fs/promises";
@@ -39635,7 +40312,7 @@ async function publishByRename(tmp, file2, move = rename2) {
39635
40312
 
39636
40313
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
39637
40314
  function createPolicyStore(dir = dataDir()) {
39638
- const file2 = join26(dir, "policy-cache.json");
40315
+ const file2 = join27(dir, "policy-cache.json");
39639
40316
  async function read() {
39640
40317
  try {
39641
40318
  const raw = await readFile2(file2, "utf8");
@@ -39866,11 +40543,11 @@ function readStorePosture(dbPath2) {
39866
40543
  // ../../packages/plugin-runtime/src/attached/posture-store.ts
39867
40544
  import { randomUUID as randomUUID17 } from "crypto";
39868
40545
  import { readFile as readFile3, rm as rm2, writeFile as writeFile3 } from "fs/promises";
39869
- import { join as join27 } from "path";
40546
+ import { join as join28 } from "path";
39870
40547
  var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
39871
40548
  function createPostureStore(dir = settingsDir(), legacyDir) {
39872
- const file2 = join27(dir, "posture-state.json");
39873
- const legacyFile = legacyDir === void 0 ? null : join27(legacyDir, "posture-state.json");
40549
+ const file2 = join28(dir, "posture-state.json");
40550
+ const legacyFile = legacyDir === void 0 ? null : join28(legacyDir, "posture-state.json");
39874
40551
  async function persist(state) {
39875
40552
  await ensureDataDir(dir);
39876
40553
  const tmp = `${file2}.${randomUUID17()}.tmp`;
@@ -39939,7 +40616,7 @@ function createPostureStore(dir = settingsDir(), legacyDir) {
39939
40616
 
39940
40617
  // ../../packages/plugin-runtime/src/attached/sync-state.ts
39941
40618
  import { readFileSync as readFileSync18 } from "fs";
39942
- import { join as join28 } from "path";
40619
+ import { join as join29 } from "path";
39943
40620
 
39944
40621
  // ../../packages/plugin-runtime/src/attached/status.ts
39945
40622
  var REFUSAL_LINES = {
@@ -39960,6 +40637,14 @@ import { spawn as spawn2 } from "child_process";
39960
40637
  import { fileURLToPath as fileURLToPath3 } from "url";
39961
40638
  var SYNC_THROTTLE_MS = 15 * 60 * 1e3;
39962
40639
 
40640
+ // ../../packages/plugin-runtime/src/content-retention-pass.ts
40641
+ var MAX_ROWS_PER_SWEEP = 50 * 1e3;
40642
+
40643
+ // ../../packages/plugin-runtime/src/content-retention-trigger.ts
40644
+ import { spawn as spawn3 } from "child_process";
40645
+ import { fileURLToPath as fileURLToPath4 } from "url";
40646
+ var CONTENT_RETENTION_THROTTLE_MS = 60 * 60 * 1e3;
40647
+
39963
40648
  // ../../packages/plugin-runtime/src/attached/factory.ts
39964
40649
  import { hostname as hostname6 } from "os";
39965
40650
 
@@ -40411,7 +41096,7 @@ var EXCEPTION_RETENTION_MS = 90 * 24 * 60 * 60 * 1e3;
40411
41096
 
40412
41097
  // ../../packages/setup-wizard/src/remediation/rotation-checklist.ts
40413
41098
  import { writeFileSync as writeFileSync8 } from "fs";
40414
- import { join as join29 } from "path";
41099
+ import { join as join30 } from "path";
40415
41100
 
40416
41101
  // ../../packages/setup-wizard/src/triage/merge.ts
40417
41102
  var RANK = Object.fromEntries(
@@ -40421,7 +41106,7 @@ var RANK = Object.fromEntries(
40421
41106
  // ../../packages/setup-wizard/src/triage/plan-file.ts
40422
41107
  import { mkdtempSync, readFileSync as readFileSync19, rmdirSync, rmSync as rmSync7, writeFileSync as writeFileSync9 } from "fs";
40423
41108
  import { tmpdir } from "os";
40424
- import { basename as basename6, dirname as dirname6, join as join30 } from "path";
41109
+ import { basename as basename6, dirname as dirname6, join as join31 } from "path";
40425
41110
  var SuppressionEntrySchema = external_exports.object({
40426
41111
  ruleId: external_exports.string(),
40427
41112
  category: DetectionCategory,
@@ -40468,9 +41153,9 @@ var TRIAGE_STATUSES = ["complete", "complete:no-history", "skipped:no-consent"];
40468
41153
  // src/history/transcripts.ts
40469
41154
  import { readdirSync as readdirSync5, readFileSync as readFileSync20 } from "fs";
40470
41155
  import { homedir as homedir3 } from "os";
40471
- import { join as join31 } from "path";
41156
+ import { join as join32 } from "path";
40472
41157
  function transcriptsDir(home) {
40473
- return join31(home ?? homedir3(), ".claude", "projects");
41158
+ return join32(home ?? homedir3(), ".claude", "projects");
40474
41159
  }
40475
41160
  function isRecord(value) {
40476
41161
  return typeof value === "object" && value !== null;
@@ -40718,7 +41403,7 @@ function* iterateFileContents(dir, excludeSessionId) {
40718
41403
  return;
40719
41404
  }
40720
41405
  for (const project of projects) {
40721
- const projectDir = join31(dir, project);
41406
+ const projectDir = join32(dir, project);
40722
41407
  let files;
40723
41408
  try {
40724
41409
  files = readdirSync5(projectDir).filter((name) => name.endsWith(".jsonl"));
@@ -40728,7 +41413,7 @@ function* iterateFileContents(dir, excludeSessionId) {
40728
41413
  for (const file2 of files) {
40729
41414
  if (excludeSessionId !== void 0 && file2.slice(0, -".jsonl".length) === excludeSessionId)
40730
41415
  continue;
40731
- const filePath = join31(projectDir, file2);
41416
+ const filePath = join32(projectDir, file2);
40732
41417
  let content;
40733
41418
  try {
40734
41419
  content = readFileSync20(filePath, "utf8");
@@ -40876,7 +41561,7 @@ import {
40876
41561
  statSync as statSync10,
40877
41562
  writeFileSync as writeFileSync10
40878
41563
  } from "fs";
40879
- import { basename as basename7, dirname as dirname7, isAbsolute as isAbsolute2, join as join32, relative, resolve as resolve2 } from "path";
41564
+ import { basename as basename7, dirname as dirname7, isAbsolute as isAbsolute2, join as join33, relative, resolve as resolve2 } from "path";
40880
41565
  function platformRedactionScope(home) {
40881
41566
  return { artifactRoots: [transcriptsDir(home)] };
40882
41567
  }
@@ -40961,7 +41646,7 @@ import {
40961
41646
  readSync as readSync2,
40962
41647
  writeFileSync as writeFileSync12
40963
41648
  } from "fs";
40964
- import { join as join33 } from "path";
41649
+ import { join as join34 } from "path";
40965
41650
 
40966
41651
  // src/history/usage.ts
40967
41652
  var NO_PROJECT_CWD = "/nonexistent/aka-reconciler/no-project";
@@ -41290,7 +41975,7 @@ async function runBackfill(deps) {
41290
41975
  } else {
41291
41976
  const heading = "\u2713 Historical scan complete";
41292
41977
  const scope = `Scanned ${String(summary.scanned)} messages from the last ${String(summary.windowDays)} days of Claude Code history.`;
41293
- const result = summary.findings > 0 ? `Found ${String(summary.findings)} pre-install finding${summary.findings === 1 ? "" : "s"} \u2014 review them with /findings.` : "No new pre-install secrets found in your history.";
41978
+ const result = summary.findings > 0 ? `Found ${String(summary.findings)} pre-install finding${summary.findings === 1 ? "" : "s"} \u2014 review them with /aka:findings.` : "No new pre-install secrets found in your history.";
41294
41979
  const lines = [heading, "", indent(scope), "", indent(result)];
41295
41980
  if (scrubbedFiles > 0) {
41296
41981
  lines.push(
@@ -41346,7 +42031,7 @@ async function readPolicyResolver(cfg) {
41346
42031
  }
41347
42032
  }
41348
42033
  }
41349
- if (process.argv[1] && fileURLToPath4(import.meta.url) === process.argv[1]) {
42034
+ if (process.argv[1] && fileURLToPath5(import.meta.url) === process.argv[1]) {
41350
42035
  const triage = process.argv.includes("--triage");
41351
42036
  const startedAt = Date.now();
41352
42037
  const sessionId = process.env.CLAUDE_CODE_BRIDGE_SESSION_ID;