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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -50,7 +50,7 @@ var require_ignore = __commonJS({
50
50
  var REGEX_SPLITALL_CRLF = /\r?\n/g;
51
51
  var REGEX_TEST_INVALID_PATH = /^\.{0,2}\/|^\.{1,2}$/;
52
52
  var REGEX_TEST_TRAILING_SLASH = /\/$/;
53
- var SLASH2 = "/";
53
+ var SLASH3 = "/";
54
54
  var TMP_KEY_IGNORE = "node-ignore";
55
55
  if (typeof Symbol !== "undefined") {
56
56
  TMP_KEY_IGNORE = /* @__PURE__ */ Symbol.for("node-ignore");
@@ -422,11 +422,11 @@ var require_ignore = __commonJS({
422
422
  if (!REGEX_TEST_TRAILING_SLASH.test(path)) {
423
423
  return this.test(path);
424
424
  }
425
- const slices = path.split(SLASH2).filter(Boolean);
425
+ const slices = path.split(SLASH3).filter(Boolean);
426
426
  slices.pop();
427
427
  if (slices.length) {
428
428
  const parent = this._t(
429
- slices.join(SLASH2) + SLASH2,
429
+ slices.join(SLASH3) + SLASH3,
430
430
  this._testCache,
431
431
  true,
432
432
  slices
@@ -442,14 +442,14 @@ var require_ignore = __commonJS({
442
442
  return cache[path];
443
443
  }
444
444
  if (!slices) {
445
- slices = path.split(SLASH2).filter(Boolean);
445
+ slices = path.split(SLASH3).filter(Boolean);
446
446
  }
447
447
  slices.pop();
448
448
  if (!slices.length) {
449
449
  return cache[path] = this._rules.test(path, checkUnignored, MODE_IGNORE);
450
450
  }
451
451
  const parent = this._t(
452
- slices.join(SLASH2) + SLASH2,
452
+ slices.join(SLASH3) + SLASH3,
453
453
  cache,
454
454
  checkUnignored,
455
455
  slices
@@ -493,7 +493,7 @@ var require_ignore = __commonJS({
493
493
 
494
494
  // ../../packages/plugin-sdk/src/config.ts
495
495
  import { existsSync as existsSync8 } from "fs";
496
- import { join as join14 } from "path";
496
+ import { join as join16 } from "path";
497
497
 
498
498
  // ../../packages/persistence/src/attached-derived.ts
499
499
  import { rmSync } from "fs";
@@ -506,6 +506,14 @@ var ATTACHED_FORWARD_DROPS_FILENAME = "attached-forward-drops.json";
506
506
  import { chmodSync as chmodSync2, lstatSync as lstatSync2, readFileSync, rmSync as rmSync3, statSync } from "fs";
507
507
  import { join as join2 } from "path";
508
508
 
509
+ // ../../packages/schema/src/drizzle/deferred-migrations.ts
510
+ var DEFERRED_MIGRATION_TAGS = [
511
+ "0031_audit_capture_by_time_index",
512
+ "0032_audit_capture_by_id_index",
513
+ "0033_audit_capture_location_index",
514
+ "0034_findings_read_indexes"
515
+ ];
516
+
509
517
  // ../../packages/schema/src/drizzle/sqlite-ddl.ts
510
518
  var SQLITE_MIGRATIONS = [
511
519
  {
@@ -623,6 +631,30 @@ var SQLITE_MIGRATIONS = [
623
631
  {
624
632
  tag: "0028_activity_session_probe_indexes",
625
633
  sql: "CREATE INDEX `idx_audit_session_prompt` ON `audit_events` (`root_session_id`) WHERE event_type = 'prompt';--> statement-breakpoint\nCREATE INDEX `idx_audit_session_share` ON `audit_events` (`root_session_id`) WHERE event_type = 'share';--> statement-breakpoint\nCREATE INDEX `idx_audit_ended_at` ON `audit_events` (`ended_at`,`root_session_id`) WHERE ended_at IS NOT NULL;--> statement-breakpoint\nCREATE INDEX `idx_audit_session_ended` ON `audit_events` (`root_session_id`,`ended_at`) WHERE ended_at IS NOT NULL;--> statement-breakpoint\n-- Expression index for the activity list's turns rollup: a live-captured\n-- session's turns are the DISTINCT `run_key` across its `llm_call` leaves, and\n-- carrying the extracted key in the index answers that count from the index\n-- alone instead of parsing every leaf's attribute bag. Written by hand, as\n-- 0013's `idx_audit_code_change_path` was: drizzle-kit cannot emit an\n-- expression containing a comma, so this index is not declared in sqlite.ts.\nCREATE INDEX `idx_audit_session_run_key` ON `audit_events` (`root_session_id`, json_extract(`attributes`, '$.run_key')) WHERE `event_type` = 'llm_call';\n"
634
+ },
635
+ {
636
+ tag: "0029_audit_capture_rollup_index",
637
+ sql: "CREATE INDEX `idx_audit_capture_rollup` ON `audit_events` (`event_type`,`started_at`,`repo`,`id`) WHERE event_type IN ('prompt','response','code_change','tool_use');"
638
+ },
639
+ {
640
+ tag: "0030_audit_content_expiry",
641
+ sql: "ALTER TABLE `audit_events` ADD `content_expired_at` integer;--> statement-breakpoint\nCREATE INDEX `idx_audit_expirable_body` ON `audit_events` (`started_at`) WHERE content IS NOT NULL;"
642
+ },
643
+ {
644
+ tag: "0031_audit_capture_by_time_index",
645
+ sql: "CREATE INDEX `idx_audit_capture_by_time` ON `audit_events` (`started_at`,`id`,`event_type`,`root_session_id`,`source_tool`,`repo`,`file_path`,`tool_name`) WHERE event_type IN ('prompt','response','code_change','tool_use');"
646
+ },
647
+ {
648
+ tag: "0032_audit_capture_by_id_index",
649
+ sql: "CREATE INDEX `idx_audit_capture_by_id` ON `audit_events` (`id`,`started_at`,`event_type`,`root_session_id`,`source_tool`,`repo`,`file_path`,`tool_name`) WHERE event_type IN ('prompt','response','code_change','tool_use');"
650
+ },
651
+ {
652
+ tag: "0033_audit_capture_location_index",
653
+ sql: "CREATE INDEX `idx_audit_capture_location` ON `audit_events` (`repo`,`file_path`,`started_at`,`id`,`event_type`) WHERE event_type IN ('prompt','response','code_change','tool_use');"
654
+ },
655
+ {
656
+ tag: "0034_findings_read_indexes",
657
+ sql: "CREATE INDEX `idx_inspection_definitions_rule` ON `inspection_definitions` (`rule_id`,`severity`,`category`);--> statement-breakpoint\nCREATE INDEX `idx_inspection_findings_def` ON `inspection_findings` (`inspection_definition_id`,`audit_event_id`);--> statement-breakpoint\nCREATE INDEX `idx_inspection_findings_event_cover` ON `inspection_findings` (`audit_event_id`,`inspection_definition_id`,`action_taken`,`finding_key`,`id`);"
626
658
  }
627
659
  ];
628
660
 
@@ -20670,6 +20702,15 @@ var FindingCategory = external_exports.enum([
20670
20702
  ]).meta({ id: "FindingCategory" });
20671
20703
  var FindingOrigin = external_exports.enum(["in-flight", "at-rest"]).meta({ id: "FindingOrigin" });
20672
20704
  var FindingStatus = external_exports.enum(["open", "handled", "resolved", "dismissed"]).meta({ id: "FindingStatus" });
20705
+ var SyncFailureReason = external_exports.enum(["deployment_refused", "payload_invalid", "detached_undelivered"]).meta({ id: "SyncFailureReason" });
20706
+ var FindingDeliveryState = external_exports.enum(["sent", "queued", "not_sent", "never_offered", "local_scan"]).meta({ id: "FindingDeliveryState" });
20707
+ var FindingDelivery = external_exports.object({
20708
+ state: FindingDeliveryState,
20709
+ // The delivery time for `sent`; the failure time for `not_sent` when recorded.
20710
+ at: external_exports.iso.datetime().optional(),
20711
+ // Only on `not_sent`, and only when a known reason was recorded.
20712
+ reason: SyncFailureReason.optional()
20713
+ }).meta({ id: "FindingDelivery" });
20673
20714
  var ResolutionMethod = external_exports.enum([
20674
20715
  "enforced-in-flight",
20675
20716
  "fixed-at-source",
@@ -20726,7 +20767,10 @@ var FindingInstance = external_exports.object({
20726
20767
  // The session that event belongs to, when it has one — the seam a
20727
20768
  // per-instance "view session" link needs. Absent for events captured
20728
20769
  // outside a session.
20729
- sessionId: external_exports.string().optional()
20770
+ sessionId: external_exports.string().optional(),
20771
+ // The delivery state of the event above (see FindingDelivery). Optional so
20772
+ // readers that do not project it stay valid.
20773
+ delivery: FindingDelivery.optional()
20730
20774
  }).meta({ id: "FindingInstance" });
20731
20775
  var FindingGroup = external_exports.object({
20732
20776
  id: external_exports.string(),
@@ -20778,7 +20822,10 @@ var FindingFacets = external_exports.object({
20778
20822
  // Host tool (attributes.tool_name). Present only on the instance-level
20779
20823
  // reads, which can filter by it; the type-level read omits the dimension
20780
20824
  // because a group spans tools.
20781
- tool: external_exports.array(FindingFacetItem).optional()
20825
+ tool: external_exports.array(FindingFacetItem).optional(),
20826
+ // Delivery states (FindingDeliveryState). Present only on the
20827
+ // instance-level reads, like `tool`.
20828
+ deployment: external_exports.array(FindingFacetItem).optional()
20782
20829
  }).meta({ id: "FindingFacets" });
20783
20830
  var FindingTypeSummary = FindingGroup.omit({ instances: true, match: true }).meta({
20784
20831
  id: "FindingTypeSummary"
@@ -20889,6 +20936,8 @@ var ListFindingInstancesQuery = external_exports.object({
20889
20936
  // Exact host-tool names (attributes.tool_name, e.g. 'Bash'). A real filter,
20890
20937
  // where the free-text `q` can only match the rendered "via Bash" label.
20891
20938
  tool: external_exports.array(external_exports.string()).optional(),
20939
+ // The delivery state of each finding's event (see FindingDelivery).
20940
+ deployment: external_exports.array(FindingDeliveryState).optional(),
20892
20941
  // Exact repository / file-path matches, for the drill-down out of the
20893
20942
  // locations view. A row whose event carries no repo/file matches neither.
20894
20943
  repo: external_exports.string().optional(),
@@ -20909,6 +20958,10 @@ var ListFindingInstancesResponse = external_exports.object({
20909
20958
  items: external_exports.array(FindingInstanceDetail),
20910
20959
  nextCursor: external_exports.string().nullable()
20911
20960
  }).meta({ id: "ListFindingInstancesResponse" });
20961
+ var ListFindingInstancesPage = external_exports.object({
20962
+ items: external_exports.array(FindingInstanceDetail),
20963
+ nextCursor: external_exports.string().nullable()
20964
+ }).meta({ id: "ListFindingInstancesPage" });
20912
20965
  var FindingLocationSummary = external_exports.object({
20913
20966
  // Opaque, stable, minted from the pair by encodeLocationId. It exists
20914
20967
  // because a location's identity is two values and a URL param carries one:
@@ -20951,6 +21004,8 @@ var ListFindingLocationsQuery = external_exports.object({
20951
21004
  // instances that match, and folds its status from those.
20952
21005
  status: external_exports.array(FindingStatus).optional(),
20953
21006
  tool: external_exports.array(external_exports.string()).optional(),
21007
+ // The delivery state of each finding's event (see FindingDelivery).
21008
+ deployment: external_exports.array(FindingDeliveryState).optional(),
20954
21009
  q: external_exports.string().optional(),
20955
21010
  sessionId: external_exports.string().optional(),
20956
21011
  from: external_exports.iso.datetime().optional(),
@@ -21153,6 +21208,10 @@ var CaptureAttributes = external_exports.object({
21153
21208
  // to 'allow' — the enforcement audit trail's link back to the grant that
21154
21209
  // authorized the bypass.
21155
21210
  exception_ids: external_exports.array(external_exports.guid()).optional(),
21211
+ // The persisted spellings of EventMetadata's messageId/conversationId — the
21212
+ // join back to the `llm_call` leaf for the same assistant turn.
21213
+ message_id: external_exports.string().optional(),
21214
+ conversation_id: external_exports.string().optional(),
21156
21215
  // Whole milliseconds this capture's inspection blocked its caller — the
21157
21216
  // plugin's own added latency (see EventMetadata.inspectionMs, whose value
21158
21217
  // this is). Promoted to the `inspection_ms` generated column so the facet is
@@ -21161,7 +21220,19 @@ var CaptureAttributes = external_exports.object({
21161
21220
  // inline json_extract and is not itself an optimization.
21162
21221
  // ABSENT on replayed captures (backfill / worktree scan) and on rows written
21163
21222
  // before the measurement shipped — never present as a placeholder 0.
21164
- inspection_ms: external_exports.number().int().nonnegative().optional()
21223
+ inspection_ms: external_exports.number().int().nonnegative().optional(),
21224
+ // What a `redact` this capture could not carry out became instead (see
21225
+ // EventMetadata.redactDegradedTo, whose value this is). Present only when a
21226
+ // degrade actually happened, so absence is the ordinary case rather than a
21227
+ // reader having to distinguish it from a zero.
21228
+ //
21229
+ // PER CAPTURE, while `inspection_findings.action_taken` is per finding —
21230
+ // so on a multi-finding row this does not say which finding degraded, and
21231
+ // its presence does not mean the fallback decided the capture's action. A
21232
+ // capture denied by another finding's own Block policy carries `block`
21233
+ // here too. The full statement is on EventMetadata.redactDegradedTo; it is
21234
+ // repeated rather than referenced because a store reader opens this file.
21235
+ redact_degraded_to: ActionTaken.optional()
21165
21236
  }).catchall(external_exports.unknown());
21166
21237
  var ToolCallInspection = external_exports.object({
21167
21238
  ruleId: external_exports.string().min(1),
@@ -21360,7 +21431,17 @@ var AuditEvent = external_exports.object({
21360
21431
  /** `share` to a first-party/internal destination. */
21361
21432
  internal: external_exports.boolean(),
21362
21433
  /** Event needs review (e.g. unverified egress). */
21363
- flagged: external_exports.boolean()
21434
+ flagged: external_exports.boolean(),
21435
+ /**
21436
+ * The body this event's `title` is drawn from was cleared by local body
21437
+ * expiry, so an EMPTY title here means "gone", not "never had one".
21438
+ *
21439
+ * A separate flag rather than a sentinel written into `title`: the title is
21440
+ * rendered text, and a store-layer module that invented display copy for it
21441
+ * would be choosing words the view is supposed to choose. Additive and
21442
+ * defaulted, so an older producer still validates.
21443
+ */
21444
+ bodyExpired: external_exports.boolean().default(false)
21364
21445
  }).meta({ id: "ActivityAuditEvent" });
21365
21446
  var ActivitySessionSummary = external_exports.object({
21366
21447
  id: external_exports.string(),
@@ -22701,6 +22782,12 @@ var EventMetadata = external_exports.object({
22701
22782
  // to 'allow' — the enforcement audit trail's link back to the grant that
22702
22783
  // authorized the bypass. Absent on captures where no exception applied.
22703
22784
  exceptionIds: external_exports.array(external_exports.guid()).optional(),
22785
+ // The assistant message this capture belongs to, and the conversation it sits
22786
+ // in — set by the browser extension's network capture so a stored `response`
22787
+ // row can be joined to the `llm_call` leaf describing the same turn. Absent
22788
+ // on every other capture path, which has no such id.
22789
+ messageId: external_exports.string().optional(),
22790
+ conversationId: external_exports.string().optional(),
22704
22791
  // How long THIS capture's inspection blocked its caller, in whole
22705
22792
  // milliseconds — the plugin's own added latency, NOT the LLM call it sat in
22706
22793
  // front of. Measured inside `capture()` (@akasecurity/plugin-sdk) across
@@ -22713,7 +22800,37 @@ var EventMetadata = external_exports.object({
22713
22800
  // Absent is also what every pre-measurement client writes, and what a
22714
22801
  // clock failure degrades to — a reader must treat absence as "not measured"
22715
22802
  // and never as a zero, which would read as "inspection is free".
22716
- inspectionMs: external_exports.number().int().nonnegative().optional()
22803
+ inspectionMs: external_exports.number().int().nonnegative().optional(),
22804
+ // What a `redact` this capture COULD NOT CARRY OUT became instead — the
22805
+ // workspace's `redactFallback`, applied because the field could not be
22806
+ // masked in place (a shell command, a URL, or any argument on a host whose
22807
+ // hook contract offers no rewrite channel).
22808
+ //
22809
+ // It exists because the action alone cannot say why. A finding recorded as
22810
+ // `warn` reads identically whether its detection was ASSIGNED Warn or was
22811
+ // assigned Redact on a field that could not take one — and those are
22812
+ // different facts about the same row: the first is a policy the user chose,
22813
+ // the second is a masking the host could not perform. Absent means no
22814
+ // degrade happened, which is every ordinary capture.
22815
+ //
22816
+ // TWO LIMITS a reader of a stored row has to know, because the grain here
22817
+ // is the CAPTURE while `actionTaken` is per FINDING:
22818
+ //
22819
+ // - It does not say WHICH finding degraded. A capture carrying a degraded
22820
+ // `redact` alongside a finding ASSIGNED the same action stores both
22821
+ // identically and one reason for the pair; attributing it to both
22822
+ // describes the assigned one wrongly, and to neither loses the degrade.
22823
+ // - PRESENCE IS NOT CAUSATION. The value is the action the lost redact
22824
+ // became, not the reason the capture ended as it did — a capture denied
22825
+ // by some other finding's own Block policy still carries `block` here,
22826
+ // and clearing the workspace's fallback would not have let it through.
22827
+ // Gate on the value against what a fallback can produce; never read the
22828
+ // field's presence as "this was the fallback's doing".
22829
+ //
22830
+ // Both are pinned as behaviour in @akasecurity/plugin-sdk's runtime suite.
22831
+ // Closing either means moving the reason onto the finding row, which
22832
+ // already carries its own action.
22833
+ redactDegradedTo: ActionTaken.optional()
22717
22834
  }).meta({ id: "EventMetadata" });
22718
22835
  var Event = external_exports.object({
22719
22836
  id: external_exports.guid(),
@@ -22823,7 +22940,32 @@ var RotateKeyInput = external_exports.object({
22823
22940
  confirmation: external_exports.string()
22824
22941
  });
22825
22942
 
22943
+ // ../../packages/schema/src/zod/finding-delivery.ts
22944
+ var KNOWN_REASONS = SyncFailureReason.options;
22945
+ function knownReason(value) {
22946
+ return value !== null && KNOWN_REASONS.includes(value) ? value : void 0;
22947
+ }
22948
+ function deriveFindingDelivery(row) {
22949
+ if (row.kind === "code_change") return { state: "local_scan" };
22950
+ if (row.syncedAt !== null && row.syncedAt > 0) {
22951
+ return { state: "sent", at: epochMillisToIso(row.syncedAt) };
22952
+ }
22953
+ if (row.syncedAt !== null) {
22954
+ const reason = knownReason(row.syncFailure);
22955
+ return {
22956
+ state: "not_sent",
22957
+ ...row.syncFailedAt === null ? {} : { at: epochMillisToIso(row.syncFailedAt) },
22958
+ ...reason === void 0 ? {} : { reason }
22959
+ };
22960
+ }
22961
+ if (row.outboxOwed === 1 || row.syncClaimedAt !== null) return { state: "queued" };
22962
+ return { state: "never_offered" };
22963
+ }
22964
+
22826
22965
  // ../../packages/schema/src/zod/findings-group-build.ts
22966
+ function lookupOwn(map2, key) {
22967
+ return Object.hasOwn(map2, key) ? map2[key] : void 0;
22968
+ }
22827
22969
  function toApiAction(dbVal) {
22828
22970
  const map2 = {
22829
22971
  log: "monitored",
@@ -22832,7 +22974,7 @@ function toApiAction(dbVal) {
22832
22974
  warn: "warned",
22833
22975
  allow: "allowed"
22834
22976
  };
22835
- return map2[dbVal] ?? "allowed";
22977
+ return lookupOwn(map2, dbVal) ?? "allowed";
22836
22978
  }
22837
22979
  function toApiCategory(dbVal) {
22838
22980
  if (dbVal === "code_context") return "source_code";
@@ -22840,13 +22982,18 @@ function toApiCategory(dbVal) {
22840
22982
  return parsed2.success ? parsed2.data : "custom";
22841
22983
  }
22842
22984
  function toApiProvider(sourceTool) {
22843
- return TOOL_TO_HARNESS[sourceTool] ?? HARNESS.Api;
22985
+ return lookupOwn(TOOL_TO_HARNESS, sourceTool) ?? HARNESS.Api;
22844
22986
  }
22845
- var STATUS_PRECEDENCE = ["open", "handled", "dismissed", "resolved"];
22987
+ var FINDING_STATUS_PRECEDENCE = [
22988
+ "open",
22989
+ "handled",
22990
+ "dismissed",
22991
+ "resolved"
22992
+ ];
22846
22993
  function foldGroupStatus(instanceStatuses) {
22847
22994
  const statuses = new Set(instanceStatuses.filter((s) => s !== void 0));
22848
22995
  if (statuses.size === 0) return void 0;
22849
- for (const candidate of STATUS_PRECEDENCE) {
22996
+ for (const candidate of FINDING_STATUS_PRECEDENCE) {
22850
22997
  if (statuses.has(candidate)) return candidate;
22851
22998
  }
22852
22999
  return void 0;
@@ -22953,11 +23100,16 @@ function applyFindingFilters(types, opts) {
22953
23100
  }
22954
23101
  return filtered;
22955
23102
  }
22956
- var SEVERITY_ORDER = { critical: 0, high: 1, medium: 2, low: 3 };
22957
- var SEVERITY_RANK = SEVERITY_ORDER;
23103
+ function rankByOrder(members2) {
23104
+ return Object.fromEntries(members2.map((member, index) => [member, index]));
23105
+ }
23106
+ var SEVERITY_RANK = rankByOrder(Severity.options);
23107
+ function severityRank(severity) {
23108
+ return lookupOwn(SEVERITY_RANK, severity);
23109
+ }
22958
23110
  function compareFindingGroupOrder(a, b) {
22959
- const rankA = SEVERITY_RANK[a.severity] ?? -1;
22960
- const rankB = SEVERITY_RANK[b.severity] ?? -1;
23111
+ const rankA = severityRank(a.severity) ?? -1;
23112
+ const rankB = severityRank(b.severity) ?? -1;
22961
23113
  const severityDiff = rankA - rankB;
22962
23114
  if (severityDiff !== 0) return severityDiff;
22963
23115
  const recencyDiff = b.latestDetectedAt.localeCompare(a.latestDetectedAt);
@@ -23032,6 +23184,20 @@ function computeFindingFacets(allTypes, opts) {
23032
23184
  }
23033
23185
 
23034
23186
  // ../../packages/schema/src/zod/findings-flat-build.ts
23187
+ function compareCodePoints(a, b) {
23188
+ const aIter = a[Symbol.iterator]();
23189
+ const bIter = b[Symbol.iterator]();
23190
+ for (; ; ) {
23191
+ const aNext = aIter.next();
23192
+ const bNext = bIter.next();
23193
+ if (aNext.done && bNext.done) return 0;
23194
+ if (aNext.done) return -1;
23195
+ if (bNext.done) return 1;
23196
+ const aPoint = aNext.value.codePointAt(0) ?? 0;
23197
+ const bPoint = bNext.value.codePointAt(0) ?? 0;
23198
+ if (aPoint !== bPoint) return aPoint - bPoint;
23199
+ }
23200
+ }
23035
23201
  function rowHaystack(row) {
23036
23202
  return [
23037
23203
  row.ruleId,
@@ -23056,6 +23222,8 @@ function matchesDimension(row, opts, dimension) {
23056
23222
  return !opts.actions?.length || opts.actions.includes(toApiAction(row.actionTaken));
23057
23223
  case "statuses":
23058
23224
  return !opts.statuses?.length || row.status !== void 0 && opts.statuses.includes(row.status);
23225
+ case "deliveries":
23226
+ return !opts.deliveries?.length || row.delivery !== void 0 && opts.deliveries.includes(row.delivery.state);
23059
23227
  case "tools":
23060
23228
  return !opts.tools?.length || row.toolName !== void 0 && opts.tools.includes(row.toolName);
23061
23229
  // An EMPTY value is a real filter here, not an absent one. The location
@@ -23082,6 +23250,7 @@ var DIMENSIONS = [
23082
23250
  "providers",
23083
23251
  "actions",
23084
23252
  "statuses",
23253
+ "deliveries",
23085
23254
  "tools",
23086
23255
  "repo",
23087
23256
  "file",
@@ -23095,10 +23264,19 @@ function matchesInstanceFilters(row, opts, except) {
23095
23264
  return true;
23096
23265
  }
23097
23266
  function toItems(counts) {
23098
- return [...counts.entries()].map(([value, count]) => ({ value, count })).sort((a, b) => b.count - a.count || a.value.localeCompare(b.value));
23267
+ return [...counts.entries()].map(([value, count]) => ({ value, count })).sort(
23268
+ (a, b) => b.count - a.count || a.value.localeCompare(b.value) || // localeCompare reports canonically-equivalent strings (an NFC and an
23269
+ // NFD spelling of the same text) as equal, so a count tie between
23270
+ // them would otherwise be ordered by whichever the Map iteration
23271
+ // produced. compareCodePoints breaks that tie deterministically, which
23272
+ // makes this a TOTAL order — not one that agrees with SQL collation,
23273
+ // which it need not: foldFacetTuples runs this same sort over grouped
23274
+ // tuples, so both paths order facets identically by construction.
23275
+ compareCodePoints(a.value, b.value)
23276
+ );
23099
23277
  }
23100
- function bump(counts, value) {
23101
- counts.set(value, (counts.get(value) ?? 0) + 1);
23278
+ function bump(counts, value, by = 1) {
23279
+ counts.set(value, (counts.get(value) ?? 0) + by);
23102
23280
  }
23103
23281
  function createInstanceFacetAccumulator(opts) {
23104
23282
  const severity = /* @__PURE__ */ new Map();
@@ -23107,6 +23285,7 @@ function createInstanceFacetAccumulator(opts) {
23107
23285
  const action = /* @__PURE__ */ new Map();
23108
23286
  const status = /* @__PURE__ */ new Map();
23109
23287
  const tool = /* @__PURE__ */ new Map();
23288
+ const deployment = /* @__PURE__ */ new Map();
23110
23289
  return {
23111
23290
  add(row) {
23112
23291
  if (matchesInstanceFilters(row, opts, "severity")) bump(severity, row.severity);
@@ -23121,6 +23300,9 @@ function createInstanceFacetAccumulator(opts) {
23121
23300
  if (row.toolName !== void 0 && matchesInstanceFilters(row, opts, "tools")) {
23122
23301
  bump(tool, row.toolName);
23123
23302
  }
23303
+ if (row.delivery !== void 0 && matchesInstanceFilters(row, opts, "deliveries")) {
23304
+ bump(deployment, row.delivery.state);
23305
+ }
23124
23306
  },
23125
23307
  facets: () => ({
23126
23308
  severity: toItems(severity),
@@ -23128,7 +23310,8 @@ function createInstanceFacetAccumulator(opts) {
23128
23310
  provider: toItems(provider),
23129
23311
  action: toItems(action),
23130
23312
  status: toItems(status),
23131
- tool: toItems(tool)
23313
+ tool: toItems(tool),
23314
+ deployment: toItems(deployment)
23132
23315
  })
23133
23316
  };
23134
23317
  }
@@ -23142,6 +23325,7 @@ function toInstanceDetail(row) {
23142
23325
  ...row.toolName === void 0 ? {} : { toolName: row.toolName },
23143
23326
  eventId: row.eventId,
23144
23327
  ...row.sessionId === void 0 ? {} : { sessionId: row.sessionId },
23328
+ ...row.delivery === void 0 ? {} : { delivery: row.delivery },
23145
23329
  ...row.user === void 0 ? {} : { user: row.user },
23146
23330
  action: toApiAction(row.actionTaken),
23147
23331
  detectedAt: row.occurredAt,
@@ -23156,12 +23340,6 @@ function toInstanceDetail(row) {
23156
23340
  policy: { id: `category:${category}`, name: category }
23157
23341
  };
23158
23342
  }
23159
- var SEVERITY_ORDER2 = {
23160
- critical: 0,
23161
- high: 1,
23162
- medium: 2,
23163
- low: 3
23164
- };
23165
23343
  function newLocationAccumulator() {
23166
23344
  return {
23167
23345
  instanceCount: 0,
@@ -23176,7 +23354,7 @@ function newLocationAccumulator() {
23176
23354
  }
23177
23355
  function addToLocation(acc, row) {
23178
23356
  acc.instanceCount += 1;
23179
- const rank = SEVERITY_ORDER2[row.severity] ?? Number.MAX_SAFE_INTEGER - 1;
23357
+ const rank = severityRank(row.severity) ?? Number.MAX_SAFE_INTEGER - 1;
23180
23358
  if (rank < acc.maxSeverityRank) {
23181
23359
  acc.maxSeverityRank = rank;
23182
23360
  acc.maxSeverity = row.severity;
@@ -23186,15 +23364,15 @@ function addToLocation(acc, row) {
23186
23364
  acc.ruleIds.add(row.ruleId);
23187
23365
  }
23188
23366
  function compareLocationOrder(a, b) {
23189
- const rankA = SEVERITY_ORDER2[a.maxSeverity] ?? -1;
23190
- const rankB = SEVERITY_ORDER2[b.maxSeverity] ?? -1;
23367
+ const rankA = severityRank(a.maxSeverity) ?? -1;
23368
+ const rankB = severityRank(b.maxSeverity) ?? -1;
23191
23369
  if (rankA !== rankB) return rankA - rankB;
23192
23370
  if (a.latestDetectedAt !== b.latestDetectedAt) {
23193
23371
  return a.latestDetectedAt < b.latestDetectedAt ? 1 : -1;
23194
23372
  }
23195
- if (a.repo !== b.repo) return a.repo < b.repo ? -1 : 1;
23196
- if (a.file !== b.file) return a.file < b.file ? -1 : 1;
23197
- return 0;
23373
+ const repoDiff = compareCodePoints(a.repo, b.repo);
23374
+ if (repoDiff !== 0) return repoDiff;
23375
+ return compareCodePoints(a.file, b.file);
23198
23376
  }
23199
23377
  function encodeLocationId(repo, file2) {
23200
23378
  return `${encodePart(repo)}/${encodePart(file2)}`;
@@ -23269,6 +23447,11 @@ var Policy = external_exports.object({
23269
23447
  // test `prohibitedModels` passes and `reversibleRuleIds` fails.
23270
23448
  provenance: PolicyProvenance.optional()
23271
23449
  }).meta({ id: "Policy" });
23450
+ var KNOWN_BUILTIN_IDS = ["monitor", "warn", "redact", "vault", "block"];
23451
+ var BuiltinPolicyId = external_exports.enum(KNOWN_BUILTIN_IDS).meta({ id: "BuiltinPolicyId" });
23452
+ var RedactFallback = BuiltinPolicyId.extract(["monitor", "warn", "block"]).meta({
23453
+ id: "RedactFallback"
23454
+ });
23272
23455
  var PolicyBundle = external_exports.object({
23273
23456
  version: external_exports.string(),
23274
23457
  policies: external_exports.array(Policy),
@@ -23316,6 +23499,16 @@ var PolicyBundle = external_exports.object({
23316
23499
  // control plane), so no name resolution stands between the decision and the
23317
23500
  // comparison.
23318
23501
  prohibitedModels: external_exports.array(external_exports.string()).optional(),
23502
+ // What a resolved `redact` becomes on a field the host cannot rewrite, as
23503
+ // the ORGANIZATION would have it. Merged raise-only against the device's own
23504
+ // `WorkspaceSettings.redactFallback` (see strongerRedactFallback below), so
23505
+ // a control plane can tighten a machine and never loosen one — the same
23506
+ // direction `mergeRaiseOnly` enforces for policies.
23507
+ //
23508
+ // Optional so an older backend, and an older on-disk cache, still parses;
23509
+ // absent leaves the device's own setting in force, which is the behaviour
23510
+ // that predates the field and the safe direction to default.
23511
+ redactFallback: RedactFallback.optional(),
23319
23512
  customKeywords: external_exports.array(external_exports.string()),
23320
23513
  fetchedAt: external_exports.iso.datetime()
23321
23514
  }).meta({ id: "PolicyBundle" });
@@ -23345,11 +23538,6 @@ function severityFloorPolicy(category) {
23345
23538
  const peak = CATEGORY_PEAK_SEVERITY[category];
23346
23539
  return peak === "critical" || peak === "high" ? "warn" : "monitor";
23347
23540
  }
23348
- var KNOWN_BUILTIN_IDS = ["monitor", "warn", "redact", "vault", "block"];
23349
- var BuiltinPolicyId = external_exports.enum(KNOWN_BUILTIN_IDS).meta({ id: "BuiltinPolicyId" });
23350
- var RedactFallback = BuiltinPolicyId.extract(["monitor", "warn", "block"]).meta({
23351
- id: "RedactFallback"
23352
- });
23353
23541
  var BUILTIN_ORDER = KNOWN_BUILTIN_IDS;
23354
23542
  var BUILTIN_POLICY_SPECS = {
23355
23543
  monitor: {
@@ -23405,6 +23593,11 @@ function isActionAtLeast(action, floor) {
23405
23593
  function strongerAction(a, b) {
23406
23594
  return actionRank(a) >= actionRank(b) ? a : b;
23407
23595
  }
23596
+ function strongerRedactFallback(local, remote) {
23597
+ if (remote === void 0) return local;
23598
+ const localAction = builtinPolicyToAction(local);
23599
+ return localAction === strongerAction(localAction, builtinPolicyToAction(remote)) ? local : remote;
23600
+ }
23408
23601
  function weakestBuiltinAtLeast(floor) {
23409
23602
  return KNOWN_BUILTIN_IDS.find((id) => isActionAtLeast(builtinPolicyToAction(id), floor)) ?? "block";
23410
23603
  }
@@ -23653,7 +23846,7 @@ function isVaultConsentValid(consent) {
23653
23846
  }
23654
23847
 
23655
23848
  // ../../packages/schema/src/zod/local.ts
23656
- var WORKSPACE_SETTINGS_SPEC_VERSION = 7;
23849
+ var WORKSPACE_SETTINGS_SPEC_VERSION = 8;
23657
23850
  var MODEL_JUDGE_PAYLOAD_VERSION = 1;
23658
23851
  var RunMode = external_exports.enum(["standalone", "attached"]);
23659
23852
  var ControlPlaneConnection = external_exports.object({
@@ -23673,6 +23866,15 @@ var HistorySyncConsent = external_exports.object({
23673
23866
  payloadVersion: external_exports.number().int().positive(),
23674
23867
  endpoint: external_exports.string()
23675
23868
  });
23869
+ var BODY_RETENTION_DEFAULT_DAYS = 30;
23870
+ var BodyRetention = external_exports.object({
23871
+ enabled: external_exports.boolean().default(false),
23872
+ // Never 0, and the ceiling is a fat-finger guard rather than a policy
23873
+ // limit — `enabled` is the real gate. A low value cannot reach a row the
23874
+ // sync ledger still owes: the sweep's age filter only ever NARROWS a
23875
+ // candidate set that is already bounded by "delivered, or never owed".
23876
+ retainDays: external_exports.number().int().min(1).max(3650).default(BODY_RETENTION_DEFAULT_DAYS)
23877
+ }).meta({ id: "BodyRetention" });
23676
23878
  var WorkspaceSettings = external_exports.object({
23677
23879
  specVersion: external_exports.number().int().positive().default(WORKSPACE_SETTINGS_SPEC_VERSION),
23678
23880
  runMode: RunMode.default("standalone"),
@@ -23721,7 +23923,13 @@ var WorkspaceSettings = external_exports.object({
23721
23923
  // carry prompt/reply/tool-output text in `content`; the key name predates
23722
23924
  // both widenings. Absent until granted, and a grant for a different endpoint
23723
23925
  // or an older payload no longer counts.
23724
- historySyncConsent: HistorySyncConsent.optional()
23926
+ historySyncConsent: HistorySyncConsent.optional(),
23927
+ // Local body expiry (see BodyRetention). Off until switched on; expiring a
23928
+ // body never removes the row or its findings.
23929
+ bodyRetention: BodyRetention.default({
23930
+ enabled: false,
23931
+ retainDays: BODY_RETENTION_DEFAULT_DAYS
23932
+ })
23725
23933
  });
23726
23934
  function defaultWorkspaceSettings() {
23727
23935
  return WorkspaceSettings.parse({});
@@ -23816,12 +24024,15 @@ function toCaptureAttributes(event) {
23816
24024
  ...metadata?.traceId !== void 0 ? { trace_id: metadata.traceId } : {},
23817
24025
  ...metadata?.exceptionIds !== void 0 ? { exception_ids: metadata.exceptionIds } : {},
23818
24026
  ...metadata?.inspectionMs !== void 0 ? { inspection_ms: metadata.inspectionMs } : {},
24027
+ ...metadata?.redactDegradedTo !== void 0 ? { redact_degraded_to: metadata.redactDegradedTo } : {},
23819
24028
  // `model`/`turnIndex` have no dedicated CaptureAttributes field (no writer
23820
24029
  // has ever populated either), but every legacy metadata key still rides
23821
24030
  // the bag rather than being silently dropped — CaptureAttributes'
23822
24031
  // `.catchall(z.unknown())` carries the long tail.
23823
24032
  ...metadata?.model !== void 0 ? { model: metadata.model } : {},
23824
- ...metadata?.turnIndex !== void 0 ? { turn_index: metadata.turnIndex } : {}
24033
+ ...metadata?.turnIndex !== void 0 ? { turn_index: metadata.turnIndex } : {},
24034
+ ...metadata?.messageId !== void 0 ? { message_id: metadata.messageId } : {},
24035
+ ...metadata?.conversationId !== void 0 ? { conversation_id: metadata.conversationId } : {}
23825
24036
  };
23826
24037
  }
23827
24038
  function captureDefinitionVersion(finding) {
@@ -23849,13 +24060,22 @@ var ManagedSettingKey = external_exports.enum([
23849
24060
  "vaultInlineReveal",
23850
24061
  "modelJudgeConsent",
23851
24062
  "dataSharesInPlace",
23852
- "redactFallback"
24063
+ "redactFallback",
24064
+ // Pins the toggle and the day count together — see BodyRetention on why the
24065
+ // two are one unit. An administrator mandating a window wants the count
24066
+ // enforced with it, not one a user can widen while the toggle stays on.
24067
+ "bodyRetention"
23853
24068
  ]).meta({ id: "ManagedSettingKey" });
23854
24069
  function isManagedSettingKey(value) {
23855
24070
  return ManagedSettingKey.safeParse(value).success;
23856
24071
  }
23857
24072
  var ManagedSettingsValues = external_exports.object({
23858
24073
  runMode: external_exports.enum(["standalone", "attached"]).optional(),
24074
+ // `controlPlane` and `bodyRetention` are the two nested values, and both are
24075
+ // plain, non-strict objects: a key under either that this build does not know
24076
+ // is stripped and nothing reports it. The unknown-value split in
24077
+ // ManagedSettings below classifies top-level names only, so it stops at
24078
+ // these boundaries.
23859
24079
  controlPlane: external_exports.object({
23860
24080
  endpoint: external_exports.string().min(1),
23861
24081
  label: external_exports.string().min(1).optional()
@@ -23866,7 +24086,8 @@ var ManagedSettingsValues = external_exports.object({
23866
24086
  vaultInlineReveal: external_exports.enum(["masked", "full", "off"]).optional(),
23867
24087
  modelJudgeConsent: external_exports.boolean().optional(),
23868
24088
  dataSharesInPlace: external_exports.boolean().optional(),
23869
- redactFallback: RedactFallback.optional()
24089
+ redactFallback: RedactFallback.optional(),
24090
+ bodyRetention: BodyRetention.optional()
23870
24091
  }).meta({ id: "ManagedSettingsValues" });
23871
24092
  var ManagedSettings = external_exports.object({
23872
24093
  specVersion: external_exports.number().int().positive().default(MANAGED_SETTINGS_SPEC_VERSION),
@@ -23874,7 +24095,21 @@ var ManagedSettings = external_exports.object({
23874
24095
  // decision from a bug. Absent renders as a generic "your organization".
23875
24096
  organization: external_exports.string().min(1).optional(),
23876
24097
  // What the administrator pinned.
23877
- values: ManagedSettingsValues.default({}),
24098
+ //
24099
+ // Parsed as a RECORD rather than as the nested schema, and split below for
24100
+ // the same reason `lockedFields` is parsed as names: a plain `z.object`
24101
+ // drops an unrecognised key and succeeds, so a pin this build does not know
24102
+ // vanished and nothing anywhere said so. A pin with no lock is a supported
24103
+ // shape — it is a DEFAULT the user may still change — so that silence hit
24104
+ // exactly the file an administrator is most likely to write while a fleet
24105
+ // is mid-upgrade.
24106
+ //
24107
+ // Splitting here rather than calling `.strict()`: strict would REFUSE the
24108
+ // file, which is the outcome the lock half already rejected — an older
24109
+ // build then runs entirely unmanaged, every pin and lock gone. A bad KNOWN
24110
+ // value still fails, because the nested schema is re-run over the known
24111
+ // subset and its issues are re-raised on this parse.
24112
+ values: external_exports.record(external_exports.string(), external_exports.unknown()).default({}),
23878
24113
  // Which of those the user may not change. A key here with no matching value
23879
24114
  // freezes whatever the user last chose; a value with no lock is a DEFAULT
23880
24115
  // the user may still override. The two are separable on purpose.
@@ -23887,17 +24122,31 @@ var ManagedSettings = external_exports.object({
23887
24122
  // the fleets most likely to carry a version skew. A name outside the enum
23888
24123
  // is still never HONOURED: the lockable set stays explicit above.
23889
24124
  lockedFields: external_exports.array(external_exports.string()).default([])
23890
- }).transform(({ lockedFields, ...rest }) => {
24125
+ }).transform(({ lockedFields, values, ...rest }, ctx) => {
23891
24126
  const known = [];
23892
24127
  const unknown2 = [];
23893
24128
  for (const name of lockedFields) {
23894
24129
  if (isManagedSettingKey(name)) known.push(name);
23895
24130
  else unknown2.push(name);
23896
24131
  }
24132
+ const knownValues = /* @__PURE__ */ Object.create(null);
24133
+ const unknownValues = [];
24134
+ for (const [name, value] of Object.entries(values)) {
24135
+ if (Object.hasOwn(ManagedSettingsValues.shape, name)) knownValues[name] = value;
24136
+ else unknownValues.push(name);
24137
+ }
24138
+ const pinned = ManagedSettingsValues.safeParse(knownValues);
24139
+ if (!pinned.success) {
24140
+ for (const issue2 of pinned.error.issues)
24141
+ ctx.addIssue({ ...issue2, path: ["values", ...issue2.path] });
24142
+ return external_exports.NEVER;
24143
+ }
23897
24144
  return {
23898
24145
  ...rest,
24146
+ values: pinned.data,
23899
24147
  lockedFields: known,
23900
- ...unknown2.length > 0 ? { unknownLockedFields: unknown2 } : {}
24148
+ ...unknown2.length > 0 ? { unknownLockedFields: unknown2 } : {},
24149
+ ...unknownValues.length > 0 ? { unknownValueFields: unknownValues } : {}
23901
24150
  };
23902
24151
  }).meta({ id: "ManagedSettings" });
23903
24152
 
@@ -24161,7 +24410,23 @@ var SaveSettingsInput = external_exports.object({
24161
24410
  modelJudgeConsent: ModelJudgeConsentChoice,
24162
24411
  historySyncConsent: HistorySyncConsentChoice,
24163
24412
  vaultConsent: external_exports.string(),
24164
- vaultInlineReveal: external_exports.string()
24413
+ vaultInlineReveal: external_exports.string(),
24414
+ // Widened to `string` like its neighbours rather than typed as
24415
+ // `RedactFallback`, on this module's own layering rule: shape here, VALUE at
24416
+ // the call site, so the domain check receives the type it was written for.
24417
+ //
24418
+ // NOT because a narrower schema would reject differently. `parseActionInput`
24419
+ // is a `safeParse` wrapper and throws for no field schema, so either spelling
24420
+ // reaches a recoverable `{ ok: false }` and there is no rejected promise to
24421
+ // trade against. The real cost runs the other way and is the part worth
24422
+ // knowing: a value this schema admits and the domain enum then rejects lands
24423
+ // on the action's shared refusal, which names NO field, where a shape
24424
+ // rejection reaches `malformedInput` and names the schema key.
24425
+ redactFallback: external_exports.string(),
24426
+ // Shape only, the way the enum fields above are strings only: the RANGE is
24427
+ // `BodyRetention`'s and the action checks it there, so there is one place
24428
+ // that decides what a legal horizon is rather than two that can drift.
24429
+ bodyRetention: external_exports.object({ enabled: external_exports.boolean(), retainDays: external_exports.number() })
24165
24430
  });
24166
24431
  var AttachInput = external_exports.object({
24167
24432
  endpoint: external_exports.string(),
@@ -24333,6 +24598,52 @@ function reviewSeverityRank(reasons) {
24333
24598
  return Math.min(...reasons.map((r) => REVIEW_SEVERITY_RANK[r]));
24334
24599
  }
24335
24600
 
24601
+ // ../../packages/schema/src/zod/web-capture.ts
24602
+ var WebUsageSource = external_exports.enum(["site", "estimated", "none"]);
24603
+ var WebUsage = external_exports.object({
24604
+ inputTokens: external_exports.number().int().nonnegative().optional(),
24605
+ outputTokens: external_exports.number().int().nonnegative().optional(),
24606
+ cacheReadInputTokens: external_exports.number().int().nonnegative().optional(),
24607
+ cacheCreationInputTokens: external_exports.number().int().nonnegative().optional()
24608
+ });
24609
+ var WebToolCall = external_exports.object({
24610
+ toolUseId: external_exports.string().min(1),
24611
+ toolName: external_exports.string().min(1),
24612
+ target: external_exports.string().optional(),
24613
+ isError: external_exports.boolean().optional(),
24614
+ inputSize: external_exports.number().int().nonnegative().optional(),
24615
+ outputSize: external_exports.number().int().nonnegative().optional()
24616
+ });
24617
+ var WebExchange = external_exports.object({
24618
+ messageId: external_exports.string().min(1),
24619
+ startedAt: external_exports.iso.datetime(),
24620
+ model: external_exports.string().optional(),
24621
+ usage: WebUsage.optional(),
24622
+ usageSource: WebUsageSource,
24623
+ stopReason: external_exports.string().optional(),
24624
+ conversationId: external_exports.string().optional(),
24625
+ turnIndex: external_exports.number().int().nonnegative().optional(),
24626
+ toolCalls: external_exports.array(WebToolCall).default([]),
24627
+ // Absent when the adapter recovered no text. Capped by the caller at
24628
+ // RESPONSE_TEXT_MAX_BYTES; `truncated` records that the cap was reached, so a
24629
+ // short capture is never mistaken for a short reply.
24630
+ responseText: external_exports.string().optional(),
24631
+ truncated: external_exports.boolean().default(false)
24632
+ });
24633
+ var RESPONSE_TEXT_MAX_BYTES = 2 * 1024 * 1024;
24634
+ var WebCaptureStatus = external_exports.object({
24635
+ patched: external_exports.boolean(),
24636
+ live: external_exports.boolean(),
24637
+ blind: external_exports.boolean(),
24638
+ sendsSeenDom: external_exports.number().int().nonnegative(),
24639
+ exchangesSeenNet: external_exports.number().int().nonnegative(),
24640
+ parseFailures: external_exports.number().int().nonnegative(),
24641
+ unparsedBodies: external_exports.number().int().nonnegative(),
24642
+ // The adapter-declared JSON key paths that were absent from a real payload —
24643
+ // the earliest signal that a site's contract moved.
24644
+ shapeMisses: external_exports.array(external_exports.string()).default([])
24645
+ });
24646
+
24336
24647
  // ../../packages/persistence/src/paths.ts
24337
24648
  import {
24338
24649
  chmodSync,
@@ -24693,6 +25004,22 @@ function discardStore(file2, backup) {
24693
25004
  }
24694
25005
  }
24695
25006
 
25007
+ // ../../packages/persistence/src/internal/sql-functions.ts
25008
+ var utf8 = new TextDecoder();
25009
+ function akaLower(value) {
25010
+ if (value === null) return null;
25011
+ if (typeof value === "string") return value.toLowerCase();
25012
+ if (typeof value === "number" || typeof value === "bigint") return String(value).toLowerCase();
25013
+ return utf8.decode(value).toLowerCase();
25014
+ }
25015
+ function registerSqlFunctions(db) {
25016
+ db.function(
25017
+ "aka_lower",
25018
+ { deterministic: true, directOnly: true, useBigIntArguments: true },
25019
+ akaLower
25020
+ );
25021
+ }
25022
+
24696
25023
  // ../../packages/persistence/src/internal/sql-text.ts
24697
25024
  function escapeLikePattern(s) {
24698
25025
  return s.replace(/\\/g, "\\\\").replace(/%/g, "\\%").replace(/_/g, "\\_");
@@ -24777,6 +25104,11 @@ function schemaObjectExists(db, kind, name) {
24777
25104
  function indexExists(db, name) {
24778
25105
  return schemaObjectExists(db, "index", name);
24779
25106
  }
25107
+ function indexColumns(db, name) {
25108
+ if (!indexExists(db, name)) return [];
25109
+ const columns = db.prepare(`PRAGMA index_info(${name})`).all();
25110
+ return columns.map((c) => c.name).filter((c) => c !== null);
25111
+ }
24780
25112
  function columnNames(db, table, opts) {
24781
25113
  const pragma = opts?.includeGenerated ? "table_xinfo" : "table_info";
24782
25114
  const columns = db.prepare(`PRAGMA ${pragma}(${table})`).all();
@@ -24838,176 +25170,818 @@ function mapRowsTolerant(rows, map2) {
24838
25170
  return out;
24839
25171
  }
24840
25172
 
24841
- // ../../packages/persistence/src/migrations.ts
24842
- function describeObject(object2) {
24843
- return object2.kind === "column" ? `column ${object2.table}.${object2.name}` : `table ${object2.name}`;
24844
- }
24845
- function splitStatements(sql) {
24846
- return sql.split(/-->\s*statement-breakpoint/).map((s) => s.trim()).filter((s) => s.length > 0);
24847
- }
24848
- function createdIndexName(statement) {
24849
- const body = statement.replace(/^(?:\s*--[^\n]*\n?)+/, "").trimStart();
24850
- return /^CREATE (?:UNIQUE )?INDEX (?:IF NOT EXISTS )?`([^`]+)`/.exec(body)?.[1];
25173
+ // ../../packages/persistence/src/internal/outbox-lane.ts
25174
+ var OUTBOX_CAPTURE_EVENT_TYPES = ["prompt", "response", "tool_use"];
25175
+ var OUTBOX_CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25176
+
25177
+ // ../../packages/persistence/src/sync-failure.ts
25178
+ var SYNC_FAILURE_REASONS = SyncFailureReason.options;
25179
+ function syncFailureRejectCondition(column = "sync_failure") {
25180
+ const members2 = SYNC_FAILURE_REASONS.map((r) => `'${r}'`).join(", ");
25181
+ return `NEW.${column} IS NOT NULL AND NEW.${column} NOT IN (${members2})`;
24851
25182
  }
24852
- var LEGACY_DROP_MIGRATION_TAG = "0014_drop_legacy_events_findings";
24853
- function applyMigrations(db, file2) {
24854
- const legacyCount = db.prepare("PRAGMA user_version").get().user_version;
24855
- db.exec(
24856
- "CREATE TABLE IF NOT EXISTS migration_ledger (tag TEXT PRIMARY KEY, applied_at INTEGER NOT NULL)"
24857
- );
24858
- const applied = new Set(
24859
- db.prepare("SELECT tag FROM migration_ledger").all().map((r) => r.tag)
24860
- );
24861
- const preLedgerStore = applied.size === 0 && legacyCount > 0;
24862
- const record2 = db.prepare(
24863
- "INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)"
24864
- );
24865
- for (const [index, migration] of SQLITE_MIGRATIONS.entries()) {
24866
- if (applied.has(migration.tag)) continue;
24867
- if (migration.tag === LEGACY_DROP_MIGRATION_TAG) continue;
24868
- const evidence = evidenceObjects(migration.sql);
24869
- const present = evidence.filter((o) => evidenceExists(db, o));
24870
- if (present.length > 0 && present.length < evidence.length) {
24871
- const missing = evidence.filter((o) => !present.includes(o));
24872
- 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.`;
24873
- akaWarn(message);
24874
- throw new Error(`[aka] ${message}`);
24875
- }
24876
- const alreadyApplied = evidence.length > 0 ? present.length === evidence.length : preLedgerStore && index < legacyCount;
24877
- const wantsFkOff = /PRAGMA foreign_keys\s*=\s*OFF/i.test(migration.sql);
24878
- const statements = splitStatements(migration.sql);
24879
- if (wantsFkOff) db.exec("PRAGMA foreign_keys = OFF");
24880
- try {
24881
- withTransaction(
24882
- db,
24883
- () => {
24884
- for (const statement of statements) {
24885
- const indexName = createdIndexName(statement);
24886
- if (indexName === void 0) {
24887
- if (alreadyApplied) continue;
24888
- } else if (indexExists(db, indexName)) {
24889
- continue;
24890
- }
24891
- db.exec(statement);
24892
- }
24893
- if (wantsFkOff && !alreadyApplied) {
24894
- const violations = db.prepare("PRAGMA foreign_key_check").all();
24895
- if (violations.length > 0) {
24896
- throw new Error(
24897
- `[aka] sqlite migration ${migration.tag} left ${String(violations.length)} foreign-key violation(s); rolling back.`
24898
- );
24899
- }
24900
- }
24901
- record2.run(migration.tag, Date.now());
24902
- },
24903
- "IMMEDIATE"
24904
- );
24905
- } finally {
24906
- if (wantsFkOff) db.exec("PRAGMA foreign_keys = ON");
24907
- }
25183
+
25184
+ // ../../packages/persistence/src/repositories/history-sync.ts
25185
+ var STRUCTURAL_EVENT_TYPES = ["session", "llm_call", "tool_call"];
25186
+ var TYPE_LIST = STRUCTURAL_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25187
+ var CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_TYPE_LIST;
25188
+ var COUNTED_EVENT_TYPES = [
25189
+ ...STRUCTURAL_EVENT_TYPES,
25190
+ ...OUTBOX_CAPTURE_EVENT_TYPES
25191
+ ];
25192
+ var COUNTED_TYPE_LIST = COUNTED_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25193
+ var PARTITION_BUCKETS = `
25194
+ SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NULL THEN 1 ELSE 0 END) AS queued,
25195
+ SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NOT NULL THEN 1 ELSE 0 END) AS inProgress,
25196
+ SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS synced,
25197
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25198
+ AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
25199
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25200
+ AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached,
25201
+ -- Spelled as what it INCLUDES rather than what it excludes, so a reason
25202
+ -- added later lands in no bucket and fails the sum assertion, instead
25203
+ -- of silently joining this one.
25204
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25205
+ AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
25206
+ THEN 1 ELSE 0 END) AS failed,
25207
+ COUNT(*) AS total`;
25208
+ var COUNTED_SCOPE = `
25209
+ WHERE event_type IN (${COUNTED_TYPE_LIST})
25210
+ AND (
25211
+ event_type IN (${TYPE_LIST})
25212
+ OR synced_at IS NOT NULL
25213
+ OR outbox_owed = 1
25214
+ )`;
25215
+ var SKIPPED = -1;
25216
+ var ROW_COLUMNS = `id,
25217
+ parent_id AS parentId,
25218
+ root_session_id AS rootSessionId,
25219
+ event_type AS eventType,
25220
+ host_id AS hostId,
25221
+ harness_id AS harnessId,
25222
+ source_project_id AS sourceProjectId,
25223
+ started_at AS startedAt,
25224
+ ended_at AS endedAt,
25225
+ severity,
25226
+ priority,
25227
+ content,
25228
+ content_hash AS contentHash,
25229
+ attributes`;
25230
+ var SqliteHistorySyncRepository = class {
25231
+ constructor(db) {
25232
+ this.db = db;
25233
+ this.ensureRowStmt = db.prepare(`INSERT OR IGNORE INTO history_sync (id) VALUES (1)`);
25234
+ this.sessionsStmt = db.prepare(
25235
+ `SELECT COALESCE(root_session_id, id) AS sessionId, MIN(started_at) AS earliest
25236
+ FROM audit_events
25237
+ WHERE synced_at IS NULL
25238
+ AND event_type IN (${TYPE_LIST})
25239
+ AND started_at < :before
25240
+ GROUP BY sessionId
25241
+ ORDER BY earliest
25242
+ LIMIT :limit`
25243
+ );
25244
+ this.rowsStmt = db.prepare(
25245
+ `SELECT ${ROW_COLUMNS}
25246
+ FROM audit_events
25247
+ WHERE synced_at IS NULL
25248
+ AND event_type IN (${TYPE_LIST})
25249
+ AND started_at < :before
25250
+ AND COALESCE(root_session_id, id) = :sessionId
25251
+ ORDER BY (event_type = 'session') DESC, started_at
25252
+ LIMIT :limit`
25253
+ );
25254
+ this.captureRowsStmt = db.prepare(
25255
+ `SELECT ${ROW_COLUMNS}
25256
+ FROM audit_events
25257
+ WHERE synced_at IS NULL
25258
+ AND sync_claimed_at IS NULL
25259
+ AND outbox_owed = 1
25260
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25261
+ AND started_at < :before
25262
+ ORDER BY started_at
25263
+ LIMIT :limit`
25264
+ );
25265
+ this.markOwedStmt = db.prepare(
25266
+ `UPDATE audit_events SET outbox_owed = 1 WHERE id = :id AND synced_at IS NULL`
25267
+ );
25268
+ this.markCaptureBacklogOwedStmt = db.prepare(
25269
+ `UPDATE audit_events SET outbox_owed = 1
25270
+ WHERE synced_at IS NULL
25271
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25272
+ AND started_at < :before`
25273
+ );
25274
+ this.stampStmt = db.prepare(
25275
+ `UPDATE audit_events
25276
+ SET synced_at = :at,
25277
+ sync_claimed_at = NULL,
25278
+ sync_failed_at = :failedAt,
25279
+ sync_failure = :failure
25280
+ WHERE id = :id`
25281
+ );
25282
+ this.claimRowStmt = db.prepare(
25283
+ `UPDATE audit_events SET sync_claimed_at = :at WHERE id = :id AND synced_at IS NULL`
25284
+ );
25285
+ this.releaseRowStmt = db.prepare(
25286
+ `UPDATE audit_events SET sync_claimed_at = NULL WHERE id = :id`
25287
+ );
25288
+ this.releaseStaleClaimsStmt = db.prepare(
25289
+ `UPDATE audit_events SET sync_claimed_at = NULL
25290
+ WHERE sync_claimed_at IS NOT NULL AND sync_claimed_at < :staleBefore`
25291
+ );
25292
+ this.partitionStmt = db.prepare(`SELECT${PARTITION_BUCKETS}
25293
+ FROM audit_events${COUNTED_SCOPE}`);
25294
+ this.partitionByKindStmt = db.prepare(
25295
+ `SELECT event_type AS kind,${PARTITION_BUCKETS}
25296
+ FROM audit_events INDEXED BY idx_audit_events_sync${COUNTED_SCOPE}
25297
+ GROUP BY event_type`
25298
+ );
25299
+ this.countsStmt = db.prepare(
25300
+ `SELECT
25301
+ SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
25302
+ SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
25303
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25304
+ AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
25305
+ THEN 1 ELSE 0 END) AS skipped,
25306
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25307
+ AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
25308
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25309
+ AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached
25310
+ FROM audit_events
25311
+ WHERE event_type IN (${TYPE_LIST})`
25312
+ );
25313
+ this.captureSkipCountStmt = db.prepare(
25314
+ // EVERY sentinel capture, whatever the reason — deliberately NOT split the
25315
+ // way the structural totals are. The split exists because a refusal is
25316
+ // terminal only against the deployment that gave it, and the structural
25317
+ // re-arm frees it on a change of deployment. The capture lane has no such
25318
+ // escape: re-arming a capture would offer one deployment's undelivered
25319
+ // prompts, with their text, to a deployment that never saw them, which is
25320
+ // exactly what disownCapturesStmt exists to prevent. So on this lane both
25321
+ // reasons mean the same thing — this row will not be sent — and splitting
25322
+ // them would put refused captures in a bucket nothing reads and nothing
25323
+ // frees.
25324
+ `SELECT COUNT(*) AS skipped
25325
+ FROM audit_events
25326
+ WHERE synced_at = ${String(SKIPPED)}
25327
+ AND event_type IN (${CAPTURE_TYPE_LIST})`
25328
+ );
25329
+ this.fingerprintStmt = db.prepare(
25330
+ `SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
25331
+ FROM history_sync WHERE id = 1`
25332
+ );
25333
+ this.setFingerprintStmt = db.prepare(
25334
+ `UPDATE history_sync
25335
+ SET endpoint_fingerprint = :fingerprint, backlog_before = :backlogBefore
25336
+ WHERE id = 1`
25337
+ );
25338
+ this.disownCapturesStmt = db.prepare(
25339
+ `UPDATE audit_events SET outbox_owed = NULL
25340
+ WHERE outbox_owed IS NOT NULL
25341
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25342
+ AND started_at < :attachedAt`
25343
+ );
25344
+ this.rearmStmt = db.prepare(
25345
+ `UPDATE audit_events
25346
+ SET synced_at = NULL, sync_failed_at = NULL, sync_failure = NULL
25347
+ WHERE (synced_at > 0
25348
+ OR sync_failure IN ('deployment_refused', 'detached_undelivered'))
25349
+ AND event_type IN (${TYPE_LIST})`
25350
+ );
25351
+ this.claimStmt = db.prepare(
25352
+ `UPDATE history_sync
25353
+ SET owner_pid = :pid, owner_host = :host, acquired_at = :now, heartbeat_at = :now
25354
+ WHERE id = 1
25355
+ AND (owner_pid IS NULL
25356
+ OR heartbeat_at IS NULL
25357
+ OR heartbeat_at < :staleBefore
25358
+ OR heartbeat_at > :now)`
25359
+ );
25360
+ this.heartbeatStmt = db.prepare(
25361
+ `UPDATE history_sync SET heartbeat_at = :now WHERE id = 1 AND owner_pid = :pid`
25362
+ );
25363
+ this.releaseStmt = db.prepare(
25364
+ `UPDATE history_sync
25365
+ SET owner_pid = NULL, owner_host = NULL, acquired_at = NULL, heartbeat_at = NULL
25366
+ WHERE id = 1 AND owner_pid = :pid`
25367
+ );
25368
+ this.closeWindowStmt = db.prepare(
25369
+ `UPDATE audit_events
25370
+ SET synced_at = ${String(SKIPPED)},
25371
+ sync_failed_at = :at,
25372
+ sync_failure = 'detached_undelivered'
25373
+ WHERE synced_at IS NULL
25374
+ AND event_type IN (${TYPE_LIST})
25375
+ AND started_at >= :attachedAt`
25376
+ );
25377
+ this.releaseBoundaryStmt = db.prepare(
25378
+ `UPDATE history_sync SET backlog_before = NULL WHERE id = 1`
25379
+ );
25380
+ this.freezeBoundaryStmt = db.prepare(
25381
+ `UPDATE history_sync SET backlog_before = :backlogBefore WHERE id = 1`
25382
+ );
25383
+ this.leaseStmt = db.prepare(
25384
+ `SELECT owner_pid AS ownerPid, owner_host AS ownerHost,
25385
+ acquired_at AS acquiredAt, heartbeat_at AS heartbeatAt
25386
+ FROM history_sync WHERE id = 1`
25387
+ );
25388
+ this.inspectionsStmt = db.prepare(
25389
+ `SELECT d.rule_id AS ruleId,
25390
+ d.name AS ruleName,
25391
+ d.version AS ruleVersion,
25392
+ d.category AS category,
25393
+ d.severity AS severity,
25394
+ f.span_start AS spanStart,
25395
+ f.span_end AS spanEnd,
25396
+ f.masked_match AS maskedMatch,
25397
+ f.action_taken AS actionTaken,
25398
+ f.confidence AS confidence
25399
+ FROM inspection_findings f
25400
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
25401
+ WHERE f.audit_event_id = :auditEventId
25402
+ ORDER BY f.span_start, f.id`
25403
+ );
24908
25404
  }
24909
- if (legacyCount < SQLITE_MIGRATIONS.length) {
24910
- db.exec(`PRAGMA user_version = ${String(SQLITE_MIGRATIONS.length)}`);
25405
+ db;
25406
+ ensureRowStmt;
25407
+ sessionsStmt;
25408
+ rowsStmt;
25409
+ stampStmt;
25410
+ countsStmt;
25411
+ fingerprintStmt;
25412
+ setFingerprintStmt;
25413
+ rearmStmt;
25414
+ claimStmt;
25415
+ heartbeatStmt;
25416
+ releaseStmt;
25417
+ leaseStmt;
25418
+ inspectionsStmt;
25419
+ closeWindowStmt;
25420
+ releaseBoundaryStmt;
25421
+ freezeBoundaryStmt;
25422
+ captureRowsStmt;
25423
+ markOwedStmt;
25424
+ markCaptureBacklogOwedStmt;
25425
+ captureSkipCountStmt;
25426
+ disownCapturesStmt;
25427
+ partitionStmt;
25428
+ partitionByKindStmt;
25429
+ claimRowStmt;
25430
+ releaseRowStmt;
25431
+ releaseStaleClaimsStmt;
25432
+ /**
25433
+ * The masked detections recorded against one tool call.
25434
+ *
25435
+ * These travel with the event because a tool call's target is not
25436
+ * re-inspectable from the event alone — unlike a capture, where the text
25437
+ * itself is re-scannable. What crosses is the masked match and the rule that
25438
+ * produced it, never the value.
25439
+ */
25440
+ inspectionsFor(auditEventId) {
25441
+ return allRows(this.inspectionsStmt, { auditEventId });
24911
25442
  }
24912
- ensureSyncedAtColumn(db, "audit_events");
24913
- ensureScanLedgerTable(db);
24914
- ensureHistorySyncTable(db);
24915
- ensureBlockedDetectionsTable(db);
24916
- ensureRuleProbeCacheTable(db);
24917
- ensureWriteGateTrigger(db);
24918
- ensureTokenUsageColumns(db);
24919
- reconcileSourceProjectIds(db);
24920
- if (!applied.has(LEGACY_DROP_MIGRATION_TAG)) {
24921
- const drained = runLegacyHistoryBackfill(db);
24922
- if (drained) applyLegacyDropMigration(db, file2);
25443
+ /**
25444
+ * Sessions with structural rows still to send, oldest first.
25445
+ *
25446
+ * BOUNDED BY THE BACKLOG BOUNDARY, which is the whole correctness of this
25447
+ * read. Anything recorded after the machine attached is the live forward
25448
+ * path's to deliver; this drain exists for what was recorded before it, and a
25449
+ * row both paths send is at best a duplicate request and at worst — for a
25450
+ * session root — an overwrite of the inventory ids the live path resolved.
25451
+ */
25452
+ pendingSessions(limit, before) {
25453
+ return allRows(this.sessionsStmt, { limit, before }).map(
25454
+ (r) => r.sessionId
25455
+ );
24923
25456
  }
24924
- }
24925
- function readLegacyTables(db) {
24926
- let holdsRows = false;
24927
- const marks = [];
24928
- for (const table of ["events", "findings"]) {
24929
- try {
24930
- const row = db.prepare(`SELECT count(*) AS n, ifnull(max(rowid), -1) AS hi FROM ${table}`).get();
24931
- if (row === void 0) {
24932
- holdsRows = true;
24933
- marks.push(`${table}:unreadable`);
24934
- continue;
24935
- }
24936
- if (row.n > 0) holdsRows = true;
24937
- marks.push(`${table}:${String(row.n)}:${String(row.hi)}`);
24938
- } catch {
24939
- holdsRows = true;
24940
- marks.push(`${table}:unreadable`);
24941
- }
25457
+ /** One session's undelivered structural rows within the backlog, root first. */
25458
+ pendingRows(sessionId, limit, before) {
25459
+ return allRows(this.rowsStmt, { sessionId, limit, before });
24942
25460
  }
24943
- return { holdsRows, mark: marks.join("|") };
24944
- }
24945
- function applyLegacyDropMigration(db, file2) {
24946
- const migration = SQLITE_MIGRATIONS.find((m) => m.tag === LEGACY_DROP_MIGRATION_TAG);
24947
- if (!migration) return;
24948
- const before = file2 === void 0 ? void 0 : readLegacyTables(db);
24949
- if (file2 !== void 0 && before?.holdsRows === true) {
24950
- try {
24951
- backupBeforeLegacyDrop(db, file2);
24952
- } catch (error61) {
24953
- akaWarn(`legacy events/findings backup failed; deferring the drop: ${String(error61)}`);
24954
- return;
24955
- }
25461
+ /**
25462
+ * Captures this machine still owes the deployment, oldest first.
25463
+ *
25464
+ * Selected by the `outbox_owed` marker the attached forward path writes, not
25465
+ * by a time window — see captureRowsStmt for why a window could not express
25466
+ * this. `before` is the grace window that leaves a just-recorded capture to
25467
+ * the live path.
25468
+ */
25469
+ pendingCaptureRows(limit, before) {
25470
+ return allRows(this.captureRowsStmt, { limit, before });
24956
25471
  }
24957
- try {
25472
+ /**
25473
+ * Record that a capture is OWED to the deployment.
25474
+ *
25475
+ * Written by the attached forward path when a live send did not confirm
25476
+ * delivery, and read by the drain as the whole of its eligibility test. It is
25477
+ * a fact rather than an inference: the machine was attached, the send did not
25478
+ * land, so the row is owed — which no time window can state, because the same
25479
+ * window that holds the rows a past attachment left owed also holds every
25480
+ * capture recorded while the machine was DETACHED, and those were never
25481
+ * offered to anyone.
25482
+ *
25483
+ * Idempotent, and never un-set: `markSynced` settling the row is what takes it
25484
+ * out of the drain's read.
25485
+ */
25486
+ markCaptureOwed(id) {
25487
+ this.markOwedStmt.run({ id });
25488
+ }
25489
+ /**
25490
+ * Mark every capture already on disk as owed, as of `before`.
25491
+ *
25492
+ * The consent-time backfill, called once from `aka attach` when a human
25493
+ * grants existing-history consent — never from an ongoing drain pass, and
25494
+ * never inferred from a boundary that could later move. `before` is the
25495
+ * caller's own "now" at the moment consent was granted, so what this marks
25496
+ * is exactly the backlog the consent prompt already counted, not whatever a
25497
+ * later re-attach or key rotation might widen it to.
25498
+ *
25499
+ * Returns how many rows matched, for the caller to log or test against. Not a
25500
+ * count of NEWLY marked rows — a row still unsynced from an earlier call
25501
+ * matches again and is counted again, the same as `UPDATE`'s own `changes`.
25502
+ */
25503
+ markCaptureBacklogOwed(before) {
25504
+ return Number(this.markCaptureBacklogOwedStmt.run({ before }).changes);
25505
+ }
25506
+ /**
25507
+ * Record delivery. Called only AFTER the far side has accepted the rows.
25508
+ *
25509
+ * CLEARS any failure reason in the same statement. A row that failed against
25510
+ * one deployment and then landed is delivered, and leaving the reason behind
25511
+ * would leave the store holding two contradictory answers about one row —
25512
+ * with the surface free to render either.
25513
+ */
25514
+ markSynced(ids, atMs) {
25515
+ this.stampAll(ids, atMs, null);
25516
+ }
25517
+ /**
25518
+ * Record that THIS MACHINE cannot express the row on the wire.
25519
+ *
25520
+ * Reserved for a local defect — a row that cannot be rebuilt into a valid
25521
+ * payload, or a body the client itself refused to send. It fails identically
25522
+ * against every deployment, so it is terminal everywhere and the re-arm leaves
25523
+ * it alone. A row that merely failed to REACH the deployment stays NULL, so it
25524
+ * is retried; marking those would turn one outage into permanent data loss.
25525
+ */
25526
+ markSkipped(ids, atMs) {
25527
+ this.stampAll(ids, SKIPPED, "payload_invalid", atMs);
25528
+ }
25529
+ /**
25530
+ * Record that THIS DEPLOYMENT refused the row.
25531
+ *
25532
+ * The same sentinel as `markSkipped`, and deliberately so: both stop the row
25533
+ * being re-offered on this lane, and `synced_at` goes on answering whether a
25534
+ * row is outstanding rather than why. What separates them is the reason, and
25535
+ * what the reason buys is the re-arm — a refusal is one deployment's verdict
25536
+ * on one body, so it is terminal only for as long as this machine points at
25537
+ * that deployment, and `rearmFor` clears it when the deployment changes.
25538
+ *
25539
+ * Leaving such a row NULL instead would be worse than the loss it replaces:
25540
+ * these reads carry no cursor, so an unstamped row the deployment refuses is
25541
+ * the head of every subsequent page, and the lane stalls behind it for ever.
25542
+ */
25543
+ markRefused(ids, atMs) {
25544
+ this.stampAll(ids, SKIPPED, "deployment_refused", atMs);
25545
+ }
25546
+ eachInTransaction(ids, run) {
25547
+ if (ids.length === 0) return;
24958
25548
  withTransaction(
24959
- db,
25549
+ this.db,
24960
25550
  () => {
24961
- const alreadyDropped = db.prepare("SELECT 1 FROM migration_ledger WHERE tag = ?").get(migration.tag);
24962
- if (alreadyDropped) return;
24963
- if (before !== void 0 && readLegacyTables(db).mark !== before.mark) {
24964
- akaWarn(
24965
- "legacy events/findings rows changed after the pre-drop snapshot decision; deferring the drop so the next open can copy them first."
24966
- );
24967
- return;
24968
- }
24969
- for (const statement of splitStatements(migration.sql)) {
24970
- db.exec(statement);
24971
- }
24972
- db.prepare("INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)").run(
24973
- migration.tag,
24974
- Date.now()
24975
- );
25551
+ for (const id of ids) run(id);
24976
25552
  },
24977
25553
  "IMMEDIATE"
24978
25554
  );
24979
- } catch (error61) {
24980
- akaWarn(`legacy events/findings drop failed; deferring: ${String(error61)}`);
24981
25555
  }
24982
- }
24983
- function backupBeforeLegacyDrop(db, file2) {
24984
- reapStalePartials(file2);
24985
- const backup = backupPath(file2, "pre-drop");
24986
- snapshotStore(db, backup);
24987
- return backup;
24988
- }
24989
- var TOKEN_USAGE_COLUMNS = [
24990
- {
24991
- name: "input_tokens",
24992
- ddl: "ALTER TABLE audit_events ADD COLUMN input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.input_tokens')) VIRTUAL"
24993
- },
24994
- {
24995
- name: "output_tokens",
24996
- ddl: "ALTER TABLE audit_events ADD COLUMN output_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.output_tokens')) VIRTUAL"
24997
- },
24998
- {
24999
- name: "cache_creation_input_tokens",
25000
- ddl: "ALTER TABLE audit_events ADD COLUMN cache_creation_input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.cache_creation_input_tokens')) VIRTUAL"
25001
- },
25002
- {
25003
- name: "cache_read_input_tokens",
25004
- ddl: "ALTER TABLE audit_events ADD COLUMN cache_read_input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.cache_read_input_tokens')) VIRTUAL"
25005
- },
25006
- {
25007
- name: "model",
25008
- ddl: "ALTER TABLE audit_events ADD COLUMN model text GENERATED ALWAYS AS (json_extract(attributes, '$.model')) VIRTUAL"
25009
- },
25010
- {
25556
+ stampAll(ids, value, failure, failedAtMs) {
25557
+ if (ids.length === 0) return;
25558
+ const failedAt = failure === null ? null : failedAtMs ?? null;
25559
+ withTransaction(
25560
+ this.db,
25561
+ () => {
25562
+ for (const id of ids) this.stampStmt.run({ at: value, failedAt, failure, id });
25563
+ },
25564
+ "IMMEDIATE"
25565
+ );
25566
+ }
25567
+ /**
25568
+ * Claim rows as in-flight.
25569
+ *
25570
+ * Advisory in exactly the sense the lease is: it records that a send is in
25571
+ * progress so a surface can say so, and a lost claim costs a row showing as
25572
+ * queued while it is actually being sent. It is not exclusion — the far side
25573
+ * settles a duplicate on the row id.
25574
+ */
25575
+ claimRows(ids, atMs) {
25576
+ this.eachInTransaction(ids, (id) => this.claimRowStmt.run({ at: atMs, id }));
25577
+ }
25578
+ /** Give back a claim without settling — the send failed, the row is queued again. */
25579
+ releaseRows(ids) {
25580
+ this.eachInTransaction(ids, (id) => this.releaseRowStmt.run({ id }));
25581
+ }
25582
+ /**
25583
+ * Clear claims older than `staleBefore`, and report how many were cleared.
25584
+ *
25585
+ * A process killed between claiming and settling leaves rows claimed with
25586
+ * nothing left to settle them. Without this they read as "sending" for ever.
25587
+ */
25588
+ releaseStaleClaims(staleBefore) {
25589
+ return Number(this.releaseStaleClaimsStmt.run({ staleBefore }).changes);
25590
+ }
25591
+ /**
25592
+ * Every tracked row in exactly one delivery state.
25593
+ *
25594
+ * Takes no boundary on purpose. The boundary answers "what should the drain
25595
+ * pick up now", which is a different question from "what state is this row
25596
+ * in" — and a machine that has never attached has no boundary to pass, so
25597
+ * requiring one would force a caller to invent one and report the whole store
25598
+ * as queued.
25599
+ */
25600
+ /**
25601
+ * The same partition, one row per kind that a lane carries.
25602
+ *
25603
+ * A kind with nothing to report is ABSENT rather than a row of zeros: the
25604
+ * scope decides which rows exist at all, so a kind that has never been
25605
+ * recorded — or whose captures nobody ever owed — produces no group. A caller
25606
+ * rendering a fixed list of kinds must therefore treat a missing one as "no
25607
+ * rows", never as "zero sent"; the two look identical in a bar and mean
25608
+ * different things.
25609
+ */
25610
+ partitionByKind() {
25611
+ return allRows(
25612
+ this.partitionByKindStmt,
25613
+ {}
25614
+ ).map((row) => ({
25615
+ kind: row.kind,
25616
+ queued: row.queued ?? 0,
25617
+ inProgress: row.inProgress ?? 0,
25618
+ synced: row.synced ?? 0,
25619
+ failed: row.failed ?? 0,
25620
+ refused: row.refused ?? 0,
25621
+ detached: row.detached ?? 0,
25622
+ total: row.total ?? 0
25623
+ }));
25624
+ }
25625
+ partition() {
25626
+ const row = getRow(this.partitionStmt, {});
25627
+ return {
25628
+ queued: row?.queued ?? 0,
25629
+ inProgress: row?.inProgress ?? 0,
25630
+ synced: row?.synced ?? 0,
25631
+ failed: row?.failed ?? 0,
25632
+ refused: row?.refused ?? 0,
25633
+ detached: row?.detached ?? 0,
25634
+ total: row?.total ?? 0
25635
+ };
25636
+ }
25637
+ /** `pending` counts only what is inside the backlog; sent and skipped are totals. */
25638
+ counts(before) {
25639
+ const row = getRow(this.countsStmt, { before });
25640
+ const captures = getRow(this.captureSkipCountStmt);
25641
+ return {
25642
+ pending: row?.pending ?? 0,
25643
+ sent: row?.sent ?? 0,
25644
+ skipped: row?.skipped ?? 0,
25645
+ refused: row?.refused ?? 0,
25646
+ detached: row?.detached ?? 0,
25647
+ capturesSkipped: captures?.skipped ?? 0
25648
+ };
25649
+ }
25650
+ /**
25651
+ * The deployment the current stamps were made against, and where its backlog
25652
+ * ends.
25653
+ *
25654
+ * READ-ONLY. An absent row reads as an absent deployment, which is what a
25655
+ * machine that has never drained is — and every writer below seeds the row
25656
+ * before it needs one, so nothing depends on this creating it. Keeping the
25657
+ * write off the gate path matters because the gate runs on every pass while a
25658
+ * write has to take the database's write lock.
25659
+ */
25660
+ deployment() {
25661
+ const row = getRow(
25662
+ this.fingerprintStmt
25663
+ );
25664
+ return {
25665
+ fingerprint: row?.fingerprint ?? void 0,
25666
+ backlogBefore: row?.backlogBefore ?? void 0
25667
+ };
25668
+ }
25669
+ /**
25670
+ * Point the ledger at a different deployment, discarding what it recorded
25671
+ * about the previous one.
25672
+ *
25673
+ * Delivery is a fact about ONE recipient: rows sent to the deployment a
25674
+ * machine has just left are undelivered as far as the new one is concerned.
25675
+ * All four in one transaction, so a crash between them cannot leave stamps
25676
+ * attributed to the wrong deployment, a boundary that belongs to another, or
25677
+ * a disown with no re-mark to follow it.
25678
+ *
25679
+ * The boundary is written HERE and only here, which is what freezes it: a
25680
+ * re-attach to the SAME deployment (a key rotation) leaves the fingerprint
25681
+ * unchanged, so this never runs and the backlog does not widen back over rows
25682
+ * the live path has since delivered.
25683
+ *
25684
+ * `backfillCapturesBefore` is the caller's OWN "now" at the instant a human
25685
+ * granted existing-history consent for the deployment this call is arming —
25686
+ * a DIFFERENT instant from `backlogBefore`: the re-mark boundary is the GRANT
25687
+ * instant, `backlogBefore` is the ATTACH instant, and the two can be far
25688
+ * apart. Passed only when that grant is valid, since this method has no way
25689
+ * to check consent itself and must not mark a row owed for a machine that
25690
+ * never agreed to it. Applied AFTER the disown above, in the SAME
25691
+ * transaction: what the disown clears is every marker below `backlogBefore`,
25692
+ * which includes this deployment's OWN pre-attach rows — `aka attach` calls
25693
+ * `seedCaptureBacklogOwed` at the attach instant, so every row it marks sits
25694
+ * on the cleared side of that bound — and the re-mark in the same
25695
+ * transaction is what puts those rows back. A crash between the two cannot
25696
+ * strand the ledger disowned with nothing re-marked — the transaction either
25697
+ * lands whole or not at all, and a fingerprint mismatch that has not yet
25698
+ * committed re-enters this method on the very next pass. Omit it (the
25699
+ * structural-only tests do) to exercise the disown in isolation.
25700
+ *
25701
+ * The disown is bounded by `backlogBefore`, which is what keeps it from
25702
+ * touching a marker the NEW deployment's OWN live path has already set: B's
25703
+ * live path can mark a capture owed from the moment `aka attach` writes the
25704
+ * descriptor, before the drain's first pass ever reaches this method, and
25705
+ * such a row sits at or after the bound rather than below it. What keeps the
25706
+ * disown from eating THIS SAME CALL's own re-mark is the order, not the
25707
+ * bound — disown runs first, re-mark second, both inside the one
25708
+ * transaction above.
25709
+ */
25710
+ rearmFor(fingerprint, backlogBefore, backfillCapturesBefore) {
25711
+ this.ensureRowStmt.run();
25712
+ withTransaction(
25713
+ this.db,
25714
+ () => {
25715
+ const previous = getRow(this.fingerprintStmt)?.fingerprint;
25716
+ this.rearmStmt.run();
25717
+ if (previous !== null && previous !== void 0 && previous !== fingerprint) {
25718
+ this.disownCapturesStmt.run({ attachedAt: backlogBefore });
25719
+ }
25720
+ if (backfillCapturesBefore !== void 0) {
25721
+ this.markCaptureBacklogOwedStmt.run({ before: backfillCapturesBefore });
25722
+ }
25723
+ this.setFingerprintStmt.run({ fingerprint, backlogBefore });
25724
+ },
25725
+ "IMMEDIATE"
25726
+ );
25727
+ }
25728
+ /**
25729
+ * End the attached period: hand its rows to the live path, and release the
25730
+ * boundary so the next attachment can freeze a new one.
25731
+ *
25732
+ * WITHOUT THIS, a detach and a re-attach to the same deployment leave a window
25733
+ * nothing delivers. The fingerprint is unchanged, so the boundary is never
25734
+ * re-frozen and stays at the FIRST attachment — while nothing forwards at all
25735
+ * during the detached period, because the machine is not attached. Rows
25736
+ * recorded in that window sit after the boundary and before the re-attach, so
25737
+ * neither path takes them, and the pending count reports none outstanding.
25738
+ *
25739
+ * WHAT IT RECORDS, and what it deliberately does not. These rows were the
25740
+ * closing attachment's to deliver and are no longer outstanding — that is what
25741
+ * lets the boundary move. It is NOT a claim that any of them arrived, and the
25742
+ * distinction is not academic: this used to write a delivery TIME, which every
25743
+ * read treats as delivery, so one detach turned a window of undelivered rows
25744
+ * into a window of delivered ones and no surface could tell. It writes the
25745
+ * skip sentinel and a reason of its own instead, so "no longer owed" and
25746
+ * "received" stop being the same fact.
25747
+ *
25748
+ * A change of deployment still frees them (see the re-arm), because the next
25749
+ * deployment has seen none of this machine's history — so the rows reach it
25750
+ * exactly as they did when this wrote a delivery time.
25751
+ *
25752
+ * ONE TRANSACTION, so a crash cannot release the boundary while leaving the
25753
+ * window unstamped — that half-state would re-send the whole attached period
25754
+ * on the next attach, which is the failure the boundary exists to prevent.
25755
+ */
25756
+ closeAttachedWindow(attachedAtMs, atMs) {
25757
+ this.ensureRowStmt.run();
25758
+ withTransaction(
25759
+ this.db,
25760
+ () => {
25761
+ const row = getRow(this.fingerprintStmt);
25762
+ const from = row?.backlogBefore ?? attachedAtMs;
25763
+ this.closeWindowStmt.run({ at: atMs, attachedAt: from });
25764
+ this.releaseBoundaryStmt.run();
25765
+ },
25766
+ "IMMEDIATE"
25767
+ );
25768
+ }
25769
+ /**
25770
+ * Freeze a boundary for the deployment already on file, KEEPING the stamps.
25771
+ *
25772
+ * The re-attach half of the above. Distinct from `rearmFor`, which is for a
25773
+ * different deployment and therefore discards what was delivered to the old
25774
+ * one: here the recipient is the same, so everything already sent to it stays
25775
+ * sent.
25776
+ */
25777
+ freezeBoundary(backlogBefore) {
25778
+ this.ensureRowStmt.run();
25779
+ this.freezeBoundaryStmt.run({ backlogBefore });
25780
+ }
25781
+ /** Take the claim, or report that someone live already holds it. */
25782
+ claim(pid, host, nowMs, staleAfterMs) {
25783
+ this.ensureRowStmt.run();
25784
+ let taken = false;
25785
+ withTransaction(
25786
+ this.db,
25787
+ () => {
25788
+ const result = this.claimStmt.run({
25789
+ pid,
25790
+ host,
25791
+ now: nowMs,
25792
+ staleBefore: nowMs - staleAfterMs
25793
+ });
25794
+ taken = result.changes === 1;
25795
+ },
25796
+ "IMMEDIATE"
25797
+ );
25798
+ return taken;
25799
+ }
25800
+ /** Say the holder is still alive. A no-op once the claim has moved on. */
25801
+ heartbeat(pid, nowMs) {
25802
+ this.heartbeatStmt.run({ now: nowMs, pid });
25803
+ }
25804
+ /** Give the claim up. Scoped to this holder, so a taken-over claim is left be. */
25805
+ release(pid) {
25806
+ this.releaseStmt.run({ pid });
25807
+ }
25808
+ /** Who holds the claim, if anyone. Read-only, for the same reason as above. */
25809
+ lease() {
25810
+ return getRow(this.leaseStmt);
25811
+ }
25812
+ };
25813
+
25814
+ // ../../packages/persistence/src/migrations.ts
25815
+ function describeObject(object2) {
25816
+ return object2.kind === "column" ? `column ${object2.table}.${object2.name}` : `table ${object2.name}`;
25817
+ }
25818
+ function splitStatements(sql) {
25819
+ return sql.split(/-->\s*statement-breakpoint/).map((s) => s.trim()).filter((s) => s.length > 0);
25820
+ }
25821
+ function createdIndexName(statement) {
25822
+ const body = statement.replace(/^(?:\s*--[^\n]*\n?)+/, "").trimStart();
25823
+ return /^CREATE (?:UNIQUE )?INDEX (?:IF NOT EXISTS )?`([^`]+)`/.exec(body)?.[1];
25824
+ }
25825
+ var LEGACY_DROP_MIGRATION_TAG = "0014_drop_legacy_events_findings";
25826
+ function applyMigrations(db, file2, options = {}) {
25827
+ const legacyCount = db.prepare("PRAGMA user_version").get().user_version;
25828
+ db.exec(
25829
+ "CREATE TABLE IF NOT EXISTS migration_ledger (tag TEXT PRIMARY KEY, applied_at INTEGER NOT NULL)"
25830
+ );
25831
+ const applied = new Set(
25832
+ db.prepare("SELECT tag FROM migration_ledger").all().map((r) => r.tag)
25833
+ );
25834
+ const preLedgerStore = applied.size === 0 && legacyCount > 0;
25835
+ const record2 = db.prepare(
25836
+ "INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)"
25837
+ );
25838
+ for (const [index, migration] of SQLITE_MIGRATIONS.entries()) {
25839
+ if (applied.has(migration.tag)) continue;
25840
+ if (options.skipTags?.has(migration.tag) === true) continue;
25841
+ if (migration.tag === LEGACY_DROP_MIGRATION_TAG) continue;
25842
+ const evidence = evidenceObjects(migration.sql);
25843
+ const present = evidence.filter((o) => evidenceExists(db, o));
25844
+ if (present.length > 0 && present.length < evidence.length) {
25845
+ const missing = evidence.filter((o) => !present.includes(o));
25846
+ 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.`;
25847
+ akaWarn(message);
25848
+ throw new Error(`[aka] ${message}`);
25849
+ }
25850
+ const alreadyApplied = evidence.length > 0 ? present.length === evidence.length : preLedgerStore && index < legacyCount;
25851
+ const wantsFkOff = /PRAGMA foreign_keys\s*=\s*OFF/i.test(migration.sql);
25852
+ const statements = splitStatements(migration.sql);
25853
+ if (wantsFkOff) db.exec("PRAGMA foreign_keys = OFF");
25854
+ try {
25855
+ withTransaction(
25856
+ db,
25857
+ () => {
25858
+ for (const statement of statements) {
25859
+ const indexName = createdIndexName(statement);
25860
+ if (indexName === void 0) {
25861
+ if (alreadyApplied) continue;
25862
+ } else if (indexExists(db, indexName)) {
25863
+ continue;
25864
+ }
25865
+ db.exec(statement);
25866
+ }
25867
+ if (wantsFkOff && !alreadyApplied) {
25868
+ const violations = db.prepare("PRAGMA foreign_key_check").all();
25869
+ if (violations.length > 0) {
25870
+ throw new Error(
25871
+ `[aka] sqlite migration ${migration.tag} left ${String(violations.length)} foreign-key violation(s); rolling back.`
25872
+ );
25873
+ }
25874
+ }
25875
+ record2.run(migration.tag, Date.now());
25876
+ },
25877
+ "IMMEDIATE"
25878
+ );
25879
+ } finally {
25880
+ if (wantsFkOff) db.exec("PRAGMA foreign_keys = ON");
25881
+ }
25882
+ }
25883
+ if (legacyCount < SQLITE_MIGRATIONS.length) {
25884
+ db.exec(`PRAGMA user_version = ${String(SQLITE_MIGRATIONS.length)}`);
25885
+ }
25886
+ ensureSyncedAtColumn(db, "audit_events");
25887
+ ensureScanLedgerTable(db);
25888
+ ensureHistorySyncTable(db);
25889
+ ensureBlockedDetectionsTable(db);
25890
+ ensureRuleProbeCacheTable(db);
25891
+ ensureWriteGateTrigger(db);
25892
+ ensureTokenUsageColumns(db);
25893
+ reconcileSourceProjectIds(db);
25894
+ if (!applied.has(LEGACY_DROP_MIGRATION_TAG)) {
25895
+ const drained = runLegacyHistoryBackfill(db);
25896
+ if (drained) applyLegacyDropMigration(db, file2);
25897
+ }
25898
+ }
25899
+ function readLegacyTables(db) {
25900
+ let holdsRows = false;
25901
+ const marks = [];
25902
+ for (const table of ["events", "findings"]) {
25903
+ try {
25904
+ const row = db.prepare(`SELECT count(*) AS n, ifnull(max(rowid), -1) AS hi FROM ${table}`).get();
25905
+ if (row === void 0) {
25906
+ holdsRows = true;
25907
+ marks.push(`${table}:unreadable`);
25908
+ continue;
25909
+ }
25910
+ if (row.n > 0) holdsRows = true;
25911
+ marks.push(`${table}:${String(row.n)}:${String(row.hi)}`);
25912
+ } catch {
25913
+ holdsRows = true;
25914
+ marks.push(`${table}:unreadable`);
25915
+ }
25916
+ }
25917
+ return { holdsRows, mark: marks.join("|") };
25918
+ }
25919
+ function applyLegacyDropMigration(db, file2) {
25920
+ const migration = SQLITE_MIGRATIONS.find((m) => m.tag === LEGACY_DROP_MIGRATION_TAG);
25921
+ if (!migration) return;
25922
+ const before = file2 === void 0 ? void 0 : readLegacyTables(db);
25923
+ if (file2 !== void 0 && before?.holdsRows === true) {
25924
+ try {
25925
+ backupBeforeLegacyDrop(db, file2);
25926
+ } catch (error61) {
25927
+ akaWarn(`legacy events/findings backup failed; deferring the drop: ${String(error61)}`);
25928
+ return;
25929
+ }
25930
+ }
25931
+ try {
25932
+ withTransaction(
25933
+ db,
25934
+ () => {
25935
+ const alreadyDropped = db.prepare("SELECT 1 FROM migration_ledger WHERE tag = ?").get(migration.tag);
25936
+ if (alreadyDropped) return;
25937
+ if (before !== void 0 && readLegacyTables(db).mark !== before.mark) {
25938
+ akaWarn(
25939
+ "legacy events/findings rows changed after the pre-drop snapshot decision; deferring the drop so the next open can copy them first."
25940
+ );
25941
+ return;
25942
+ }
25943
+ for (const statement of splitStatements(migration.sql)) {
25944
+ db.exec(statement);
25945
+ }
25946
+ db.prepare("INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)").run(
25947
+ migration.tag,
25948
+ Date.now()
25949
+ );
25950
+ },
25951
+ "IMMEDIATE"
25952
+ );
25953
+ } catch (error61) {
25954
+ akaWarn(`legacy events/findings drop failed; deferring: ${String(error61)}`);
25955
+ }
25956
+ }
25957
+ function backupBeforeLegacyDrop(db, file2) {
25958
+ reapStalePartials(file2);
25959
+ const backup = backupPath(file2, "pre-drop");
25960
+ snapshotStore(db, backup);
25961
+ return backup;
25962
+ }
25963
+ var TOKEN_USAGE_COLUMNS = [
25964
+ {
25965
+ name: "input_tokens",
25966
+ ddl: "ALTER TABLE audit_events ADD COLUMN input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.input_tokens')) VIRTUAL"
25967
+ },
25968
+ {
25969
+ name: "output_tokens",
25970
+ ddl: "ALTER TABLE audit_events ADD COLUMN output_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.output_tokens')) VIRTUAL"
25971
+ },
25972
+ {
25973
+ name: "cache_creation_input_tokens",
25974
+ ddl: "ALTER TABLE audit_events ADD COLUMN cache_creation_input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.cache_creation_input_tokens')) VIRTUAL"
25975
+ },
25976
+ {
25977
+ name: "cache_read_input_tokens",
25978
+ ddl: "ALTER TABLE audit_events ADD COLUMN cache_read_input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.cache_read_input_tokens')) VIRTUAL"
25979
+ },
25980
+ {
25981
+ name: "model",
25982
+ ddl: "ALTER TABLE audit_events ADD COLUMN model text GENERATED ALWAYS AS (json_extract(attributes, '$.model')) VIRTUAL"
25983
+ },
25984
+ {
25011
25985
  name: "provider",
25012
25986
  ddl: "ALTER TABLE audit_events ADD COLUMN provider text GENERATED ALWAYS AS (json_extract(attributes, '$.provider')) VIRTUAL"
25013
25987
  }
@@ -25270,10 +26244,62 @@ function ensureSyncedAtColumn(db, table) {
25270
26244
  if (!columns.includes("outbox_owed")) {
25271
26245
  db.exec(`ALTER TABLE ${table} ADD COLUMN outbox_owed integer`);
25272
26246
  }
26247
+ if (!columns.includes("sync_failed_at")) {
26248
+ db.exec(`ALTER TABLE ${table} ADD COLUMN sync_failed_at integer`);
26249
+ }
26250
+ if (!columns.includes("sync_failure")) {
26251
+ withTransaction(
26252
+ db,
26253
+ () => {
26254
+ db.exec(`ALTER TABLE ${table} ADD COLUMN sync_failure text`);
26255
+ db.exec(
26256
+ `UPDATE ${table} SET synced_at = NULL
26257
+ WHERE synced_at = -1
26258
+ AND event_type IN (${COUNTED_EVENT_TYPES.map((t) => `'${t}'`).join(", ")})`
26259
+ );
26260
+ },
26261
+ "IMMEDIATE"
26262
+ );
26263
+ }
25273
26264
  db.exec(
25274
- `CREATE INDEX IF NOT EXISTS idx_audit_events_sync
25275
- ON audit_events (event_type, synced_at, sync_claimed_at, started_at)`
26265
+ `CREATE TRIGGER IF NOT EXISTS aka_sync_failure_guard
26266
+ BEFORE UPDATE OF sync_failure ON ${table}
26267
+ WHEN ${syncFailureRejectCondition()}
26268
+ BEGIN SELECT RAISE(ABORT, 'sync_failure is not one of the recorded reasons'); END`
25276
26269
  );
26270
+ const syncIndexColumns = [
26271
+ "event_type",
26272
+ "synced_at",
26273
+ "sync_claimed_at",
26274
+ "started_at",
26275
+ // Appended LAST on purpose. The delivery-state read now projects it, so it
26276
+ // has to be in the index for the read to stay covered — but putting it
26277
+ // ahead of `started_at` would reorder the prefix the structural drain's
26278
+ // reads match on.
26279
+ "sync_failure"
26280
+ // `outbox_owed` is DELIBERATELY ABSENT, and it was measured both ways.
26281
+ //
26282
+ // The delivery-state read tests it — a capture's state depends on whether a
26283
+ // live forward marked it owed — so carrying it here makes that read covering
26284
+ // rather than a row fetch per row: 16 ms against 40 ms on a real 6 GB store.
26285
+ // But a sixth column changes what the planner charges for this index, and
26286
+ // with no ANALYZE statistics it plans from schema shape alone: measured, it
26287
+ // then stops choosing the per-session index for the token rollup and walks
26288
+ // every `llm_call` in the store through the event-type index instead. That
26289
+ // read grows with the store; this one does not.
26290
+ //
26291
+ // 40 ms on the largest store measured, once per render, is a cost worth
26292
+ // paying to leave every other read's plan where it was.
26293
+ ];
26294
+ const currentSyncIndex = indexColumns(db, "idx_audit_events_sync");
26295
+ const syncIndexMatches = currentSyncIndex.length === syncIndexColumns.length && currentSyncIndex.every((column, i) => column === syncIndexColumns[i]);
26296
+ if (!syncIndexMatches) {
26297
+ db.exec("DROP INDEX IF EXISTS idx_audit_events_sync");
26298
+ db.exec(
26299
+ `CREATE INDEX idx_audit_events_sync
26300
+ ON audit_events (${syncIndexColumns.join(", ")})`
26301
+ );
26302
+ }
25277
26303
  db.exec(
25278
26304
  `CREATE INDEX IF NOT EXISTS idx_audit_outbox_owed
25279
26305
  ON audit_events (event_type, synced_at, sync_claimed_at, started_at) WHERE outbox_owed = 1`
@@ -25495,7 +26521,11 @@ function buildAuditEvent(row) {
25495
26521
  link: linkParsed?.success ? linkParsed.data : null,
25496
26522
  targetId: row.target_id,
25497
26523
  internal: intToBool(row.internal),
25498
- flagged: intToBool(row.flagged)
26524
+ flagged: intToBool(row.flagged),
26525
+ // Only meaningful when the title came out empty — a row whose body was
26526
+ // expired but whose title fell back to `tool_name` still has something to
26527
+ // render, and flagging it would make the view apologise for nothing.
26528
+ bodyExpired: row.content_expired_at !== null && (row.title ?? "") === ""
25499
26529
  };
25500
26530
  }
25501
26531
  var TIMELINE_COLUMNS = `
@@ -25503,6 +26533,7 @@ var TIMELINE_COLUMNS = `
25503
26533
  event_type,
25504
26534
  started_at,
25505
26535
  coalesce(content, json_extract(attributes, '$.tool_name')) AS title,
26536
+ content_expired_at,
25506
26537
  coalesce(json_extract(attributes, '$.detail'), json_extract(attributes, '$.target')) AS detail,
25507
26538
  coalesce(json_extract(attributes, '$.tool_name'), json_extract(attributes, '$.tool')) AS tool,
25508
26539
  json_extract(attributes, '$.severity') AS severity,
@@ -26168,6 +27199,88 @@ var SqliteAuditEventsRepository = class {
26168
27199
  }
26169
27200
  };
26170
27201
 
27202
+ // ../../packages/persistence/src/repositories/body-retention.ts
27203
+ var DEFAULT_BATCH_SIZE = 500;
27204
+ var DEFAULT_MAX_ROWS = 5e4;
27205
+ var SYNC_LANE_TYPES_SQL = OUTBOX_CAPTURE_TYPE_LIST;
27206
+ var SqliteBodyRetentionRepository = class {
27207
+ constructor(db) {
27208
+ this.db = db;
27209
+ const select = (laneClause) => `
27210
+ SELECT id, LENGTH(CAST(content AS BLOB)) AS bytes
27211
+ FROM audit_events
27212
+ WHERE content IS NOT NULL
27213
+ AND started_at < :cutoff
27214
+ AND event_type IN (${CAPTURE_EVENT_TYPES_SQL})
27215
+ ${laneClause}
27216
+ ORDER BY started_at
27217
+ LIMIT :limit`;
27218
+ this.candidatesStmt = this.db.prepare(select(""));
27219
+ this.candidatesSyncSafeStmt = this.db.prepare(
27220
+ select(`AND (event_type NOT IN (${SYNC_LANE_TYPES_SQL}) OR synced_at IS NOT NULL)`)
27221
+ );
27222
+ this.heldBySyncStmt = this.db.prepare(`
27223
+ SELECT COUNT(*) AS n
27224
+ FROM audit_events
27225
+ WHERE content IS NOT NULL
27226
+ AND started_at < :cutoff
27227
+ AND event_type IN (${SYNC_LANE_TYPES_SQL})
27228
+ AND synced_at IS NULL`);
27229
+ this.expireStmt = this.db.prepare(
27230
+ `UPDATE audit_events SET content = NULL, content_expired_at = :now WHERE id = :id`
27231
+ );
27232
+ }
27233
+ db;
27234
+ candidatesStmt;
27235
+ candidatesSyncSafeStmt;
27236
+ heldBySyncStmt;
27237
+ expireStmt;
27238
+ /** How many bytes a pass with these options would free, changing nothing. */
27239
+ preview(opts) {
27240
+ const limit = opts.maxRows ?? DEFAULT_MAX_ROWS;
27241
+ const stmt = opts.sweepSyncLane ? this.candidatesStmt : this.candidatesSyncSafeStmt;
27242
+ const rows = stmt.all({ cutoff: opts.cutoff, limit });
27243
+ return {
27244
+ rowsExpired: rows.length,
27245
+ bytesFreed: rows.reduce((sum, r) => sum + r.bytes, 0),
27246
+ rowsHeldBySync: this.countHeldBySync(opts)
27247
+ };
27248
+ }
27249
+ /** Clear eligible bodies, in bounded batches. */
27250
+ expire(opts) {
27251
+ const batchSize = opts.batchSize ?? DEFAULT_BATCH_SIZE;
27252
+ const maxRows = opts.maxRows ?? DEFAULT_MAX_ROWS;
27253
+ const stmt = opts.sweepSyncLane ? this.candidatesStmt : this.candidatesSyncSafeStmt;
27254
+ let rowsExpired = 0;
27255
+ let bytesFreed = 0;
27256
+ let done = true;
27257
+ while (rowsExpired < maxRows) {
27258
+ const remaining = Math.min(batchSize, maxRows - rowsExpired);
27259
+ const batch = stmt.all({ cutoff: opts.cutoff, limit: remaining });
27260
+ if (batch.length === 0) break;
27261
+ withTransaction(
27262
+ this.db,
27263
+ () => {
27264
+ for (const row of batch) this.expireStmt.run({ id: row.id, now: opts.now });
27265
+ },
27266
+ "IMMEDIATE"
27267
+ );
27268
+ rowsExpired += batch.length;
27269
+ bytesFreed += batch.reduce((sum, r) => sum + r.bytes, 0);
27270
+ if (batch.length < remaining) break;
27271
+ if (rowsExpired >= maxRows) {
27272
+ done = stmt.all({ cutoff: opts.cutoff, limit: 1 }).length === 0;
27273
+ }
27274
+ }
27275
+ return { rowsExpired, bytesFreed, rowsHeldBySync: this.countHeldBySync(opts), done };
27276
+ }
27277
+ countHeldBySync(opts) {
27278
+ if (opts.sweepSyncLane) return 0;
27279
+ const row = this.heldBySyncStmt.get({ cutoff: opts.cutoff });
27280
+ return row.n;
27281
+ }
27282
+ };
27283
+
26171
27284
  // ../../packages/persistence/src/repositories/classified-data.ts
26172
27285
  var SqliteClassifiedDataRepository = class {
26173
27286
  constructor(db) {
@@ -26996,7 +28109,15 @@ function toFlatFindingRow(r) {
26996
28109
  ...r.tool_name === null ? {} : { toolName: r.tool_name },
26997
28110
  eventId: r.event_id,
26998
28111
  ...r.session_id === null ? {} : { sessionId: r.session_id },
26999
- status: deriveInstanceStatus(r)
28112
+ status: deriveInstanceStatus(r),
28113
+ delivery: deriveFindingDelivery({
28114
+ kind: r.kind,
28115
+ syncedAt: r.synced_at,
28116
+ syncClaimedAt: r.sync_claimed_at,
28117
+ syncFailedAt: r.sync_failed_at,
28118
+ syncFailure: r.sync_failure,
28119
+ outboxOwed: r.outbox_owed
28120
+ })
27000
28121
  };
27001
28122
  }
27002
28123
  function encodeGroupCursor(group) {
@@ -27060,7 +28181,10 @@ var FINDING_ROW_COLUMNS_SQL = `f.id AS id, d.rule_id AS rule_id, d.category AS c
27060
28181
  e.tool_name AS tool_name,
27061
28182
  f.audit_event_id AS event_id, e.root_session_id AS session_id,
27062
28183
  e.event_type AS kind, f.finding_key AS finding_key,
27063
- ${latestResolutionStatusSql("f")} AS latest_status`;
28184
+ ${latestResolutionStatusSql("f")} AS latest_status,
28185
+ e.synced_at AS synced_at, e.sync_claimed_at AS sync_claimed_at,
28186
+ e.sync_failed_at AS sync_failed_at, e.sync_failure AS sync_failure,
28187
+ e.outbox_owed AS outbox_owed`;
27064
28188
  var DAY_MS3 = 864e5;
27065
28189
  var SqliteFindingsRepository = class {
27066
28190
  constructor(db) {
@@ -27305,6 +28429,7 @@ var SqliteFindingsRepository = class {
27305
28429
  providers: query.provider,
27306
28430
  actions: query.action,
27307
28431
  statuses: query.status,
28432
+ deliveries: query.deployment,
27308
28433
  tools: query.tool,
27309
28434
  repo: query.repo,
27310
28435
  file: query.file,
@@ -27372,6 +28497,7 @@ var SqliteFindingsRepository = class {
27372
28497
  providers: query.provider,
27373
28498
  actions: query.action,
27374
28499
  statuses: query.status,
28500
+ deliveries: query.deployment,
27375
28501
  tools: query.tool,
27376
28502
  q: query.q
27377
28503
  };
@@ -27635,7 +28761,9 @@ var SqliteFindingsRepository = class {
27635
28761
  )
27636
28762
  );
27637
28763
  for (const row of grouped) {
27638
- if (row.action_taken in byAction) byAction[row.action_taken] = row.c;
28764
+ if (Object.hasOwn(byAction, row.action_taken)) {
28765
+ byAction[row.action_taken] = row.c;
28766
+ }
27639
28767
  }
27640
28768
  const bySeverity = { critical: 0, high: 0, medium: 0, low: 0 };
27641
28769
  const sevRows = allRows(
@@ -27652,7 +28780,9 @@ var SqliteFindingsRepository = class {
27652
28780
  )
27653
28781
  );
27654
28782
  for (const row of sevRows) {
27655
- if (row.severity in bySeverity) bySeverity[row.severity] = row.c;
28783
+ if (Object.hasOwn(bySeverity, row.severity)) {
28784
+ bySeverity[row.severity] = row.c;
28785
+ }
27656
28786
  }
27657
28787
  const categories = ENFORCEABLE_CATEGORIES;
27658
28788
  const enabledRows = allRows(
@@ -27701,525 +28831,6 @@ function isoDay(ms) {
27701
28831
  return new Date(ms).toISOString().slice(0, 10);
27702
28832
  }
27703
28833
 
27704
- // ../../packages/persistence/src/repositories/history-sync.ts
27705
- var STRUCTURAL_EVENT_TYPES = ["session", "llm_call", "tool_call"];
27706
- var TYPE_LIST = STRUCTURAL_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
27707
- var OUTBOX_CAPTURE_EVENT_TYPES = ["prompt", "response", "tool_use"];
27708
- var CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
27709
- var SKIPPED = -1;
27710
- var ROW_COLUMNS = `id,
27711
- parent_id AS parentId,
27712
- root_session_id AS rootSessionId,
27713
- event_type AS eventType,
27714
- host_id AS hostId,
27715
- harness_id AS harnessId,
27716
- source_project_id AS sourceProjectId,
27717
- started_at AS startedAt,
27718
- ended_at AS endedAt,
27719
- severity,
27720
- priority,
27721
- content,
27722
- content_hash AS contentHash,
27723
- attributes`;
27724
- var SqliteHistorySyncRepository = class {
27725
- constructor(db) {
27726
- this.db = db;
27727
- this.ensureRowStmt = db.prepare(`INSERT OR IGNORE INTO history_sync (id) VALUES (1)`);
27728
- this.sessionsStmt = db.prepare(
27729
- `SELECT COALESCE(root_session_id, id) AS sessionId, MIN(started_at) AS earliest
27730
- FROM audit_events
27731
- WHERE synced_at IS NULL
27732
- AND event_type IN (${TYPE_LIST})
27733
- AND started_at < :before
27734
- GROUP BY sessionId
27735
- ORDER BY earliest
27736
- LIMIT :limit`
27737
- );
27738
- this.rowsStmt = db.prepare(
27739
- `SELECT ${ROW_COLUMNS}
27740
- FROM audit_events
27741
- WHERE synced_at IS NULL
27742
- AND event_type IN (${TYPE_LIST})
27743
- AND started_at < :before
27744
- AND COALESCE(root_session_id, id) = :sessionId
27745
- ORDER BY (event_type = 'session') DESC, started_at
27746
- LIMIT :limit`
27747
- );
27748
- this.captureRowsStmt = db.prepare(
27749
- `SELECT ${ROW_COLUMNS}
27750
- FROM audit_events
27751
- WHERE synced_at IS NULL
27752
- AND sync_claimed_at IS NULL
27753
- AND outbox_owed = 1
27754
- AND event_type IN (${CAPTURE_TYPE_LIST})
27755
- AND started_at < :before
27756
- ORDER BY started_at
27757
- LIMIT :limit`
27758
- );
27759
- this.markOwedStmt = db.prepare(
27760
- `UPDATE audit_events SET outbox_owed = 1 WHERE id = :id AND synced_at IS NULL`
27761
- );
27762
- this.markCaptureBacklogOwedStmt = db.prepare(
27763
- `UPDATE audit_events SET outbox_owed = 1
27764
- WHERE synced_at IS NULL
27765
- AND event_type IN (${CAPTURE_TYPE_LIST})
27766
- AND started_at < :before`
27767
- );
27768
- this.stampStmt = db.prepare(
27769
- `UPDATE audit_events SET synced_at = :at, sync_claimed_at = NULL WHERE id = :id`
27770
- );
27771
- this.claimRowStmt = db.prepare(
27772
- `UPDATE audit_events SET sync_claimed_at = :at WHERE id = :id AND synced_at IS NULL`
27773
- );
27774
- this.releaseRowStmt = db.prepare(
27775
- `UPDATE audit_events SET sync_claimed_at = NULL WHERE id = :id`
27776
- );
27777
- this.releaseStaleClaimsStmt = db.prepare(
27778
- `UPDATE audit_events SET sync_claimed_at = NULL
27779
- WHERE sync_claimed_at IS NOT NULL AND sync_claimed_at < :staleBefore`
27780
- );
27781
- this.partitionStmt = db.prepare(
27782
- `SELECT
27783
- SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NULL THEN 1 ELSE 0 END) AS queued,
27784
- SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NOT NULL THEN 1 ELSE 0 END) AS inProgress,
27785
- SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS synced,
27786
- SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0 THEN 1 ELSE 0 END) AS failed,
27787
- COUNT(*) AS total
27788
- FROM audit_events
27789
- WHERE event_type IN (${TYPE_LIST})`
27790
- );
27791
- this.countsStmt = db.prepare(
27792
- `SELECT
27793
- SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
27794
- SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
27795
- SUM(CASE WHEN synced_at = ${String(SKIPPED)} THEN 1 ELSE 0 END) AS skipped
27796
- FROM audit_events
27797
- WHERE event_type IN (${TYPE_LIST})`
27798
- );
27799
- this.captureSkipCountStmt = db.prepare(
27800
- `SELECT COUNT(*) AS skipped
27801
- FROM audit_events
27802
- WHERE synced_at = ${String(SKIPPED)}
27803
- AND event_type IN (${CAPTURE_TYPE_LIST})`
27804
- );
27805
- this.fingerprintStmt = db.prepare(
27806
- `SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
27807
- FROM history_sync WHERE id = 1`
27808
- );
27809
- this.setFingerprintStmt = db.prepare(
27810
- `UPDATE history_sync
27811
- SET endpoint_fingerprint = :fingerprint, backlog_before = :backlogBefore
27812
- WHERE id = 1`
27813
- );
27814
- this.disownCapturesStmt = db.prepare(
27815
- `UPDATE audit_events SET outbox_owed = NULL
27816
- WHERE outbox_owed IS NOT NULL
27817
- AND event_type IN (${CAPTURE_TYPE_LIST})
27818
- AND started_at < :attachedAt`
27819
- );
27820
- this.rearmStmt = db.prepare(
27821
- `UPDATE audit_events SET synced_at = NULL
27822
- WHERE synced_at > 0 AND event_type IN (${TYPE_LIST})`
27823
- );
27824
- this.claimStmt = db.prepare(
27825
- `UPDATE history_sync
27826
- SET owner_pid = :pid, owner_host = :host, acquired_at = :now, heartbeat_at = :now
27827
- WHERE id = 1
27828
- AND (owner_pid IS NULL
27829
- OR heartbeat_at IS NULL
27830
- OR heartbeat_at < :staleBefore
27831
- OR heartbeat_at > :now)`
27832
- );
27833
- this.heartbeatStmt = db.prepare(
27834
- `UPDATE history_sync SET heartbeat_at = :now WHERE id = 1 AND owner_pid = :pid`
27835
- );
27836
- this.releaseStmt = db.prepare(
27837
- `UPDATE history_sync
27838
- SET owner_pid = NULL, owner_host = NULL, acquired_at = NULL, heartbeat_at = NULL
27839
- WHERE id = 1 AND owner_pid = :pid`
27840
- );
27841
- this.closeWindowStmt = db.prepare(
27842
- `UPDATE audit_events SET synced_at = :at
27843
- WHERE synced_at IS NULL
27844
- AND event_type IN (${TYPE_LIST})
27845
- AND started_at >= :attachedAt`
27846
- );
27847
- this.releaseBoundaryStmt = db.prepare(
27848
- `UPDATE history_sync SET backlog_before = NULL WHERE id = 1`
27849
- );
27850
- this.freezeBoundaryStmt = db.prepare(
27851
- `UPDATE history_sync SET backlog_before = :backlogBefore WHERE id = 1`
27852
- );
27853
- this.leaseStmt = db.prepare(
27854
- `SELECT owner_pid AS ownerPid, owner_host AS ownerHost,
27855
- acquired_at AS acquiredAt, heartbeat_at AS heartbeatAt
27856
- FROM history_sync WHERE id = 1`
27857
- );
27858
- this.inspectionsStmt = db.prepare(
27859
- `SELECT d.rule_id AS ruleId,
27860
- d.name AS ruleName,
27861
- d.version AS ruleVersion,
27862
- d.category AS category,
27863
- d.severity AS severity,
27864
- f.span_start AS spanStart,
27865
- f.span_end AS spanEnd,
27866
- f.masked_match AS maskedMatch,
27867
- f.action_taken AS actionTaken,
27868
- f.confidence AS confidence
27869
- FROM inspection_findings f
27870
- JOIN inspection_definitions d ON d.id = f.inspection_definition_id
27871
- WHERE f.audit_event_id = :auditEventId
27872
- ORDER BY f.span_start, f.id`
27873
- );
27874
- }
27875
- db;
27876
- ensureRowStmt;
27877
- sessionsStmt;
27878
- rowsStmt;
27879
- stampStmt;
27880
- countsStmt;
27881
- fingerprintStmt;
27882
- setFingerprintStmt;
27883
- rearmStmt;
27884
- claimStmt;
27885
- heartbeatStmt;
27886
- releaseStmt;
27887
- leaseStmt;
27888
- inspectionsStmt;
27889
- closeWindowStmt;
27890
- releaseBoundaryStmt;
27891
- freezeBoundaryStmt;
27892
- captureRowsStmt;
27893
- markOwedStmt;
27894
- markCaptureBacklogOwedStmt;
27895
- captureSkipCountStmt;
27896
- disownCapturesStmt;
27897
- partitionStmt;
27898
- claimRowStmt;
27899
- releaseRowStmt;
27900
- releaseStaleClaimsStmt;
27901
- /**
27902
- * The masked detections recorded against one tool call.
27903
- *
27904
- * These travel with the event because a tool call's target is not
27905
- * re-inspectable from the event alone — unlike a capture, where the text
27906
- * itself is re-scannable. What crosses is the masked match and the rule that
27907
- * produced it, never the value.
27908
- */
27909
- inspectionsFor(auditEventId) {
27910
- return allRows(this.inspectionsStmt, { auditEventId });
27911
- }
27912
- /**
27913
- * Sessions with structural rows still to send, oldest first.
27914
- *
27915
- * BOUNDED BY THE BACKLOG BOUNDARY, which is the whole correctness of this
27916
- * read. Anything recorded after the machine attached is the live forward
27917
- * path's to deliver; this drain exists for what was recorded before it, and a
27918
- * row both paths send is at best a duplicate request and at worst — for a
27919
- * session root — an overwrite of the inventory ids the live path resolved.
27920
- */
27921
- pendingSessions(limit, before) {
27922
- return allRows(this.sessionsStmt, { limit, before }).map(
27923
- (r) => r.sessionId
27924
- );
27925
- }
27926
- /** One session's undelivered structural rows within the backlog, root first. */
27927
- pendingRows(sessionId, limit, before) {
27928
- return allRows(this.rowsStmt, { sessionId, limit, before });
27929
- }
27930
- /**
27931
- * Captures this machine still owes the deployment, oldest first.
27932
- *
27933
- * Selected by the `outbox_owed` marker the attached forward path writes, not
27934
- * by a time window — see captureRowsStmt for why a window could not express
27935
- * this. `before` is the grace window that leaves a just-recorded capture to
27936
- * the live path.
27937
- */
27938
- pendingCaptureRows(limit, before) {
27939
- return allRows(this.captureRowsStmt, { limit, before });
27940
- }
27941
- /**
27942
- * Record that a capture is OWED to the deployment.
27943
- *
27944
- * Written by the attached forward path when a live send did not confirm
27945
- * delivery, and read by the drain as the whole of its eligibility test. It is
27946
- * a fact rather than an inference: the machine was attached, the send did not
27947
- * land, so the row is owed — which no time window can state, because the same
27948
- * window that holds the rows a past attachment left owed also holds every
27949
- * capture recorded while the machine was DETACHED, and those were never
27950
- * offered to anyone.
27951
- *
27952
- * Idempotent, and never un-set: `markSynced` settling the row is what takes it
27953
- * out of the drain's read.
27954
- */
27955
- markCaptureOwed(id) {
27956
- this.markOwedStmt.run({ id });
27957
- }
27958
- /**
27959
- * Mark every capture already on disk as owed, as of `before`.
27960
- *
27961
- * The consent-time backfill, called once from `aka attach` when a human
27962
- * grants existing-history consent — never from an ongoing drain pass, and
27963
- * never inferred from a boundary that could later move. `before` is the
27964
- * caller's own "now" at the moment consent was granted, so what this marks
27965
- * is exactly the backlog the consent prompt already counted, not whatever a
27966
- * later re-attach or key rotation might widen it to.
27967
- *
27968
- * Returns how many rows matched, for the caller to log or test against. Not a
27969
- * count of NEWLY marked rows — a row still unsynced from an earlier call
27970
- * matches again and is counted again, the same as `UPDATE`'s own `changes`.
27971
- */
27972
- markCaptureBacklogOwed(before) {
27973
- return Number(this.markCaptureBacklogOwedStmt.run({ before }).changes);
27974
- }
27975
- /** Record delivery. Called only AFTER the far side has accepted the rows. */
27976
- markSynced(ids, atMs) {
27977
- this.stampAll(ids, atMs);
27978
- }
27979
- /**
27980
- * Record that a row will never be sent.
27981
- *
27982
- * Reserved for a local defect — a row that cannot be rebuilt into a valid
27983
- * payload. A row that merely failed to reach the deployment stays NULL, so it
27984
- * is retried; marking those would turn one outage into permanent data loss.
27985
- */
27986
- markSkipped(ids) {
27987
- this.stampAll(ids, SKIPPED);
27988
- }
27989
- eachInTransaction(ids, run) {
27990
- if (ids.length === 0) return;
27991
- withTransaction(
27992
- this.db,
27993
- () => {
27994
- for (const id of ids) run(id);
27995
- },
27996
- "IMMEDIATE"
27997
- );
27998
- }
27999
- stampAll(ids, value) {
28000
- if (ids.length === 0) return;
28001
- withTransaction(
28002
- this.db,
28003
- () => {
28004
- for (const id of ids) this.stampStmt.run({ at: value, id });
28005
- },
28006
- "IMMEDIATE"
28007
- );
28008
- }
28009
- /**
28010
- * Claim rows as in-flight.
28011
- *
28012
- * Advisory in exactly the sense the lease is: it records that a send is in
28013
- * progress so a surface can say so, and a lost claim costs a row showing as
28014
- * queued while it is actually being sent. It is not exclusion — the far side
28015
- * settles a duplicate on the row id.
28016
- */
28017
- claimRows(ids, atMs) {
28018
- this.eachInTransaction(ids, (id) => this.claimRowStmt.run({ at: atMs, id }));
28019
- }
28020
- /** Give back a claim without settling — the send failed, the row is queued again. */
28021
- releaseRows(ids) {
28022
- this.eachInTransaction(ids, (id) => this.releaseRowStmt.run({ id }));
28023
- }
28024
- /**
28025
- * Clear claims older than `staleBefore`, and report how many were cleared.
28026
- *
28027
- * A process killed between claiming and settling leaves rows claimed with
28028
- * nothing left to settle them. Without this they read as "sending" for ever.
28029
- */
28030
- releaseStaleClaims(staleBefore) {
28031
- return Number(this.releaseStaleClaimsStmt.run({ staleBefore }).changes);
28032
- }
28033
- /**
28034
- * Every tracked row in exactly one delivery state.
28035
- *
28036
- * Takes no boundary on purpose. The boundary answers "what should the drain
28037
- * pick up now", which is a different question from "what state is this row
28038
- * in" — and a machine that has never attached has no boundary to pass, so
28039
- * requiring one would force a caller to invent one and report the whole store
28040
- * as queued.
28041
- */
28042
- partition() {
28043
- const row = getRow(this.partitionStmt, {});
28044
- return {
28045
- queued: row?.queued ?? 0,
28046
- inProgress: row?.inProgress ?? 0,
28047
- synced: row?.synced ?? 0,
28048
- failed: row?.failed ?? 0,
28049
- total: row?.total ?? 0
28050
- };
28051
- }
28052
- /** `pending` counts only what is inside the backlog; sent and skipped are totals. */
28053
- counts(before) {
28054
- const row = getRow(
28055
- this.countsStmt,
28056
- { before }
28057
- );
28058
- const captures = getRow(this.captureSkipCountStmt);
28059
- return {
28060
- pending: row?.pending ?? 0,
28061
- sent: row?.sent ?? 0,
28062
- skipped: row?.skipped ?? 0,
28063
- capturesSkipped: captures?.skipped ?? 0
28064
- };
28065
- }
28066
- /**
28067
- * The deployment the current stamps were made against, and where its backlog
28068
- * ends.
28069
- *
28070
- * READ-ONLY. An absent row reads as an absent deployment, which is what a
28071
- * machine that has never drained is — and every writer below seeds the row
28072
- * before it needs one, so nothing depends on this creating it. Keeping the
28073
- * write off the gate path matters because the gate runs on every pass while a
28074
- * write has to take the database's write lock.
28075
- */
28076
- deployment() {
28077
- const row = getRow(
28078
- this.fingerprintStmt
28079
- );
28080
- return {
28081
- fingerprint: row?.fingerprint ?? void 0,
28082
- backlogBefore: row?.backlogBefore ?? void 0
28083
- };
28084
- }
28085
- /**
28086
- * Point the ledger at a different deployment, discarding what it recorded
28087
- * about the previous one.
28088
- *
28089
- * Delivery is a fact about ONE recipient: rows sent to the deployment a
28090
- * machine has just left are undelivered as far as the new one is concerned.
28091
- * All four in one transaction, so a crash between them cannot leave stamps
28092
- * attributed to the wrong deployment, a boundary that belongs to another, or
28093
- * a disown with no re-mark to follow it.
28094
- *
28095
- * The boundary is written HERE and only here, which is what freezes it: a
28096
- * re-attach to the SAME deployment (a key rotation) leaves the fingerprint
28097
- * unchanged, so this never runs and the backlog does not widen back over rows
28098
- * the live path has since delivered.
28099
- *
28100
- * `backfillCapturesBefore` is the caller's OWN "now" at the instant a human
28101
- * granted existing-history consent for the deployment this call is arming —
28102
- * a DIFFERENT instant from `backlogBefore`: the re-mark boundary is the GRANT
28103
- * instant, `backlogBefore` is the ATTACH instant, and the two can be far
28104
- * apart. Passed only when that grant is valid, since this method has no way
28105
- * to check consent itself and must not mark a row owed for a machine that
28106
- * never agreed to it. Applied AFTER the disown above, in the SAME
28107
- * transaction: what the disown clears is every marker below `backlogBefore`,
28108
- * which includes this deployment's OWN pre-attach rows — `aka attach` calls
28109
- * `seedCaptureBacklogOwed` at the attach instant, so every row it marks sits
28110
- * on the cleared side of that bound — and the re-mark in the same
28111
- * transaction is what puts those rows back. A crash between the two cannot
28112
- * strand the ledger disowned with nothing re-marked — the transaction either
28113
- * lands whole or not at all, and a fingerprint mismatch that has not yet
28114
- * committed re-enters this method on the very next pass. Omit it (the
28115
- * structural-only tests do) to exercise the disown in isolation.
28116
- *
28117
- * The disown is bounded by `backlogBefore`, which is what keeps it from
28118
- * touching a marker the NEW deployment's OWN live path has already set: B's
28119
- * live path can mark a capture owed from the moment `aka attach` writes the
28120
- * descriptor, before the drain's first pass ever reaches this method, and
28121
- * such a row sits at or after the bound rather than below it. What keeps the
28122
- * disown from eating THIS SAME CALL's own re-mark is the order, not the
28123
- * bound — disown runs first, re-mark second, both inside the one
28124
- * transaction above.
28125
- */
28126
- rearmFor(fingerprint, backlogBefore, backfillCapturesBefore) {
28127
- this.ensureRowStmt.run();
28128
- withTransaction(
28129
- this.db,
28130
- () => {
28131
- const previous = getRow(this.fingerprintStmt)?.fingerprint;
28132
- this.rearmStmt.run();
28133
- if (previous !== null && previous !== void 0 && previous !== fingerprint) {
28134
- this.disownCapturesStmt.run({ attachedAt: backlogBefore });
28135
- }
28136
- if (backfillCapturesBefore !== void 0) {
28137
- this.markCaptureBacklogOwedStmt.run({ before: backfillCapturesBefore });
28138
- }
28139
- this.setFingerprintStmt.run({ fingerprint, backlogBefore });
28140
- },
28141
- "IMMEDIATE"
28142
- );
28143
- }
28144
- /**
28145
- * End the attached period: hand its rows to the live path, and release the
28146
- * boundary so the next attachment can freeze a new one.
28147
- *
28148
- * WITHOUT THIS, a detach and a re-attach to the same deployment leave a window
28149
- * nothing delivers. The fingerprint is unchanged, so the boundary is never
28150
- * re-frozen and stays at the FIRST attachment — while nothing forwards at all
28151
- * during the detached period, because the machine is not attached. Rows
28152
- * recorded in that window sit after the boundary and before the re-attach, so
28153
- * neither path takes them, and the pending count reports none outstanding.
28154
- *
28155
- * Stamping the attached window is not a claim that every one of those rows
28156
- * reached the deployment — the live path drops on failure and says so
28157
- * elsewhere. It records that they were ITS to deliver, which is exactly the
28158
- * status quo: they sit outside the frozen boundary today and are equally never
28159
- * re-sent. Making it explicit is what lets the boundary move.
28160
- *
28161
- * ONE TRANSACTION, so a crash cannot release the boundary while leaving the
28162
- * window unstamped — that half-state would re-send the whole attached period
28163
- * on the next attach, which is the failure the boundary exists to prevent.
28164
- */
28165
- closeAttachedWindow(attachedAtMs, atMs) {
28166
- this.ensureRowStmt.run();
28167
- withTransaction(
28168
- this.db,
28169
- () => {
28170
- const row = getRow(this.fingerprintStmt);
28171
- const from = row?.backlogBefore ?? attachedAtMs;
28172
- this.closeWindowStmt.run({ at: atMs, attachedAt: from });
28173
- this.releaseBoundaryStmt.run();
28174
- },
28175
- "IMMEDIATE"
28176
- );
28177
- }
28178
- /**
28179
- * Freeze a boundary for the deployment already on file, KEEPING the stamps.
28180
- *
28181
- * The re-attach half of the above. Distinct from `rearmFor`, which is for a
28182
- * different deployment and therefore discards what was delivered to the old
28183
- * one: here the recipient is the same, so everything already sent to it stays
28184
- * sent.
28185
- */
28186
- freezeBoundary(backlogBefore) {
28187
- this.ensureRowStmt.run();
28188
- this.freezeBoundaryStmt.run({ backlogBefore });
28189
- }
28190
- /** Take the claim, or report that someone live already holds it. */
28191
- claim(pid, host, nowMs, staleAfterMs) {
28192
- this.ensureRowStmt.run();
28193
- let taken = false;
28194
- withTransaction(
28195
- this.db,
28196
- () => {
28197
- const result = this.claimStmt.run({
28198
- pid,
28199
- host,
28200
- now: nowMs,
28201
- staleBefore: nowMs - staleAfterMs
28202
- });
28203
- taken = result.changes === 1;
28204
- },
28205
- "IMMEDIATE"
28206
- );
28207
- return taken;
28208
- }
28209
- /** Say the holder is still alive. A no-op once the claim has moved on. */
28210
- heartbeat(pid, nowMs) {
28211
- this.heartbeatStmt.run({ now: nowMs, pid });
28212
- }
28213
- /** Give the claim up. Scoped to this holder, so a taken-over claim is left be. */
28214
- release(pid) {
28215
- this.releaseStmt.run({ pid });
28216
- }
28217
- /** Who holds the claim, if anyone. Read-only, for the same reason as above. */
28218
- lease() {
28219
- return getRow(this.leaseStmt);
28220
- }
28221
- };
28222
-
28223
28834
  // ../../packages/persistence/src/repositories/inspection-definitions.ts
28224
28835
  var SqliteInspectionDefinitionsRepository = class {
28225
28836
  constructor(db) {
@@ -28450,6 +29061,7 @@ function overlayManagedSettings(settings, managed, now = () => /* @__PURE__ */ n
28450
29061
  if (values.vaultInlineReveal !== void 0) merged.vaultInlineReveal = values.vaultInlineReveal;
28451
29062
  if (values.dataSharesInPlace !== void 0) merged.dataSharesInPlace = values.dataSharesInPlace;
28452
29063
  if (values.redactFallback !== void 0) merged.redactFallback = values.redactFallback;
29064
+ if (values.bodyRetention !== void 0) merged.bodyRetention = values.bodyRetention;
28453
29065
  if (values.vaultConsent !== void 0) {
28454
29066
  merged.vaultConsent = values.vaultConsent ? (
28455
29067
  // Keep an existing valid grant so its acknowledgedAt survives; mint one
@@ -30957,7 +31569,7 @@ var SqliteSecurityRepository = class {
30957
31569
  ELSE 0
30958
31570
  END) AS open_at_rest
30959
31571
  FROM inspection_findings f
30960
- JOIN audit_events e ON e.id = f.audit_event_id
31572
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
30961
31573
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
30962
31574
  LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
30963
31575
  ON latest.finding_key = f.finding_key
@@ -31183,7 +31795,7 @@ var SqliteSecurityRepository = class {
31183
31795
  this.db.prepare(
31184
31796
  `SELECT e.repo AS repo, count(*) AS c
31185
31797
  FROM inspection_findings f
31186
- JOIN audit_events e ON e.id = f.audit_event_id
31798
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31187
31799
  WHERE e.started_at >= :from AND e.started_at < :to
31188
31800
  AND e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
31189
31801
  AND e.repo IS NOT NULL
@@ -31307,7 +31919,7 @@ var SqliteSecurityRepository = class {
31307
31919
  d.severity AS severity,
31308
31920
  COUNT(*) AS count
31309
31921
  FROM inspection_findings f
31310
- JOIN audit_events e ON e.id = f.audit_event_id
31922
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31311
31923
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
31312
31924
  LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
31313
31925
  ON latest.finding_key = f.finding_key
@@ -31342,7 +31954,7 @@ var SqliteSecurityRepository = class {
31342
31954
  `SELECT e.started_at AS occurred_at, d.severity AS severity, f.action_taken AS action_taken,
31343
31955
  d.rule_id AS rule_id, d.category AS category
31344
31956
  FROM inspection_findings f
31345
- JOIN audit_events e ON e.id = f.audit_event_id
31957
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31346
31958
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
31347
31959
  WHERE e.started_at >= :from AND e.started_at < :to
31348
31960
  AND e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
@@ -32183,6 +32795,7 @@ function openWithPragmas(file2) {
32183
32795
  db.exec("PRAGMA journal_mode = WAL");
32184
32796
  db.exec("PRAGMA busy_timeout = 2000");
32185
32797
  db.exec("PRAGMA foreign_keys = ON");
32798
+ registerSqlFunctions(db);
32186
32799
  } catch (err) {
32187
32800
  closeQuietly(db);
32188
32801
  throw err;
@@ -32212,7 +32825,7 @@ function backupLegacyStore(db, file2) {
32212
32825
  discardStore(file2, backup);
32213
32826
  return backup;
32214
32827
  }
32215
- function openAndInitialize(file2, base) {
32828
+ function openAndInitialize(file2, base, skipTags) {
32216
32829
  let db = openWithPragmas(file2);
32217
32830
  try {
32218
32831
  if (isForeignSqliteLineage(db)) {
@@ -32222,7 +32835,7 @@ function openAndInitialize(file2, base) {
32222
32835
  `Detected an older, incompatible (tenant-bearing) ${DB_FILENAME}; backed it up to ${backup} and created a fresh store.`
32223
32836
  );
32224
32837
  }
32225
- applyMigrations(db, file2);
32838
+ applyMigrations(db, file2, { skipTags });
32226
32839
  tightenPerms(file2);
32227
32840
  const policies = new SqlitePoliciesRepository(db);
32228
32841
  const installedPacks = new SqliteInstalledPacksRepository(db, base);
@@ -32237,6 +32850,7 @@ function openAndInitialize(file2, base) {
32237
32850
  exceptions: new SqliteExceptionsRepository(db),
32238
32851
  resolutions: new SqliteResolutionsRepository(db),
32239
32852
  ruleProbeCache: new SqliteRuleProbeCacheRepository(db),
32853
+ bodyRetention: new SqliteBodyRetentionRepository(db),
32240
32854
  security: new SqliteSecurityRepository(db),
32241
32855
  detections: new SqliteDetectionsRepository(db),
32242
32856
  shares: new SqliteSharesRepository(db),
@@ -32259,7 +32873,8 @@ function openAndInitialize(file2, base) {
32259
32873
  throw err;
32260
32874
  }
32261
32875
  }
32262
- function openLocalDatabase(dir) {
32876
+ var DEFERRED_TAGS = new Set(DEFERRED_MIGRATION_TAGS);
32877
+ function openLocalDatabase(dir, options = {}) {
32263
32878
  ensureDataDirSync(dir);
32264
32879
  const file2 = join7(dir, DB_FILENAME);
32265
32880
  reapStalePartials(file2);
@@ -32271,6 +32886,7 @@ function openLocalDatabase(dir) {
32271
32886
  installedPacks,
32272
32887
  scanLedger,
32273
32888
  historySync,
32889
+ bodyRetention,
32274
32890
  secretVault,
32275
32891
  exceptions,
32276
32892
  resolutions,
@@ -32294,7 +32910,8 @@ function openLocalDatabase(dir) {
32294
32910
  // `dir` is always `<base>/data` — every caller resolves it through
32295
32911
  // `dataDir()` — so its parent is the `~/.aka` base the layout splits into
32296
32912
  // settings/ and data/, and the pack-policy floor needs both halves.
32297
- dirname2(dir)
32913
+ dirname2(dir),
32914
+ options.applyDeferredMigrations === true ? void 0 : DEFERRED_TAGS
32298
32915
  );
32299
32916
  function captureRowId(event) {
32300
32917
  return captureId(
@@ -32487,6 +33104,7 @@ function openLocalDatabase(dir) {
32487
33104
  installedPacks,
32488
33105
  scanLedger,
32489
33106
  historySync,
33107
+ bodyRetention,
32490
33108
  secretVault,
32491
33109
  exceptions,
32492
33110
  resolutions,
@@ -32527,8 +33145,35 @@ function openLocalDatabase(dir) {
32527
33145
 
32528
33146
  // ../../packages/persistence/src/egress-wire.ts
32529
33147
  import { createHash as createHash3 } from "crypto";
33148
+ var PROJECT_KEY_DIGEST_VERSION = "v2";
33149
+ var SCP_FORM = /^(?:[^@/]+@)?([^/:]+):(.+)$/;
33150
+ var DOS_DRIVE = /^[A-Za-z]:[\\/]/;
33151
+ var FILE_URL = /^file:\/\//i;
33152
+ var SCHEME_FORM = /^[a-z][a-z0-9+.-]*:\/\/(?:[^@/]+@)?([^/:]+)(?::\d+)?(\/.*)?$/i;
33153
+ var SLASH = "/".charCodeAt(0);
33154
+ var GIT_SUFFIX = ".git";
33155
+ function trimSlashes(path) {
33156
+ let start = 0;
33157
+ let end = path.length;
33158
+ while (start < end && path.charCodeAt(start) === SLASH) start += 1;
33159
+ while (end > start && path.charCodeAt(end - 1) === SLASH) end -= 1;
33160
+ return path.slice(start, end);
33161
+ }
33162
+ function canonicalGitUrl(url2) {
33163
+ const trimmed = url2.trim();
33164
+ if (DOS_DRIVE.test(trimmed) || FILE_URL.test(trimmed)) return trimmed;
33165
+ const scheme = SCHEME_FORM.exec(trimmed);
33166
+ const scp = scheme === null ? SCP_FORM.exec(trimmed) : null;
33167
+ const host = (scheme?.[1] ?? scp?.[1])?.toLowerCase();
33168
+ if (host === void 0) return trimmed;
33169
+ const path = (scheme === null ? scp?.[2] : scheme[2]) ?? "";
33170
+ const bare = trimSlashes(path);
33171
+ const cleaned = bare.endsWith(GIT_SUFFIX) ? bare.slice(0, -GIT_SUFFIX.length) : bare;
33172
+ return cleaned === "" ? host : `${host}/${cleaned}`;
33173
+ }
32530
33174
  function hashProjectKey(projectKey) {
32531
- return createHash3("sha256").update(projectKey, "utf8").digest("hex");
33175
+ const canonical = projectKey.startsWith("git:") ? `git:${canonicalGitUrl(projectKey.slice("git:".length))}` : projectKey;
33176
+ return createHash3("sha256").update(`${PROJECT_KEY_DIGEST_VERSION}:${canonical}`, "utf8").digest("hex");
32532
33177
  }
32533
33178
  function toIngestHit(hit) {
32534
33179
  return {
@@ -32715,18 +33360,50 @@ function fingerprintValue(key, raw) {
32715
33360
  return createHmac("sha256", key.material).update(raw, "utf8").digest("hex");
32716
33361
  }
32717
33362
 
33363
+ // ../../packages/persistence/src/forward-health.ts
33364
+ import { readFileSync as readFileSync7 } from "fs";
33365
+ import { join as join9 } from "path";
33366
+ var FAILURES = /* @__PURE__ */ new Set([
33367
+ "unauthorized",
33368
+ "forbidden",
33369
+ "unreachable"
33370
+ ]);
33371
+ var BREAKER_COOLDOWN_MS = 3e4;
33372
+ function parseForwardHealth(raw, nowMs) {
33373
+ try {
33374
+ const parsed2 = JSON.parse(raw);
33375
+ if (typeof parsed2 !== "object" || parsed2 === null) return null;
33376
+ const record2 = parsed2;
33377
+ const failures = typeof record2.consecutiveFailures === "number" && record2.consecutiveFailures >= 0 ? record2.consecutiveFailures : 0;
33378
+ const openedAtMs = typeof record2.openedAtMs === "number" && Number.isFinite(record2.openedAtMs) && record2.openedAtMs <= nowMs ? record2.openedAtMs : null;
33379
+ const lastFailure = typeof record2.lastFailure === "string" && FAILURES.has(record2.lastFailure) ? record2.lastFailure : null;
33380
+ return { consecutiveFailures: failures, openedAtMs, lastFailure };
33381
+ } catch {
33382
+ return null;
33383
+ }
33384
+ }
33385
+ function isForwardPaused(health, nowMs) {
33386
+ const openedAtMs = health?.openedAtMs ?? null;
33387
+ if (openedAtMs === null) return false;
33388
+ return nowMs - openedAtMs < BREAKER_COOLDOWN_MS;
33389
+ }
33390
+
32718
33391
  // ../../packages/persistence/src/history-backfill.ts
32719
33392
  import { existsSync as existsSync4 } from "fs";
32720
- import { join as join9 } from "path";
33393
+ import { join as join10 } from "path";
32721
33394
 
32722
33395
  // ../../packages/persistence/src/history-preview.ts
32723
33396
  import { existsSync as existsSync5 } from "fs";
32724
- import { join as join10 } from "path";
33397
+ import { join as join11 } from "path";
32725
33398
  import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
32726
33399
 
33400
+ // ../../packages/persistence/src/history-sync-state.ts
33401
+ import { readFileSync as readFileSync8 } from "fs";
33402
+ import { join as join12 } from "path";
33403
+
32727
33404
  // ../../packages/persistence/src/store-symlinks.ts
32728
33405
  import { existsSync as existsSync6, lstatSync as lstatSync3, readlinkSync, realpathSync, statSync as statSync4 } from "fs";
32729
- import { dirname as dirname3, join as join11, resolve } from "path";
33406
+ import { dirname as dirname3, join as join13, resolve } from "path";
32730
33407
  var STORE_DB = "the store database (including the prompt corpus)";
32731
33408
  var STORE_SETTINGS = "your settings file";
32732
33409
  function storeContents(home) {
@@ -32735,7 +33412,7 @@ function storeContents(home) {
32735
33412
  [settingsDir(home), STORE_SETTINGS],
32736
33413
  [dataDir(home), STORE_DB],
32737
33414
  [keysDir(home), "the vault key"],
32738
- [join11(settingsDir(home), "settings.json"), STORE_SETTINGS],
33415
+ [join13(settingsDir(home), "settings.json"), STORE_SETTINGS],
32739
33416
  [dbPath(home), STORE_DB]
32740
33417
  ]);
32741
33418
  }
@@ -32886,8 +33563,8 @@ function formatPointer(category, keyVersion, pointerId, tag) {
32886
33563
  // ../../packages/persistence/src/vault/key-provider.ts
32887
33564
  import { execFileSync } from "child_process";
32888
33565
  import { randomBytes as randomBytes2 } from "crypto";
32889
- import { chmodSync as chmodSync3, readFileSync as readFileSync7, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
32890
- import { join as join12 } from "path";
33566
+ import { chmodSync as chmodSync3, readFileSync as readFileSync9, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
33567
+ import { join as join14 } from "path";
32891
33568
  var VAULT_OCCUPANT_REASON = {
32892
33569
  symlink: "the path is a symlink; remove it so a keyring can be created",
32893
33570
  gone: "the path was occupied but holds no keyring (removed while it was being created)",
@@ -32986,7 +33663,7 @@ function claimRotationLock(lock, owner) {
32986
33663
  throw asError(err);
32987
33664
  }
32988
33665
  try {
32989
- writeFileSync3(join12(lock, LOCK_OWNER_FILE), `${owner}
33666
+ writeFileSync3(join14(lock, LOCK_OWNER_FILE), `${owner}
32990
33667
  `, { mode: DATA_FILE_MODE });
32991
33668
  return true;
32992
33669
  } catch (err) {
@@ -32995,7 +33672,7 @@ function claimRotationLock(lock, owner) {
32995
33672
  }
32996
33673
  }
32997
33674
  function acquireRotationLock(keysDir2) {
32998
- const lock = join12(keysDir2, `${VAULT_KEY_FILENAME}.lock`);
33675
+ const lock = join14(keysDir2, `${VAULT_KEY_FILENAME}.lock`);
32999
33676
  const owner = randomBytes2(16).toString("hex");
33000
33677
  if (claimRotationLock(lock, owner)) return { lock, owner };
33001
33678
  let held;
@@ -33022,7 +33699,7 @@ function acquireRotationLock(keysDir2) {
33022
33699
  }
33023
33700
  function releaseRotationLock(lease) {
33024
33701
  try {
33025
- if (readFileSync7(join12(lease.lock, LOCK_OWNER_FILE), "utf8").trim() !== lease.owner) return;
33702
+ if (readFileSync9(join14(lease.lock, LOCK_OWNER_FILE), "utf8").trim() !== lease.owner) return;
33026
33703
  } catch {
33027
33704
  return;
33028
33705
  }
@@ -33043,7 +33720,7 @@ var FileKeyProvider = class {
33043
33720
  this.#keysDir = keysDir2;
33044
33721
  }
33045
33722
  get filePath() {
33046
- return join12(this.#keysDir, VAULT_KEY_FILENAME);
33723
+ return join14(this.#keysDir, VAULT_KEY_FILENAME);
33047
33724
  }
33048
33725
  loadOrCreate() {
33049
33726
  return asAsync(() => {
@@ -33073,7 +33750,7 @@ var FileKeyProvider = class {
33073
33750
  #read() {
33074
33751
  let raw;
33075
33752
  try {
33076
- raw = readFileSync7(this.filePath, "utf8");
33753
+ raw = readFileSync9(this.filePath, "utf8");
33077
33754
  } catch (err) {
33078
33755
  if (err.code === "ENOENT") return null;
33079
33756
  throw err instanceof Error ? err : new Error(String(err));
@@ -33709,11 +34386,11 @@ var SecretVault = class {
33709
34386
 
33710
34387
  // ../../packages/persistence/src/warn-era-cap.ts
33711
34388
  import { existsSync as existsSync7, writeFileSync as writeFileSync4 } from "fs";
33712
- import { join as join13 } from "path";
34389
+ import { join as join15 } from "path";
33713
34390
  var MARKER = "warn-era-capped";
33714
34391
  function capWarnEraEnforcementOnce(db, policyMode, dataDir2) {
33715
34392
  if (policyMode !== "warn") return { capped: 0, skipped: "not-warn" };
33716
- const marker = join13(dataDir2, MARKER);
34393
+ const marker = join15(dataDir2, MARKER);
33717
34394
  if (existsSync7(marker)) return { capped: 0, skipped: "already-run" };
33718
34395
  const capped = db.policies.capCategoryActions();
33719
34396
  writeFileSync4(marker, `${new Date(Date.now()).toISOString()}
@@ -33773,7 +34450,7 @@ function resolveProvider() {
33773
34450
  function loadConfig(base = defaultDataDir(), resolveProviderFn = resolveProvider) {
33774
34451
  try {
33775
34452
  ensureLayoutDirSync(base);
33776
- const settingsFile = join14(settingsDir(base), "settings.json");
34453
+ const settingsFile = join16(settingsDir(base), "settings.json");
33777
34454
  if (existsSync8(settingsFile)) tightenFile(settingsFile);
33778
34455
  } catch {
33779
34456
  }
@@ -33797,9 +34474,9 @@ function resolveProviderSafe(resolveProviderFn) {
33797
34474
  }
33798
34475
 
33799
34476
  // ../../packages/plugin-sdk/src/config-inventory.ts
33800
- import { readdirSync as readdirSync2, readFileSync as readFileSync9, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
34477
+ import { readdirSync as readdirSync2, readFileSync as readFileSync11, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
33801
34478
  import { homedir as homedir2 } from "os";
33802
- import { basename as basename3, join as join16 } from "path";
34479
+ import { basename as basename3, join as join18 } from "path";
33803
34480
 
33804
34481
  // ../../packages/detections/src/egress/registry.ts
33805
34482
  var EXTRACTOR_VERSION = "1";
@@ -36888,8 +37565,8 @@ function bundledDetections() {
36888
37565
  }
36889
37566
 
36890
37567
  // ../../packages/plugin-sdk/src/repo.ts
36891
- import { existsSync as existsSync9, readFileSync as readFileSync8, statSync as statSync6 } from "fs";
36892
- import { basename as basename2, dirname as dirname4, isAbsolute, join as join15, sep as sep2 } from "path";
37568
+ import { existsSync as existsSync9, readFileSync as readFileSync10, statSync as statSync6 } from "fs";
37569
+ import { basename as basename2, dirname as dirname4, isAbsolute, join as join17, sep as sep2 } from "path";
36893
37570
  function resolveRepo(cwd) {
36894
37571
  try {
36895
37572
  const root = findGitRoot(cwd);
@@ -36904,36 +37581,36 @@ function resolveRepo(cwd) {
36904
37581
  function findGitRoot(start) {
36905
37582
  let dir = start;
36906
37583
  for (; ; ) {
36907
- if (existsSync9(join15(dir, ".git"))) return dir;
37584
+ if (existsSync9(join17(dir, ".git"))) return dir;
36908
37585
  const parent = dirname4(dir);
36909
37586
  if (parent === dir) return void 0;
36910
37587
  dir = parent;
36911
37588
  }
36912
37589
  }
36913
37590
  function resolveGitContext(root) {
36914
- const dotGit = join15(root, ".git");
37591
+ const dotGit = join17(root, ".git");
36915
37592
  try {
36916
37593
  if (statSync6(dotGit).isDirectory()) {
36917
- return { configPath: join15(dotGit, "config"), headRoot: root };
37594
+ return { configPath: join17(dotGit, "config"), headRoot: root };
36918
37595
  }
36919
37596
  } catch {
36920
37597
  return void 0;
36921
37598
  }
36922
37599
  const target = /^gitdir:\s*(.+?)\s*$/m.exec(safeRead(dotGit) ?? "")?.[1];
36923
37600
  if (!target) return void 0;
36924
- const gitdir = isAbsolute(target) ? target : join15(root, target);
36925
- if (existsSync9(join15(gitdir, "config"))) {
36926
- return { configPath: join15(gitdir, "config"), headRoot: root };
37601
+ const gitdir = isAbsolute(target) ? target : join17(root, target);
37602
+ if (existsSync9(join17(gitdir, "config"))) {
37603
+ return { configPath: join17(gitdir, "config"), headRoot: root };
36927
37604
  }
36928
- const commonRaw = safeRead(join15(gitdir, "commondir"))?.trim();
37605
+ const commonRaw = safeRead(join17(gitdir, "commondir"))?.trim();
36929
37606
  if (!commonRaw) return void 0;
36930
- const commonGitDir = isAbsolute(commonRaw) ? commonRaw : join15(gitdir, commonRaw);
37607
+ const commonGitDir = isAbsolute(commonRaw) ? commonRaw : join17(gitdir, commonRaw);
36931
37608
  const headRoot = basename2(commonGitDir) === ".git" ? dirname4(commonGitDir) : root;
36932
- return { configPath: join15(commonGitDir, "config"), headRoot };
37609
+ return { configPath: join17(commonGitDir, "config"), headRoot };
36933
37610
  }
36934
37611
  function safeRead(path) {
36935
37612
  try {
36936
- return readFileSync8(path, "utf8");
37613
+ return readFileSync10(path, "utf8");
36937
37614
  } catch {
36938
37615
  return void 0;
36939
37616
  }
@@ -37477,8 +38154,8 @@ function createGuardedScanner(partition, gateway, opts) {
37477
38154
  }
37478
38155
 
37479
38156
  // ../../packages/plugin-sdk/src/host-floor.ts
37480
- import { readFileSync as readFileSync11 } from "fs";
37481
- import { join as join18 } from "path";
38157
+ import { readFileSync as readFileSync13 } from "fs";
38158
+ import { join as join20 } from "path";
37482
38159
 
37483
38160
  // ../../packages/plugin-sdk/src/model-governance.ts
37484
38161
  import {
@@ -37486,11 +38163,11 @@ import {
37486
38163
  fstatSync,
37487
38164
  mkdirSync as mkdirSync2,
37488
38165
  openSync as openSync2,
37489
- readFileSync as readFileSync10,
38166
+ readFileSync as readFileSync12,
37490
38167
  readSync,
37491
38168
  writeFileSync as writeFileSync5
37492
38169
  } from "fs";
37493
- import { join as join17 } from "path";
38170
+ import { join as join19 } from "path";
37494
38171
  var DATE_SUFFIX = /-\d{8}$/;
37495
38172
  function normalizeModelId(model) {
37496
38173
  return model.trim().toLowerCase().replace(DATE_SUFFIX, "");
@@ -37569,15 +38246,15 @@ var HOST_FLOORS = {
37569
38246
 
37570
38247
  // ../../packages/plugin-sdk/src/ignore-layers.ts
37571
38248
  var import_ignore = __toESM(require_ignore(), 1);
37572
- import { readFileSync as readFileSync12 } from "fs";
37573
- import { join as join19 } from "path";
38249
+ import { readFileSync as readFileSync14 } from "fs";
38250
+ import { join as join21 } from "path";
37574
38251
 
37575
38252
  // ../../packages/plugin-sdk/src/inventory-resolver.ts
37576
38253
  import { arch, hostname as hostname4, platform, release } from "os";
37577
38254
 
37578
38255
  // ../../packages/plugin-sdk/src/nudge.ts
37579
- import { mkdirSync as mkdirSync3, readFileSync as readFileSync13, writeFileSync as writeFileSync6 } from "fs";
37580
- import { join as join20 } from "path";
38256
+ import { mkdirSync as mkdirSync3, readFileSync as readFileSync15, writeFileSync as writeFileSync6 } from "fs";
38257
+ import { join as join22 } from "path";
37581
38258
 
37582
38259
  // ../../packages/plugin-sdk/src/paths.ts
37583
38260
  import { readdirSync as readdirSync3, realpathSync as realpathSync3 } from "fs";
@@ -37620,7 +38297,7 @@ function createPolicyResolver(bundle) {
37620
38297
 
37621
38298
  // ../../packages/plugin-sdk/src/project-files.ts
37622
38299
  import { existsSync as existsSync11, readdirSync as readdirSync4 } from "fs";
37623
- import { basename as basename5, join as join21 } from "path";
38300
+ import { basename as basename5, join as join23 } from "path";
37624
38301
 
37625
38302
  // ../../packages/plugin-sdk/src/provider-env-antigravity.ts
37626
38303
  var optionalBaseUrl2 = external_exports.preprocess((v) => {
@@ -37695,7 +38372,7 @@ function createPluginRuntime(gateway, settings, opts) {
37695
38372
  bundlesPacked = true;
37696
38373
  }
37697
38374
  const policyMode = settings.policy;
37698
- const redactFallback = settings.redactFallback;
38375
+ let redactFallback = settings.redactFallback;
37699
38376
  const dataDir2 = opts?.dataDir;
37700
38377
  let rules = [];
37701
38378
  let scanner;
@@ -37739,6 +38416,7 @@ function createPluginRuntime(gateway, settings, opts) {
37739
38416
  rules = [...verified, ...unverified];
37740
38417
  scanner = createGuardedScanner({ verified, unverified }, gateway, opts?.scanIsolation);
37741
38418
  bundleExceptions = bundle.exceptions ?? [];
38419
+ redactFallback = strongerRedactFallback(settings.redactFallback, bundle.redactFallback);
37742
38420
  initialized = true;
37743
38421
  }
37744
38422
  let cachedKey;
@@ -37777,11 +38455,13 @@ function createPluginRuntime(gateway, settings, opts) {
37777
38455
  function decide(findings, text, excepted, rewritable = true) {
37778
38456
  if (findings.length === 0) return { action: "log", text, findings: [] };
37779
38457
  const actionFor = (finding) => actionForFinding(finding, excepted, rewritable);
38458
+ const degradedActions = rewritable ? [] : findings.filter((f) => actionForFinding(f, excepted, true) === "redact").map(actionFor);
38459
+ const degraded = degradedActions.length === 0 ? {} : { redactDegradedTo: degradedActions.reduce((a, b) => strongerAction(a, b)) };
37780
38460
  let worst = "log";
37781
38461
  for (const finding of findings) {
37782
38462
  worst = strongerAction(worst, actionFor(finding));
37783
38463
  }
37784
- if (worst === "block") return { action: "block", text: null, findings };
38464
+ if (worst === "block") return { action: "block", text: null, findings, ...degraded };
37785
38465
  if (worst === "redact") {
37786
38466
  const redactFindings = findings.filter((f) => actionFor(f) === "redact");
37787
38467
  const reversibleFindings = redactFindings.filter((f) => resolver.isReversible(f.ruleId));
@@ -37791,9 +38471,13 @@ function createPluginRuntime(gateway, settings, opts) {
37791
38471
  findings,
37792
38472
  enforcedFindings: redactFindings,
37793
38473
  reversibleFindings
38474
+ // No `degraded` here, and it is not an omission: `rewritable` is per
38475
+ // CAPTURE, so on an unrewritable field every redact has already become
38476
+ // the fallback and this branch is unreachable. Spreading it would read
38477
+ // as a case that can happen.
37794
38478
  };
37795
38479
  }
37796
- return { action: worst, text, findings };
38480
+ return { action: worst, text, findings, ...degraded };
37797
38481
  }
37798
38482
  function fingerprintOf(key, finding, cache) {
37799
38483
  let fp = cache.get(finding);
@@ -37922,8 +38606,8 @@ function createPluginRuntime(gateway, settings, opts) {
37922
38606
  };
37923
38607
  }
37924
38608
  }
37925
- async function processText(text, context) {
37926
- return (await evaluate(text, context, {})).decision;
38609
+ async function processText(text, context, opts2 = {}) {
38610
+ return (await evaluate(text, context, {}, opts2.rewritable)).decision;
37927
38611
  }
37928
38612
  async function capture(input2, opts2 = {}) {
37929
38613
  const timingStartedAt = input2.occurredAt === void 0 ? startTiming() : void 0;
@@ -37946,10 +38630,12 @@ function createPluginRuntime(gateway, settings, opts) {
37946
38630
  );
37947
38631
  const storedContent = maskedFindings.length > 0 ? redact(input2.text, maskedFindings) : input2.text;
37948
38632
  const inspectionMs = elapsedMs(timingStartedAt);
37949
- const metadata = exceptionIds.length > 0 || inspectionMs !== void 0 ? {
38633
+ const redactDegradedTo = decision.redactDegradedTo;
38634
+ const metadata = exceptionIds.length > 0 || inspectionMs !== void 0 || redactDegradedTo !== void 0 ? {
37950
38635
  ...input2.metadata,
37951
38636
  ...exceptionIds.length > 0 ? { exceptionIds } : {},
37952
- ...inspectionMs !== void 0 ? { inspectionMs } : {}
38637
+ ...inspectionMs !== void 0 ? { inspectionMs } : {},
38638
+ ...redactDegradedTo !== void 0 ? { redactDegradedTo } : {}
37953
38639
  } : input2.metadata;
37954
38640
  const event = buildIngestEvent({
37955
38641
  kind: input2.kind,
@@ -38021,7 +38707,7 @@ var THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1e3;
38021
38707
 
38022
38708
  // ../../packages/plugin-sdk/src/throttle.ts
38023
38709
  import { mkdirSync as mkdirSync4, statSync as statSync8, writeFileSync as writeFileSync7 } from "fs";
38024
- import { join as join22 } from "path";
38710
+ import { join as join24 } from "path";
38025
38711
 
38026
38712
  // ../../packages/plugin-sdk/src/tokenize.ts
38027
38713
  function redactedPlaceholder(category) {
@@ -38341,17 +39027,17 @@ var UNOPENABLE_VAULT = {
38341
39027
 
38342
39028
  // src/protocol/marker.ts
38343
39029
  import { randomBytes as randomBytes4 } from "crypto";
38344
- import { mkdirSync as mkdirSync5, readFileSync as readFileSync14, renameSync as renameSync5, writeFileSync as writeFileSync8 } from "fs";
38345
- import { join as join23 } from "path";
39030
+ import { mkdirSync as mkdirSync5, readFileSync as readFileSync16, renameSync as renameSync5, writeFileSync as writeFileSync8 } from "fs";
39031
+ import { join as join25 } from "path";
38346
39032
  var MARKER_FILE = "protocol-marker";
38347
39033
  function mintMarker() {
38348
39034
  return randomBytes4(8).toString("hex");
38349
39035
  }
38350
39036
  function sessionProtocolMarker(dataDir2, sessionId) {
38351
39037
  if (!sessionId) return mintMarker();
38352
- const path = join23(dataDir2, MARKER_FILE);
39038
+ const path = join25(dataDir2, MARKER_FILE);
38353
39039
  try {
38354
- const stored = JSON.parse(readFileSync14(path, "utf8"));
39040
+ const stored = JSON.parse(readFileSync16(path, "utf8"));
38355
39041
  if (stored.sessionId === sessionId && typeof stored.marker === "string" && /^[0-9a-f]{16}$/.test(stored.marker)) {
38356
39042
  return stored.marker;
38357
39043
  }
@@ -38360,7 +39046,7 @@ function sessionProtocolMarker(dataDir2, sessionId) {
38360
39046
  const marker = mintMarker();
38361
39047
  try {
38362
39048
  mkdirSync5(dataDir2, { recursive: true, mode: DATA_DIR_MODE });
38363
- const tmp = join23(dataDir2, `${MARKER_FILE}.tmp`);
39049
+ const tmp = join25(dataDir2, `${MARKER_FILE}.tmp`);
38364
39050
  writeFileSync8(tmp, JSON.stringify({ sessionId, marker }), { mode: DATA_FILE_MODE });
38365
39051
  renameSync5(tmp, path);
38366
39052
  } catch {
@@ -38415,9 +39101,9 @@ function userDisclosure(opts) {
38415
39101
 
38416
39102
  // src/hooks/model-guard.ts
38417
39103
  import { randomUUID as randomUUID15 } from "crypto";
38418
- import { readFileSync as readFileSync15, statSync as statSync9 } from "fs";
39104
+ import { readFileSync as readFileSync17, statSync as statSync9 } from "fs";
38419
39105
  import { homedir as homedir3 } from "os";
38420
- import { dirname as dirname6, join as join24 } from "path";
39106
+ import { dirname as dirname6, join as join26 } from "path";
38421
39107
  var SUBAGENT_TOOLS = /* @__PURE__ */ new Set(["Task", "Agent"]);
38422
39108
  var SAFE_SUBAGENT_TYPE = /^[A-Za-z0-9][A-Za-z0-9_-]*$/;
38423
39109
  function projectAgentsRoot(from) {
@@ -38427,7 +39113,7 @@ function projectAgentsRoot(from) {
38427
39113
  for (let depth = 0; depth < 24; depth += 1) {
38428
39114
  if (dir === home) return void 0;
38429
39115
  try {
38430
- if (statSync9(join24(dir, ".claude", "agents")).isDirectory()) return dir;
39116
+ if (statSync9(join26(dir, ".claude", "agents")).isDirectory()) return dir;
38431
39117
  } catch {
38432
39118
  }
38433
39119
  const parent = dirname6(dir);
@@ -38443,7 +39129,7 @@ function modelFromAgentDefinition(subagentType, cwd) {
38443
39129
  );
38444
39130
  for (const root of roots) {
38445
39131
  try {
38446
- const raw = readFileSync15(join24(root, ".claude", "agents", `${subagentType}.md`), "utf8");
39132
+ const raw = readFileSync17(join26(root, ".claude", "agents", `${subagentType}.md`), "utf8");
38447
39133
  const lines = raw.split("\n");
38448
39134
  if (lines[0]?.trim() !== "---") continue;
38449
39135
  for (const line of lines.slice(1)) {
@@ -38640,7 +39326,7 @@ function exceptionPointer(references) {
38640
39326
  }
38641
39327
 
38642
39328
  // src/hooks/pre-tool-use-decision.ts
38643
- var EXECUTABLE_REDACT_NOTE = "Masking inside an executable command would silently change what runs, so a redact policy blocks it instead.";
39329
+ var EXECUTABLE_REDACT_NOTE = "Masking inside an executable command would silently change what runs, so masking in place was not possible and this workspace\u2019s fallback for that case is to block.";
38644
39330
  var UNREDACTABLE_NOTE = "The redacted form of this input was unavailable, so the call is blocked rather than sent unmasked.";
38645
39331
  function pointerCategory(token) {
38646
39332
  const match = /^\[\[aka:([a-z_]+):/.exec(token);
@@ -38657,9 +39343,8 @@ async function decidePreToolUse(toolName, toolInput, scanned, tokenizeField) {
38657
39343
  let updatedInput = null;
38658
39344
  const realized = { pointers: [], degraded: [] };
38659
39345
  for (const { spec, text, result } of scanned) {
38660
- const escalate = result.action === "redact" && spec.executable;
38661
- if (escalate) escalated = true;
38662
- const action = escalate ? "block" : result.action;
39346
+ if (result.redactDegradedTo === "block") escalated = true;
39347
+ const action = result.action;
38663
39348
  if (action === "block") {
38664
39349
  for (const finding of result.findings) blockedRules.add(finding.ruleId);
38665
39350
  if (result.blockedReferences) blockedReferences.push(...result.blockedReferences);
@@ -38875,7 +39560,7 @@ function baseMetadata(input2) {
38875
39560
 
38876
39561
  // src/hooks/store-health.ts
38877
39562
  import { mkdirSync as mkdirSync6, readFileSync as readFileSync21, writeFileSync as writeFileSync9 } from "fs";
38878
- import { dirname as dirname7, join as join31 } from "path";
39563
+ import { dirname as dirname7, join as join32 } from "path";
38879
39564
 
38880
39565
  // ../../packages/remote/src/http.ts
38881
39566
  import { request as httpRequest } from "http";
@@ -39060,10 +39745,10 @@ function parsed(schema, body, route) {
39060
39745
  }
39061
39746
  function withoutTrailingSlashes(endpoint) {
39062
39747
  let end = endpoint.length;
39063
- while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH) end -= 1;
39748
+ while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH2) end -= 1;
39064
39749
  return endpoint.slice(0, end);
39065
39750
  }
39066
- var SLASH = "/".charCodeAt(0);
39751
+ var SLASH2 = "/".charCodeAt(0);
39067
39752
  function createRemoteClient(options) {
39068
39753
  const base = withoutTrailingSlashes(options.endpoint);
39069
39754
  const url2 = (route) => `${base}${route}`;
@@ -39245,11 +39930,11 @@ function withTimeout(promise2, ms) {
39245
39930
  }
39246
39931
 
39247
39932
  // ../../packages/plugin-runtime/src/attached/forward-drops.ts
39248
- import { readFileSync as readFileSync16 } from "fs";
39249
- import { join as join25 } from "path";
39933
+ import { readFileSync as readFileSync18 } from "fs";
39934
+ import { join as join27 } from "path";
39250
39935
  var FORWARD_DROPS_FILENAME = ATTACHED_FORWARD_DROPS_FILENAME;
39251
39936
  function forwardDropsPath(dataDir2) {
39252
- return join25(dataDir2, FORWARD_DROPS_FILENAME);
39937
+ return join27(dataDir2, FORWARD_DROPS_FILENAME);
39253
39938
  }
39254
39939
  function recordForwardDrops(dataDir2, count, nowMs) {
39255
39940
  if (count <= 0) return;
@@ -39267,7 +39952,7 @@ function recordForwardDrops(dataDir2, count, nowMs) {
39267
39952
  }
39268
39953
  function readForwardDrops(dataDir2) {
39269
39954
  try {
39270
- const parsed2 = JSON.parse(readFileSync16(forwardDropsPath(dataDir2), "utf8"));
39955
+ const parsed2 = JSON.parse(readFileSync18(forwardDropsPath(dataDir2), "utf8"));
39271
39956
  if (typeof parsed2 !== "object" || parsed2 === null) return null;
39272
39957
  const record2 = parsed2;
39273
39958
  if (typeof record2.droppedForwards !== "number" || !Number.isFinite(record2.droppedForwards)) {
@@ -39285,9 +39970,8 @@ function readForwardDrops(dataDir2) {
39285
39970
 
39286
39971
  // ../../packages/plugin-runtime/src/attached/forward-policy.ts
39287
39972
  import { randomUUID as randomUUID16 } from "crypto";
39288
- import { readFileSync as readFileSync17 } from "fs";
39289
39973
  import { readFile, rename, writeFile } from "fs/promises";
39290
- import { join as join26 } from "path";
39974
+ import { join as join28 } from "path";
39291
39975
  function isInvalidRequest(err) {
39292
39976
  return typeof err === "object" && err !== null && err.name === "RemoteRequestInvalid";
39293
39977
  }
@@ -39301,31 +39985,12 @@ function isServerRejection(err) {
39301
39985
  var FORWARD_BUDGET_MS = 1500;
39302
39986
  var DECISION_PATH_BUDGET_MS = 800;
39303
39987
  var BREAKER_FAILURE_THRESHOLD = 3;
39304
- var BREAKER_COOLDOWN_MS = 3e4;
39305
39988
  var CLOSED = { consecutiveFailures: 0, openedAtMs: null, lastFailure: null };
39306
- var FAILURES = /* @__PURE__ */ new Set([
39307
- "unauthorized",
39308
- "forbidden",
39309
- "unreachable"
39310
- ]);
39311
39989
  var FORWARD_STATE_FILENAME = ATTACHED_FORWARD_STATE_FILENAME;
39312
39990
  var STATE_FILENAME = FORWARD_STATE_FILENAME;
39313
- function parseBreakerState(raw, nowMs) {
39314
- try {
39315
- const parsed2 = JSON.parse(raw);
39316
- if (typeof parsed2 !== "object" || parsed2 === null) return null;
39317
- const record2 = parsed2;
39318
- const failures = typeof record2.consecutiveFailures === "number" && record2.consecutiveFailures >= 0 ? record2.consecutiveFailures : 0;
39319
- const openedAtMs = typeof record2.openedAtMs === "number" && Number.isFinite(record2.openedAtMs) && record2.openedAtMs <= nowMs ? record2.openedAtMs : null;
39320
- const lastFailure = typeof record2.lastFailure === "string" && FAILURES.has(record2.lastFailure) ? record2.lastFailure : null;
39321
- return { consecutiveFailures: failures, openedAtMs, lastFailure };
39322
- } catch {
39323
- return null;
39324
- }
39325
- }
39326
39991
  function createForwardPolicy(deps) {
39327
39992
  const now = deps.now ?? (() => Date.now());
39328
- const file2 = join26(deps.dir, STATE_FILENAME);
39993
+ const file2 = join28(deps.dir, STATE_FILENAME);
39329
39994
  let state = null;
39330
39995
  let loading = null;
39331
39996
  async function readState() {
@@ -39335,7 +40000,7 @@ function createForwardPolicy(deps) {
39335
40000
  } catch {
39336
40001
  return { ...CLOSED };
39337
40002
  }
39338
- return parseBreakerState(raw, now()) ?? { ...CLOSED };
40003
+ return parseForwardHealth(raw, now()) ?? { ...CLOSED };
39339
40004
  }
39340
40005
  async function load() {
39341
40006
  if (state !== null) return state;
@@ -39381,7 +40046,7 @@ function createForwardPolicy(deps) {
39381
40046
  };
39382
40047
  const at = now();
39383
40048
  if (current.openedAtMs !== null) {
39384
- if (at - current.openedAtMs < BREAKER_COOLDOWN_MS) {
40049
+ if (isForwardPaused(current, at)) {
39385
40050
  return { ok: false, reason: "breaker-open" };
39386
40051
  }
39387
40052
  await persist({
@@ -39918,7 +40583,18 @@ var AttachedDataGateway = class {
39918
40583
  // and the spread above would otherwise drop the field silently — which is
39919
40584
  // exactly what it did, leaving the whole control inert on every device
39920
40585
  // while every test around it stayed green.
39921
- prohibitedModels: cached2.prohibitedModels
40586
+ prohibitedModels: cached2.prohibitedModels,
40587
+ // NAMED for the same reason as the line above, and it is the same defect
40588
+ // if it is not: `...local` above spreads the DEVICE's bundle, so a field
40589
+ // only the cache carries is dropped in silence. That is what left
40590
+ // `prohibitedModels` inert on every attached device with every test
40591
+ // around it green.
40592
+ //
40593
+ // Taken from the cache rather than merged here, because merging it needs
40594
+ // the device's own SETTING — which is not a bundle field and is not in
40595
+ // scope at this seam. The runtime does that merge, raise-only, where both
40596
+ // values are in hand (createPluginRuntime's ensureInitialized).
40597
+ redactFallback: cached2.redactFallback
39922
40598
  // ALSO HONOURED FROM THE CACHE, and not a bundle field at all: each
39923
40599
  // merged policy's own `provenance`. `mergeRaiseOnly` spreads the policies
39924
40600
  // it emits, so an 'authored' policy arriving from the control plane
@@ -40046,10 +40722,6 @@ function toolAuditEvent(input2) {
40046
40722
  };
40047
40723
  }
40048
40724
 
40049
- // ../../packages/plugin-runtime/src/attached/history-state.ts
40050
- import { readFileSync as readFileSync18 } from "fs";
40051
- import { join as join27 } from "path";
40052
-
40053
40725
  // ../../packages/plugin-runtime/src/attached/history-sync.ts
40054
40726
  import { createHash as createHash6 } from "crypto";
40055
40727
  import { hostname as hostname5 } from "os";
@@ -40058,6 +40730,10 @@ import { hostname as hostname5 } from "os";
40058
40730
  var CORRELATION_ID = EventMetadata.shape.correlationId;
40059
40731
  var TRACE_ID = EventMetadata.shape.traceId;
40060
40732
  var EXCEPTION_ID = EventMetadata.shape.exceptionIds.unwrap().element;
40733
+ var REDACT_DEGRADED_TO = EventMetadata.shape.redactDegradedTo.unwrap();
40734
+
40735
+ // ../../packages/plugin-runtime/src/attached/history-sync.ts
40736
+ var CAPTURE_BATCH_BYTES = 1024 * 1024;
40061
40737
 
40062
40738
  // ../../packages/plugin-runtime/src/attached/history-sync-trigger.ts
40063
40739
  import { spawn } from "child_process";
@@ -40084,7 +40760,7 @@ function createPluginBlock(build, policyStore) {
40084
40760
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
40085
40761
  import { randomUUID as randomUUID17 } from "crypto";
40086
40762
  import { readFile as readFile2, rm, writeFile as writeFile2 } from "fs/promises";
40087
- import { join as join28 } from "path";
40763
+ import { join as join29 } from "path";
40088
40764
 
40089
40765
  // ../../packages/plugin-runtime/src/attached/atomic-publish.ts
40090
40766
  import { rename as rename2 } from "fs/promises";
@@ -40108,7 +40784,7 @@ async function publishByRename(tmp, file2, move = rename2) {
40108
40784
 
40109
40785
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
40110
40786
  function createPolicyStore(dir = dataDir()) {
40111
- const file2 = join28(dir, "policy-cache.json");
40787
+ const file2 = join29(dir, "policy-cache.json");
40112
40788
  async function read() {
40113
40789
  try {
40114
40790
  const raw = await readFile2(file2, "utf8");
@@ -40339,11 +41015,11 @@ function readStorePosture(dbPath2) {
40339
41015
  // ../../packages/plugin-runtime/src/attached/posture-store.ts
40340
41016
  import { randomUUID as randomUUID18 } from "crypto";
40341
41017
  import { readFile as readFile3, rm as rm2, writeFile as writeFile3 } from "fs/promises";
40342
- import { join as join29 } from "path";
41018
+ import { join as join30 } from "path";
40343
41019
  var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
40344
41020
  function createPostureStore(dir = settingsDir(), legacyDir) {
40345
- const file2 = join29(dir, "posture-state.json");
40346
- const legacyFile = legacyDir === void 0 ? null : join29(legacyDir, "posture-state.json");
41021
+ const file2 = join30(dir, "posture-state.json");
41022
+ const legacyFile = legacyDir === void 0 ? null : join30(legacyDir, "posture-state.json");
40347
41023
  async function persist(state) {
40348
41024
  await ensureDataDir(dir);
40349
41025
  const tmp = `${file2}.${randomUUID18()}.tmp`;
@@ -40412,7 +41088,7 @@ function createPostureStore(dir = settingsDir(), legacyDir) {
40412
41088
 
40413
41089
  // ../../packages/plugin-runtime/src/attached/sync-state.ts
40414
41090
  import { readFileSync as readFileSync20 } from "fs";
40415
- import { join as join30 } from "path";
41091
+ import { join as join31 } from "path";
40416
41092
 
40417
41093
  // ../../packages/plugin-runtime/src/attached/status.ts
40418
41094
  var REFUSAL_LINES = {
@@ -40433,6 +41109,14 @@ import { spawn as spawn2 } from "child_process";
40433
41109
  import { fileURLToPath as fileURLToPath3 } from "url";
40434
41110
  var SYNC_THROTTLE_MS = 15 * 60 * 1e3;
40435
41111
 
41112
+ // ../../packages/plugin-runtime/src/content-retention-pass.ts
41113
+ var MAX_ROWS_PER_SWEEP = 50 * 1e3;
41114
+
41115
+ // ../../packages/plugin-runtime/src/content-retention-trigger.ts
41116
+ import { spawn as spawn3 } from "child_process";
41117
+ import { fileURLToPath as fileURLToPath4 } from "url";
41118
+ var CONTENT_RETENTION_THROTTLE_MS = 60 * 60 * 1e3;
41119
+
40436
41120
  // ../../packages/plugin-runtime/src/attached/factory.ts
40437
41121
  import { hostname as hostname6 } from "os";
40438
41122
 
@@ -40908,7 +41592,7 @@ function markerDirs(dataDir2) {
40908
41592
  function alreadyClaimed(dirs, marker, sessionId) {
40909
41593
  return dirs.some((dir) => {
40910
41594
  try {
40911
- return readFileSync21(join31(dir, marker), "utf8") === sessionId;
41595
+ return readFileSync21(join32(dir, marker), "utf8") === sessionId;
40912
41596
  } catch {
40913
41597
  return false;
40914
41598
  }
@@ -40918,7 +41602,7 @@ function recordClaim(dirs, marker, sessionId) {
40918
41602
  for (const dir of dirs) {
40919
41603
  try {
40920
41604
  mkdirSync6(dir, { recursive: true, mode: DATA_DIR_MODE });
40921
- writeFileSync9(join31(dir, marker), sessionId, { mode: DATA_FILE_MODE });
41605
+ writeFileSync9(join32(dir, marker), sessionId, { mode: DATA_FILE_MODE });
40922
41606
  return;
40923
41607
  } catch {
40924
41608
  }
@@ -41066,7 +41750,14 @@ async function main() {
41066
41750
  ...kind === "tool_use" ? { persist: "with-findings" } : {},
41067
41751
  // Grants this call's pointer crossing already spent: suppression
41068
41752
  // applies without charging a second use.
41069
- ...spentGrantIds.length > 0 ? { preAuthorizedGrantIds: spentGrantIds } : {}
41753
+ ...spentGrantIds.length > 0 ? { preAuthorizedGrantIds: spentGrantIds } : {},
41754
+ // Per FIELD: a field that EXECUTES cannot be masked in place, since
41755
+ // rewriting a command changes what runs. Data fields can be, and keep
41756
+ // true redaction — including the reversible vault rewrite below. A
41757
+ // redact on an executable field degrades to the configured
41758
+ // `redactFallback` inside the runtime, the one place the emitted
41759
+ // decision, the recorded action and the ledger all read.
41760
+ rewritable: !spec.executable
41070
41761
  }
41071
41762
  );
41072
41763
  scanned.push({ spec, text, result });