@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: {
@@ -23642,7 +23830,7 @@ var VaultConsent = external_exports.object({
23642
23830
  });
23643
23831
 
23644
23832
  // ../../packages/schema/src/zod/local.ts
23645
- var WORKSPACE_SETTINGS_SPEC_VERSION = 7;
23833
+ var WORKSPACE_SETTINGS_SPEC_VERSION = 8;
23646
23834
  var MODEL_JUDGE_PAYLOAD_VERSION = 1;
23647
23835
  var RunMode = external_exports.enum(["standalone", "attached"]);
23648
23836
  var ControlPlaneConnection = external_exports.object({
@@ -23662,6 +23850,15 @@ var HistorySyncConsent = external_exports.object({
23662
23850
  payloadVersion: external_exports.number().int().positive(),
23663
23851
  endpoint: external_exports.string()
23664
23852
  });
23853
+ var BODY_RETENTION_DEFAULT_DAYS = 30;
23854
+ var BodyRetention = external_exports.object({
23855
+ enabled: external_exports.boolean().default(false),
23856
+ // Never 0, and the ceiling is a fat-finger guard rather than a policy
23857
+ // limit — `enabled` is the real gate. A low value cannot reach a row the
23858
+ // sync ledger still owes: the sweep's age filter only ever NARROWS a
23859
+ // candidate set that is already bounded by "delivered, or never owed".
23860
+ retainDays: external_exports.number().int().min(1).max(3650).default(BODY_RETENTION_DEFAULT_DAYS)
23861
+ }).meta({ id: "BodyRetention" });
23665
23862
  var WorkspaceSettings = external_exports.object({
23666
23863
  specVersion: external_exports.number().int().positive().default(WORKSPACE_SETTINGS_SPEC_VERSION),
23667
23864
  runMode: RunMode.default("standalone"),
@@ -23710,7 +23907,13 @@ var WorkspaceSettings = external_exports.object({
23710
23907
  // carry prompt/reply/tool-output text in `content`; the key name predates
23711
23908
  // both widenings. Absent until granted, and a grant for a different endpoint
23712
23909
  // or an older payload no longer counts.
23713
- historySyncConsent: HistorySyncConsent.optional()
23910
+ historySyncConsent: HistorySyncConsent.optional(),
23911
+ // Local body expiry (see BodyRetention). Off until switched on; expiring a
23912
+ // body never removes the row or its findings.
23913
+ bodyRetention: BodyRetention.default({
23914
+ enabled: false,
23915
+ retainDays: BODY_RETENTION_DEFAULT_DAYS
23916
+ })
23714
23917
  });
23715
23918
  function defaultWorkspaceSettings() {
23716
23919
  return WorkspaceSettings.parse({});
@@ -23805,12 +24008,15 @@ function toCaptureAttributes(event) {
23805
24008
  ...metadata?.traceId !== void 0 ? { trace_id: metadata.traceId } : {},
23806
24009
  ...metadata?.exceptionIds !== void 0 ? { exception_ids: metadata.exceptionIds } : {},
23807
24010
  ...metadata?.inspectionMs !== void 0 ? { inspection_ms: metadata.inspectionMs } : {},
24011
+ ...metadata?.redactDegradedTo !== void 0 ? { redact_degraded_to: metadata.redactDegradedTo } : {},
23808
24012
  // `model`/`turnIndex` have no dedicated CaptureAttributes field (no writer
23809
24013
  // has ever populated either), but every legacy metadata key still rides
23810
24014
  // the bag rather than being silently dropped — CaptureAttributes'
23811
24015
  // `.catchall(z.unknown())` carries the long tail.
23812
24016
  ...metadata?.model !== void 0 ? { model: metadata.model } : {},
23813
- ...metadata?.turnIndex !== void 0 ? { turn_index: metadata.turnIndex } : {}
24017
+ ...metadata?.turnIndex !== void 0 ? { turn_index: metadata.turnIndex } : {},
24018
+ ...metadata?.messageId !== void 0 ? { message_id: metadata.messageId } : {},
24019
+ ...metadata?.conversationId !== void 0 ? { conversation_id: metadata.conversationId } : {}
23814
24020
  };
23815
24021
  }
23816
24022
  function captureDefinitionVersion(finding) {
@@ -23838,13 +24044,22 @@ var ManagedSettingKey = external_exports.enum([
23838
24044
  "vaultInlineReveal",
23839
24045
  "modelJudgeConsent",
23840
24046
  "dataSharesInPlace",
23841
- "redactFallback"
24047
+ "redactFallback",
24048
+ // Pins the toggle and the day count together — see BodyRetention on why the
24049
+ // two are one unit. An administrator mandating a window wants the count
24050
+ // enforced with it, not one a user can widen while the toggle stays on.
24051
+ "bodyRetention"
23842
24052
  ]).meta({ id: "ManagedSettingKey" });
23843
24053
  function isManagedSettingKey(value) {
23844
24054
  return ManagedSettingKey.safeParse(value).success;
23845
24055
  }
23846
24056
  var ManagedSettingsValues = external_exports.object({
23847
24057
  runMode: external_exports.enum(["standalone", "attached"]).optional(),
24058
+ // `controlPlane` and `bodyRetention` are the two nested values, and both are
24059
+ // plain, non-strict objects: a key under either that this build does not know
24060
+ // is stripped and nothing reports it. The unknown-value split in
24061
+ // ManagedSettings below classifies top-level names only, so it stops at
24062
+ // these boundaries.
23848
24063
  controlPlane: external_exports.object({
23849
24064
  endpoint: external_exports.string().min(1),
23850
24065
  label: external_exports.string().min(1).optional()
@@ -23855,7 +24070,8 @@ var ManagedSettingsValues = external_exports.object({
23855
24070
  vaultInlineReveal: external_exports.enum(["masked", "full", "off"]).optional(),
23856
24071
  modelJudgeConsent: external_exports.boolean().optional(),
23857
24072
  dataSharesInPlace: external_exports.boolean().optional(),
23858
- redactFallback: RedactFallback.optional()
24073
+ redactFallback: RedactFallback.optional(),
24074
+ bodyRetention: BodyRetention.optional()
23859
24075
  }).meta({ id: "ManagedSettingsValues" });
23860
24076
  var ManagedSettings = external_exports.object({
23861
24077
  specVersion: external_exports.number().int().positive().default(MANAGED_SETTINGS_SPEC_VERSION),
@@ -23863,7 +24079,21 @@ var ManagedSettings = external_exports.object({
23863
24079
  // decision from a bug. Absent renders as a generic "your organization".
23864
24080
  organization: external_exports.string().min(1).optional(),
23865
24081
  // What the administrator pinned.
23866
- values: ManagedSettingsValues.default({}),
24082
+ //
24083
+ // Parsed as a RECORD rather than as the nested schema, and split below for
24084
+ // the same reason `lockedFields` is parsed as names: a plain `z.object`
24085
+ // drops an unrecognised key and succeeds, so a pin this build does not know
24086
+ // vanished and nothing anywhere said so. A pin with no lock is a supported
24087
+ // shape — it is a DEFAULT the user may still change — so that silence hit
24088
+ // exactly the file an administrator is most likely to write while a fleet
24089
+ // is mid-upgrade.
24090
+ //
24091
+ // Splitting here rather than calling `.strict()`: strict would REFUSE the
24092
+ // file, which is the outcome the lock half already rejected — an older
24093
+ // build then runs entirely unmanaged, every pin and lock gone. A bad KNOWN
24094
+ // value still fails, because the nested schema is re-run over the known
24095
+ // subset and its issues are re-raised on this parse.
24096
+ values: external_exports.record(external_exports.string(), external_exports.unknown()).default({}),
23867
24097
  // Which of those the user may not change. A key here with no matching value
23868
24098
  // freezes whatever the user last chose; a value with no lock is a DEFAULT
23869
24099
  // the user may still override. The two are separable on purpose.
@@ -23876,17 +24106,31 @@ var ManagedSettings = external_exports.object({
23876
24106
  // the fleets most likely to carry a version skew. A name outside the enum
23877
24107
  // is still never HONOURED: the lockable set stays explicit above.
23878
24108
  lockedFields: external_exports.array(external_exports.string()).default([])
23879
- }).transform(({ lockedFields, ...rest }) => {
24109
+ }).transform(({ lockedFields, values, ...rest }, ctx) => {
23880
24110
  const known = [];
23881
24111
  const unknown2 = [];
23882
24112
  for (const name of lockedFields) {
23883
24113
  if (isManagedSettingKey(name)) known.push(name);
23884
24114
  else unknown2.push(name);
23885
24115
  }
24116
+ const knownValues = /* @__PURE__ */ Object.create(null);
24117
+ const unknownValues = [];
24118
+ for (const [name, value] of Object.entries(values)) {
24119
+ if (Object.hasOwn(ManagedSettingsValues.shape, name)) knownValues[name] = value;
24120
+ else unknownValues.push(name);
24121
+ }
24122
+ const pinned = ManagedSettingsValues.safeParse(knownValues);
24123
+ if (!pinned.success) {
24124
+ for (const issue2 of pinned.error.issues)
24125
+ ctx.addIssue({ ...issue2, path: ["values", ...issue2.path] });
24126
+ return external_exports.NEVER;
24127
+ }
23886
24128
  return {
23887
24129
  ...rest,
24130
+ values: pinned.data,
23888
24131
  lockedFields: known,
23889
- ...unknown2.length > 0 ? { unknownLockedFields: unknown2 } : {}
24132
+ ...unknown2.length > 0 ? { unknownLockedFields: unknown2 } : {},
24133
+ ...unknownValues.length > 0 ? { unknownValueFields: unknownValues } : {}
23890
24134
  };
23891
24135
  }).meta({ id: "ManagedSettings" });
23892
24136
 
@@ -24150,7 +24394,23 @@ var SaveSettingsInput = external_exports.object({
24150
24394
  modelJudgeConsent: ModelJudgeConsentChoice,
24151
24395
  historySyncConsent: HistorySyncConsentChoice,
24152
24396
  vaultConsent: external_exports.string(),
24153
- vaultInlineReveal: external_exports.string()
24397
+ vaultInlineReveal: external_exports.string(),
24398
+ // Widened to `string` like its neighbours rather than typed as
24399
+ // `RedactFallback`, on this module's own layering rule: shape here, VALUE at
24400
+ // the call site, so the domain check receives the type it was written for.
24401
+ //
24402
+ // NOT because a narrower schema would reject differently. `parseActionInput`
24403
+ // is a `safeParse` wrapper and throws for no field schema, so either spelling
24404
+ // reaches a recoverable `{ ok: false }` and there is no rejected promise to
24405
+ // trade against. The real cost runs the other way and is the part worth
24406
+ // knowing: a value this schema admits and the domain enum then rejects lands
24407
+ // on the action's shared refusal, which names NO field, where a shape
24408
+ // rejection reaches `malformedInput` and names the schema key.
24409
+ redactFallback: external_exports.string(),
24410
+ // Shape only, the way the enum fields above are strings only: the RANGE is
24411
+ // `BodyRetention`'s and the action checks it there, so there is one place
24412
+ // that decides what a legal horizon is rather than two that can drift.
24413
+ bodyRetention: external_exports.object({ enabled: external_exports.boolean(), retainDays: external_exports.number() })
24154
24414
  });
24155
24415
  var AttachInput = external_exports.object({
24156
24416
  endpoint: external_exports.string(),
@@ -24322,6 +24582,52 @@ function reviewSeverityRank(reasons) {
24322
24582
  return Math.min(...reasons.map((r) => REVIEW_SEVERITY_RANK[r]));
24323
24583
  }
24324
24584
 
24585
+ // ../../packages/schema/src/zod/web-capture.ts
24586
+ var WebUsageSource = external_exports.enum(["site", "estimated", "none"]);
24587
+ var WebUsage = external_exports.object({
24588
+ inputTokens: external_exports.number().int().nonnegative().optional(),
24589
+ outputTokens: external_exports.number().int().nonnegative().optional(),
24590
+ cacheReadInputTokens: external_exports.number().int().nonnegative().optional(),
24591
+ cacheCreationInputTokens: external_exports.number().int().nonnegative().optional()
24592
+ });
24593
+ var WebToolCall = external_exports.object({
24594
+ toolUseId: external_exports.string().min(1),
24595
+ toolName: external_exports.string().min(1),
24596
+ target: external_exports.string().optional(),
24597
+ isError: external_exports.boolean().optional(),
24598
+ inputSize: external_exports.number().int().nonnegative().optional(),
24599
+ outputSize: external_exports.number().int().nonnegative().optional()
24600
+ });
24601
+ var WebExchange = external_exports.object({
24602
+ messageId: external_exports.string().min(1),
24603
+ startedAt: external_exports.iso.datetime(),
24604
+ model: external_exports.string().optional(),
24605
+ usage: WebUsage.optional(),
24606
+ usageSource: WebUsageSource,
24607
+ stopReason: external_exports.string().optional(),
24608
+ conversationId: external_exports.string().optional(),
24609
+ turnIndex: external_exports.number().int().nonnegative().optional(),
24610
+ toolCalls: external_exports.array(WebToolCall).default([]),
24611
+ // Absent when the adapter recovered no text. Capped by the caller at
24612
+ // RESPONSE_TEXT_MAX_BYTES; `truncated` records that the cap was reached, so a
24613
+ // short capture is never mistaken for a short reply.
24614
+ responseText: external_exports.string().optional(),
24615
+ truncated: external_exports.boolean().default(false)
24616
+ });
24617
+ var RESPONSE_TEXT_MAX_BYTES = 2 * 1024 * 1024;
24618
+ var WebCaptureStatus = external_exports.object({
24619
+ patched: external_exports.boolean(),
24620
+ live: external_exports.boolean(),
24621
+ blind: external_exports.boolean(),
24622
+ sendsSeenDom: external_exports.number().int().nonnegative(),
24623
+ exchangesSeenNet: external_exports.number().int().nonnegative(),
24624
+ parseFailures: external_exports.number().int().nonnegative(),
24625
+ unparsedBodies: external_exports.number().int().nonnegative(),
24626
+ // The adapter-declared JSON key paths that were absent from a real payload —
24627
+ // the earliest signal that a site's contract moved.
24628
+ shapeMisses: external_exports.array(external_exports.string()).default([])
24629
+ });
24630
+
24325
24631
  // ../../packages/persistence/src/paths.ts
24326
24632
  import {
24327
24633
  chmodSync,
@@ -24652,6 +24958,22 @@ function discardStore(file2, backup) {
24652
24958
  }
24653
24959
  }
24654
24960
 
24961
+ // ../../packages/persistence/src/internal/sql-functions.ts
24962
+ var utf8 = new TextDecoder();
24963
+ function akaLower(value) {
24964
+ if (value === null) return null;
24965
+ if (typeof value === "string") return value.toLowerCase();
24966
+ if (typeof value === "number" || typeof value === "bigint") return String(value).toLowerCase();
24967
+ return utf8.decode(value).toLowerCase();
24968
+ }
24969
+ function registerSqlFunctions(db) {
24970
+ db.function(
24971
+ "aka_lower",
24972
+ { deterministic: true, directOnly: true, useBigIntArguments: true },
24973
+ akaLower
24974
+ );
24975
+ }
24976
+
24655
24977
  // ../../packages/persistence/src/internal/sql-text.ts
24656
24978
  function escapeLikePattern(s) {
24657
24979
  return s.replace(/\\/g, "\\\\").replace(/%/g, "\\%").replace(/_/g, "\\_");
@@ -24736,6 +25058,11 @@ function schemaObjectExists(db, kind, name) {
24736
25058
  function indexExists(db, name) {
24737
25059
  return schemaObjectExists(db, "index", name);
24738
25060
  }
25061
+ function indexColumns(db, name) {
25062
+ if (!indexExists(db, name)) return [];
25063
+ const columns = db.prepare(`PRAGMA index_info(${name})`).all();
25064
+ return columns.map((c) => c.name).filter((c) => c !== null);
25065
+ }
24739
25066
  function columnNames(db, table, opts) {
24740
25067
  const pragma = opts?.includeGenerated ? "table_xinfo" : "table_info";
24741
25068
  const columns = db.prepare(`PRAGMA ${pragma}(${table})`).all();
@@ -24797,178 +25124,820 @@ function mapRowsTolerant(rows, map2) {
24797
25124
  return out;
24798
25125
  }
24799
25126
 
24800
- // ../../packages/persistence/src/migrations.ts
24801
- function describeObject(object2) {
24802
- return object2.kind === "column" ? `column ${object2.table}.${object2.name}` : `table ${object2.name}`;
24803
- }
24804
- function splitStatements(sql) {
24805
- return sql.split(/-->\s*statement-breakpoint/).map((s) => s.trim()).filter((s) => s.length > 0);
24806
- }
24807
- function createdIndexName(statement) {
24808
- const body = statement.replace(/^(?:\s*--[^\n]*\n?)+/, "").trimStart();
24809
- return /^CREATE (?:UNIQUE )?INDEX (?:IF NOT EXISTS )?`([^`]+)`/.exec(body)?.[1];
25127
+ // ../../packages/persistence/src/internal/outbox-lane.ts
25128
+ var OUTBOX_CAPTURE_EVENT_TYPES = ["prompt", "response", "tool_use"];
25129
+ var OUTBOX_CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25130
+
25131
+ // ../../packages/persistence/src/sync-failure.ts
25132
+ var SYNC_FAILURE_REASONS = SyncFailureReason.options;
25133
+ function syncFailureRejectCondition(column = "sync_failure") {
25134
+ const members2 = SYNC_FAILURE_REASONS.map((r) => `'${r}'`).join(", ");
25135
+ return `NEW.${column} IS NOT NULL AND NEW.${column} NOT IN (${members2})`;
24810
25136
  }
24811
- var LEGACY_DROP_MIGRATION_TAG = "0014_drop_legacy_events_findings";
24812
- function applyMigrations(db, file2) {
24813
- const legacyCount = db.prepare("PRAGMA user_version").get().user_version;
24814
- db.exec(
24815
- "CREATE TABLE IF NOT EXISTS migration_ledger (tag TEXT PRIMARY KEY, applied_at INTEGER NOT NULL)"
24816
- );
24817
- const applied = new Set(
24818
- db.prepare("SELECT tag FROM migration_ledger").all().map((r) => r.tag)
24819
- );
24820
- const preLedgerStore = applied.size === 0 && legacyCount > 0;
24821
- const record2 = db.prepare(
24822
- "INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)"
24823
- );
24824
- for (const [index, migration] of SQLITE_MIGRATIONS.entries()) {
24825
- if (applied.has(migration.tag)) continue;
24826
- if (migration.tag === LEGACY_DROP_MIGRATION_TAG) continue;
24827
- const evidence = evidenceObjects(migration.sql);
24828
- const present = evidence.filter((o) => evidenceExists(db, o));
24829
- if (present.length > 0 && present.length < evidence.length) {
24830
- const missing = evidence.filter((o) => !present.includes(o));
24831
- 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.`;
24832
- akaWarn(message);
24833
- throw new Error(`[aka] ${message}`);
24834
- }
24835
- const alreadyApplied = evidence.length > 0 ? present.length === evidence.length : preLedgerStore && index < legacyCount;
24836
- const wantsFkOff = /PRAGMA foreign_keys\s*=\s*OFF/i.test(migration.sql);
24837
- const statements = splitStatements(migration.sql);
24838
- if (wantsFkOff) db.exec("PRAGMA foreign_keys = OFF");
24839
- try {
24840
- withTransaction(
24841
- db,
24842
- () => {
24843
- for (const statement of statements) {
24844
- const indexName = createdIndexName(statement);
24845
- if (indexName === void 0) {
24846
- if (alreadyApplied) continue;
24847
- } else if (indexExists(db, indexName)) {
24848
- continue;
24849
- }
24850
- db.exec(statement);
24851
- }
24852
- if (wantsFkOff && !alreadyApplied) {
24853
- const violations = db.prepare("PRAGMA foreign_key_check").all();
24854
- if (violations.length > 0) {
24855
- throw new Error(
24856
- `[aka] sqlite migration ${migration.tag} left ${String(violations.length)} foreign-key violation(s); rolling back.`
24857
- );
24858
- }
24859
- }
24860
- record2.run(migration.tag, Date.now());
24861
- },
24862
- "IMMEDIATE"
24863
- );
24864
- } finally {
24865
- if (wantsFkOff) db.exec("PRAGMA foreign_keys = ON");
24866
- }
25137
+
25138
+ // ../../packages/persistence/src/repositories/history-sync.ts
25139
+ var STRUCTURAL_EVENT_TYPES = ["session", "llm_call", "tool_call"];
25140
+ var TYPE_LIST = STRUCTURAL_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25141
+ var CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_TYPE_LIST;
25142
+ var COUNTED_EVENT_TYPES = [
25143
+ ...STRUCTURAL_EVENT_TYPES,
25144
+ ...OUTBOX_CAPTURE_EVENT_TYPES
25145
+ ];
25146
+ var COUNTED_TYPE_LIST = COUNTED_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25147
+ var PARTITION_BUCKETS = `
25148
+ SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NULL THEN 1 ELSE 0 END) AS queued,
25149
+ SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NOT NULL THEN 1 ELSE 0 END) AS inProgress,
25150
+ SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS synced,
25151
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25152
+ AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
25153
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25154
+ AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached,
25155
+ -- Spelled as what it INCLUDES rather than what it excludes, so a reason
25156
+ -- added later lands in no bucket and fails the sum assertion, instead
25157
+ -- of silently joining this one.
25158
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25159
+ AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
25160
+ THEN 1 ELSE 0 END) AS failed,
25161
+ COUNT(*) AS total`;
25162
+ var COUNTED_SCOPE = `
25163
+ WHERE event_type IN (${COUNTED_TYPE_LIST})
25164
+ AND (
25165
+ event_type IN (${TYPE_LIST})
25166
+ OR synced_at IS NOT NULL
25167
+ OR outbox_owed = 1
25168
+ )`;
25169
+ var SKIPPED = -1;
25170
+ var ROW_COLUMNS = `id,
25171
+ parent_id AS parentId,
25172
+ root_session_id AS rootSessionId,
25173
+ event_type AS eventType,
25174
+ host_id AS hostId,
25175
+ harness_id AS harnessId,
25176
+ source_project_id AS sourceProjectId,
25177
+ started_at AS startedAt,
25178
+ ended_at AS endedAt,
25179
+ severity,
25180
+ priority,
25181
+ content,
25182
+ content_hash AS contentHash,
25183
+ attributes`;
25184
+ var SqliteHistorySyncRepository = class {
25185
+ constructor(db) {
25186
+ this.db = db;
25187
+ this.ensureRowStmt = db.prepare(`INSERT OR IGNORE INTO history_sync (id) VALUES (1)`);
25188
+ this.sessionsStmt = db.prepare(
25189
+ `SELECT COALESCE(root_session_id, id) AS sessionId, MIN(started_at) AS earliest
25190
+ FROM audit_events
25191
+ WHERE synced_at IS NULL
25192
+ AND event_type IN (${TYPE_LIST})
25193
+ AND started_at < :before
25194
+ GROUP BY sessionId
25195
+ ORDER BY earliest
25196
+ LIMIT :limit`
25197
+ );
25198
+ this.rowsStmt = db.prepare(
25199
+ `SELECT ${ROW_COLUMNS}
25200
+ FROM audit_events
25201
+ WHERE synced_at IS NULL
25202
+ AND event_type IN (${TYPE_LIST})
25203
+ AND started_at < :before
25204
+ AND COALESCE(root_session_id, id) = :sessionId
25205
+ ORDER BY (event_type = 'session') DESC, started_at
25206
+ LIMIT :limit`
25207
+ );
25208
+ this.captureRowsStmt = db.prepare(
25209
+ `SELECT ${ROW_COLUMNS}
25210
+ FROM audit_events
25211
+ WHERE synced_at IS NULL
25212
+ AND sync_claimed_at IS NULL
25213
+ AND outbox_owed = 1
25214
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25215
+ AND started_at < :before
25216
+ ORDER BY started_at
25217
+ LIMIT :limit`
25218
+ );
25219
+ this.markOwedStmt = db.prepare(
25220
+ `UPDATE audit_events SET outbox_owed = 1 WHERE id = :id AND synced_at IS NULL`
25221
+ );
25222
+ this.markCaptureBacklogOwedStmt = db.prepare(
25223
+ `UPDATE audit_events SET outbox_owed = 1
25224
+ WHERE synced_at IS NULL
25225
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25226
+ AND started_at < :before`
25227
+ );
25228
+ this.stampStmt = db.prepare(
25229
+ `UPDATE audit_events
25230
+ SET synced_at = :at,
25231
+ sync_claimed_at = NULL,
25232
+ sync_failed_at = :failedAt,
25233
+ sync_failure = :failure
25234
+ WHERE id = :id`
25235
+ );
25236
+ this.claimRowStmt = db.prepare(
25237
+ `UPDATE audit_events SET sync_claimed_at = :at WHERE id = :id AND synced_at IS NULL`
25238
+ );
25239
+ this.releaseRowStmt = db.prepare(
25240
+ `UPDATE audit_events SET sync_claimed_at = NULL WHERE id = :id`
25241
+ );
25242
+ this.releaseStaleClaimsStmt = db.prepare(
25243
+ `UPDATE audit_events SET sync_claimed_at = NULL
25244
+ WHERE sync_claimed_at IS NOT NULL AND sync_claimed_at < :staleBefore`
25245
+ );
25246
+ this.partitionStmt = db.prepare(`SELECT${PARTITION_BUCKETS}
25247
+ FROM audit_events${COUNTED_SCOPE}`);
25248
+ this.partitionByKindStmt = db.prepare(
25249
+ `SELECT event_type AS kind,${PARTITION_BUCKETS}
25250
+ FROM audit_events INDEXED BY idx_audit_events_sync${COUNTED_SCOPE}
25251
+ GROUP BY event_type`
25252
+ );
25253
+ this.countsStmt = db.prepare(
25254
+ `SELECT
25255
+ SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
25256
+ SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
25257
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25258
+ AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
25259
+ THEN 1 ELSE 0 END) AS skipped,
25260
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25261
+ AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
25262
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25263
+ AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached
25264
+ FROM audit_events
25265
+ WHERE event_type IN (${TYPE_LIST})`
25266
+ );
25267
+ this.captureSkipCountStmt = db.prepare(
25268
+ // EVERY sentinel capture, whatever the reason — deliberately NOT split the
25269
+ // way the structural totals are. The split exists because a refusal is
25270
+ // terminal only against the deployment that gave it, and the structural
25271
+ // re-arm frees it on a change of deployment. The capture lane has no such
25272
+ // escape: re-arming a capture would offer one deployment's undelivered
25273
+ // prompts, with their text, to a deployment that never saw them, which is
25274
+ // exactly what disownCapturesStmt exists to prevent. So on this lane both
25275
+ // reasons mean the same thing — this row will not be sent — and splitting
25276
+ // them would put refused captures in a bucket nothing reads and nothing
25277
+ // frees.
25278
+ `SELECT COUNT(*) AS skipped
25279
+ FROM audit_events
25280
+ WHERE synced_at = ${String(SKIPPED)}
25281
+ AND event_type IN (${CAPTURE_TYPE_LIST})`
25282
+ );
25283
+ this.fingerprintStmt = db.prepare(
25284
+ `SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
25285
+ FROM history_sync WHERE id = 1`
25286
+ );
25287
+ this.setFingerprintStmt = db.prepare(
25288
+ `UPDATE history_sync
25289
+ SET endpoint_fingerprint = :fingerprint, backlog_before = :backlogBefore
25290
+ WHERE id = 1`
25291
+ );
25292
+ this.disownCapturesStmt = db.prepare(
25293
+ `UPDATE audit_events SET outbox_owed = NULL
25294
+ WHERE outbox_owed IS NOT NULL
25295
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25296
+ AND started_at < :attachedAt`
25297
+ );
25298
+ this.rearmStmt = db.prepare(
25299
+ `UPDATE audit_events
25300
+ SET synced_at = NULL, sync_failed_at = NULL, sync_failure = NULL
25301
+ WHERE (synced_at > 0
25302
+ OR sync_failure IN ('deployment_refused', 'detached_undelivered'))
25303
+ AND event_type IN (${TYPE_LIST})`
25304
+ );
25305
+ this.claimStmt = db.prepare(
25306
+ `UPDATE history_sync
25307
+ SET owner_pid = :pid, owner_host = :host, acquired_at = :now, heartbeat_at = :now
25308
+ WHERE id = 1
25309
+ AND (owner_pid IS NULL
25310
+ OR heartbeat_at IS NULL
25311
+ OR heartbeat_at < :staleBefore
25312
+ OR heartbeat_at > :now)`
25313
+ );
25314
+ this.heartbeatStmt = db.prepare(
25315
+ `UPDATE history_sync SET heartbeat_at = :now WHERE id = 1 AND owner_pid = :pid`
25316
+ );
25317
+ this.releaseStmt = db.prepare(
25318
+ `UPDATE history_sync
25319
+ SET owner_pid = NULL, owner_host = NULL, acquired_at = NULL, heartbeat_at = NULL
25320
+ WHERE id = 1 AND owner_pid = :pid`
25321
+ );
25322
+ this.closeWindowStmt = db.prepare(
25323
+ `UPDATE audit_events
25324
+ SET synced_at = ${String(SKIPPED)},
25325
+ sync_failed_at = :at,
25326
+ sync_failure = 'detached_undelivered'
25327
+ WHERE synced_at IS NULL
25328
+ AND event_type IN (${TYPE_LIST})
25329
+ AND started_at >= :attachedAt`
25330
+ );
25331
+ this.releaseBoundaryStmt = db.prepare(
25332
+ `UPDATE history_sync SET backlog_before = NULL WHERE id = 1`
25333
+ );
25334
+ this.freezeBoundaryStmt = db.prepare(
25335
+ `UPDATE history_sync SET backlog_before = :backlogBefore WHERE id = 1`
25336
+ );
25337
+ this.leaseStmt = db.prepare(
25338
+ `SELECT owner_pid AS ownerPid, owner_host AS ownerHost,
25339
+ acquired_at AS acquiredAt, heartbeat_at AS heartbeatAt
25340
+ FROM history_sync WHERE id = 1`
25341
+ );
25342
+ this.inspectionsStmt = db.prepare(
25343
+ `SELECT d.rule_id AS ruleId,
25344
+ d.name AS ruleName,
25345
+ d.version AS ruleVersion,
25346
+ d.category AS category,
25347
+ d.severity AS severity,
25348
+ f.span_start AS spanStart,
25349
+ f.span_end AS spanEnd,
25350
+ f.masked_match AS maskedMatch,
25351
+ f.action_taken AS actionTaken,
25352
+ f.confidence AS confidence
25353
+ FROM inspection_findings f
25354
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
25355
+ WHERE f.audit_event_id = :auditEventId
25356
+ ORDER BY f.span_start, f.id`
25357
+ );
24867
25358
  }
24868
- if (legacyCount < SQLITE_MIGRATIONS.length) {
24869
- db.exec(`PRAGMA user_version = ${String(SQLITE_MIGRATIONS.length)}`);
25359
+ db;
25360
+ ensureRowStmt;
25361
+ sessionsStmt;
25362
+ rowsStmt;
25363
+ stampStmt;
25364
+ countsStmt;
25365
+ fingerprintStmt;
25366
+ setFingerprintStmt;
25367
+ rearmStmt;
25368
+ claimStmt;
25369
+ heartbeatStmt;
25370
+ releaseStmt;
25371
+ leaseStmt;
25372
+ inspectionsStmt;
25373
+ closeWindowStmt;
25374
+ releaseBoundaryStmt;
25375
+ freezeBoundaryStmt;
25376
+ captureRowsStmt;
25377
+ markOwedStmt;
25378
+ markCaptureBacklogOwedStmt;
25379
+ captureSkipCountStmt;
25380
+ disownCapturesStmt;
25381
+ partitionStmt;
25382
+ partitionByKindStmt;
25383
+ claimRowStmt;
25384
+ releaseRowStmt;
25385
+ releaseStaleClaimsStmt;
25386
+ /**
25387
+ * The masked detections recorded against one tool call.
25388
+ *
25389
+ * These travel with the event because a tool call's target is not
25390
+ * re-inspectable from the event alone — unlike a capture, where the text
25391
+ * itself is re-scannable. What crosses is the masked match and the rule that
25392
+ * produced it, never the value.
25393
+ */
25394
+ inspectionsFor(auditEventId) {
25395
+ return allRows(this.inspectionsStmt, { auditEventId });
24870
25396
  }
24871
- ensureSyncedAtColumn(db, "audit_events");
24872
- ensureScanLedgerTable(db);
24873
- ensureHistorySyncTable(db);
24874
- ensureBlockedDetectionsTable(db);
24875
- ensureRuleProbeCacheTable(db);
24876
- ensureWriteGateTrigger(db);
24877
- ensureTokenUsageColumns(db);
24878
- reconcileSourceProjectIds(db);
24879
- if (!applied.has(LEGACY_DROP_MIGRATION_TAG)) {
24880
- const drained = runLegacyHistoryBackfill(db);
24881
- if (drained) applyLegacyDropMigration(db, file2);
25397
+ /**
25398
+ * Sessions with structural rows still to send, oldest first.
25399
+ *
25400
+ * BOUNDED BY THE BACKLOG BOUNDARY, which is the whole correctness of this
25401
+ * read. Anything recorded after the machine attached is the live forward
25402
+ * path's to deliver; this drain exists for what was recorded before it, and a
25403
+ * row both paths send is at best a duplicate request and at worst — for a
25404
+ * session root — an overwrite of the inventory ids the live path resolved.
25405
+ */
25406
+ pendingSessions(limit, before) {
25407
+ return allRows(this.sessionsStmt, { limit, before }).map(
25408
+ (r) => r.sessionId
25409
+ );
24882
25410
  }
24883
- }
24884
- function readLegacyTables(db) {
24885
- let holdsRows = false;
24886
- const marks = [];
24887
- for (const table of ["events", "findings"]) {
24888
- try {
24889
- const row = db.prepare(`SELECT count(*) AS n, ifnull(max(rowid), -1) AS hi FROM ${table}`).get();
24890
- if (row === void 0) {
24891
- holdsRows = true;
24892
- marks.push(`${table}:unreadable`);
24893
- continue;
24894
- }
24895
- if (row.n > 0) holdsRows = true;
24896
- marks.push(`${table}:${String(row.n)}:${String(row.hi)}`);
24897
- } catch {
24898
- holdsRows = true;
24899
- marks.push(`${table}:unreadable`);
24900
- }
25411
+ /** One session's undelivered structural rows within the backlog, root first. */
25412
+ pendingRows(sessionId, limit, before) {
25413
+ return allRows(this.rowsStmt, { sessionId, limit, before });
24901
25414
  }
24902
- return { holdsRows, mark: marks.join("|") };
24903
- }
24904
- function applyLegacyDropMigration(db, file2) {
24905
- const migration = SQLITE_MIGRATIONS.find((m) => m.tag === LEGACY_DROP_MIGRATION_TAG);
24906
- if (!migration) return;
24907
- const before = file2 === void 0 ? void 0 : readLegacyTables(db);
24908
- if (file2 !== void 0 && before?.holdsRows === true) {
24909
- try {
24910
- backupBeforeLegacyDrop(db, file2);
24911
- } catch (error61) {
24912
- akaWarn(`legacy events/findings backup failed; deferring the drop: ${String(error61)}`);
24913
- return;
24914
- }
25415
+ /**
25416
+ * Captures this machine still owes the deployment, oldest first.
25417
+ *
25418
+ * Selected by the `outbox_owed` marker the attached forward path writes, not
25419
+ * by a time window — see captureRowsStmt for why a window could not express
25420
+ * this. `before` is the grace window that leaves a just-recorded capture to
25421
+ * the live path.
25422
+ */
25423
+ pendingCaptureRows(limit, before) {
25424
+ return allRows(this.captureRowsStmt, { limit, before });
24915
25425
  }
24916
- try {
25426
+ /**
25427
+ * Record that a capture is OWED to the deployment.
25428
+ *
25429
+ * Written by the attached forward path when a live send did not confirm
25430
+ * delivery, and read by the drain as the whole of its eligibility test. It is
25431
+ * a fact rather than an inference: the machine was attached, the send did not
25432
+ * land, so the row is owed — which no time window can state, because the same
25433
+ * window that holds the rows a past attachment left owed also holds every
25434
+ * capture recorded while the machine was DETACHED, and those were never
25435
+ * offered to anyone.
25436
+ *
25437
+ * Idempotent, and never un-set: `markSynced` settling the row is what takes it
25438
+ * out of the drain's read.
25439
+ */
25440
+ markCaptureOwed(id) {
25441
+ this.markOwedStmt.run({ id });
25442
+ }
25443
+ /**
25444
+ * Mark every capture already on disk as owed, as of `before`.
25445
+ *
25446
+ * The consent-time backfill, called once from `aka attach` when a human
25447
+ * grants existing-history consent — never from an ongoing drain pass, and
25448
+ * never inferred from a boundary that could later move. `before` is the
25449
+ * caller's own "now" at the moment consent was granted, so what this marks
25450
+ * is exactly the backlog the consent prompt already counted, not whatever a
25451
+ * later re-attach or key rotation might widen it to.
25452
+ *
25453
+ * Returns how many rows matched, for the caller to log or test against. Not a
25454
+ * count of NEWLY marked rows — a row still unsynced from an earlier call
25455
+ * matches again and is counted again, the same as `UPDATE`'s own `changes`.
25456
+ */
25457
+ markCaptureBacklogOwed(before) {
25458
+ return Number(this.markCaptureBacklogOwedStmt.run({ before }).changes);
25459
+ }
25460
+ /**
25461
+ * Record delivery. Called only AFTER the far side has accepted the rows.
25462
+ *
25463
+ * CLEARS any failure reason in the same statement. A row that failed against
25464
+ * one deployment and then landed is delivered, and leaving the reason behind
25465
+ * would leave the store holding two contradictory answers about one row —
25466
+ * with the surface free to render either.
25467
+ */
25468
+ markSynced(ids, atMs) {
25469
+ this.stampAll(ids, atMs, null);
25470
+ }
25471
+ /**
25472
+ * Record that THIS MACHINE cannot express the row on the wire.
25473
+ *
25474
+ * Reserved for a local defect — a row that cannot be rebuilt into a valid
25475
+ * payload, or a body the client itself refused to send. It fails identically
25476
+ * against every deployment, so it is terminal everywhere and the re-arm leaves
25477
+ * it alone. A row that merely failed to REACH the deployment stays NULL, so it
25478
+ * is retried; marking those would turn one outage into permanent data loss.
25479
+ */
25480
+ markSkipped(ids, atMs) {
25481
+ this.stampAll(ids, SKIPPED, "payload_invalid", atMs);
25482
+ }
25483
+ /**
25484
+ * Record that THIS DEPLOYMENT refused the row.
25485
+ *
25486
+ * The same sentinel as `markSkipped`, and deliberately so: both stop the row
25487
+ * being re-offered on this lane, and `synced_at` goes on answering whether a
25488
+ * row is outstanding rather than why. What separates them is the reason, and
25489
+ * what the reason buys is the re-arm — a refusal is one deployment's verdict
25490
+ * on one body, so it is terminal only for as long as this machine points at
25491
+ * that deployment, and `rearmFor` clears it when the deployment changes.
25492
+ *
25493
+ * Leaving such a row NULL instead would be worse than the loss it replaces:
25494
+ * these reads carry no cursor, so an unstamped row the deployment refuses is
25495
+ * the head of every subsequent page, and the lane stalls behind it for ever.
25496
+ */
25497
+ markRefused(ids, atMs) {
25498
+ this.stampAll(ids, SKIPPED, "deployment_refused", atMs);
25499
+ }
25500
+ eachInTransaction(ids, run) {
25501
+ if (ids.length === 0) return;
24917
25502
  withTransaction(
24918
- db,
25503
+ this.db,
24919
25504
  () => {
24920
- const alreadyDropped = db.prepare("SELECT 1 FROM migration_ledger WHERE tag = ?").get(migration.tag);
24921
- if (alreadyDropped) return;
24922
- if (before !== void 0 && readLegacyTables(db).mark !== before.mark) {
24923
- akaWarn(
24924
- "legacy events/findings rows changed after the pre-drop snapshot decision; deferring the drop so the next open can copy them first."
24925
- );
24926
- return;
24927
- }
24928
- for (const statement of splitStatements(migration.sql)) {
24929
- db.exec(statement);
24930
- }
24931
- db.prepare("INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)").run(
24932
- migration.tag,
24933
- Date.now()
24934
- );
25505
+ for (const id of ids) run(id);
24935
25506
  },
24936
25507
  "IMMEDIATE"
24937
25508
  );
24938
- } catch (error61) {
24939
- akaWarn(`legacy events/findings drop failed; deferring: ${String(error61)}`);
24940
25509
  }
24941
- }
24942
- function backupBeforeLegacyDrop(db, file2) {
24943
- reapStalePartials(file2);
24944
- const backup = backupPath(file2, "pre-drop");
24945
- snapshotStore(db, backup);
24946
- return backup;
24947
- }
24948
- var TOKEN_USAGE_COLUMNS = [
24949
- {
24950
- name: "input_tokens",
24951
- ddl: "ALTER TABLE audit_events ADD COLUMN input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.input_tokens')) VIRTUAL"
24952
- },
24953
- {
24954
- name: "output_tokens",
24955
- ddl: "ALTER TABLE audit_events ADD COLUMN output_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.output_tokens')) VIRTUAL"
24956
- },
24957
- {
24958
- name: "cache_creation_input_tokens",
24959
- ddl: "ALTER TABLE audit_events ADD COLUMN cache_creation_input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.cache_creation_input_tokens')) VIRTUAL"
24960
- },
24961
- {
24962
- name: "cache_read_input_tokens",
24963
- ddl: "ALTER TABLE audit_events ADD COLUMN cache_read_input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.cache_read_input_tokens')) VIRTUAL"
24964
- },
24965
- {
24966
- name: "model",
24967
- ddl: "ALTER TABLE audit_events ADD COLUMN model text GENERATED ALWAYS AS (json_extract(attributes, '$.model')) VIRTUAL"
24968
- },
24969
- {
24970
- name: "provider",
24971
- ddl: "ALTER TABLE audit_events ADD COLUMN provider text GENERATED ALWAYS AS (json_extract(attributes, '$.provider')) VIRTUAL"
25510
+ stampAll(ids, value, failure, failedAtMs) {
25511
+ if (ids.length === 0) return;
25512
+ const failedAt = failure === null ? null : failedAtMs ?? null;
25513
+ withTransaction(
25514
+ this.db,
25515
+ () => {
25516
+ for (const id of ids) this.stampStmt.run({ at: value, failedAt, failure, id });
25517
+ },
25518
+ "IMMEDIATE"
25519
+ );
25520
+ }
25521
+ /**
25522
+ * Claim rows as in-flight.
25523
+ *
25524
+ * Advisory in exactly the sense the lease is: it records that a send is in
25525
+ * progress so a surface can say so, and a lost claim costs a row showing as
25526
+ * queued while it is actually being sent. It is not exclusion — the far side
25527
+ * settles a duplicate on the row id.
25528
+ */
25529
+ claimRows(ids, atMs) {
25530
+ this.eachInTransaction(ids, (id) => this.claimRowStmt.run({ at: atMs, id }));
25531
+ }
25532
+ /** Give back a claim without settling — the send failed, the row is queued again. */
25533
+ releaseRows(ids) {
25534
+ this.eachInTransaction(ids, (id) => this.releaseRowStmt.run({ id }));
25535
+ }
25536
+ /**
25537
+ * Clear claims older than `staleBefore`, and report how many were cleared.
25538
+ *
25539
+ * A process killed between claiming and settling leaves rows claimed with
25540
+ * nothing left to settle them. Without this they read as "sending" for ever.
25541
+ */
25542
+ releaseStaleClaims(staleBefore) {
25543
+ return Number(this.releaseStaleClaimsStmt.run({ staleBefore }).changes);
25544
+ }
25545
+ /**
25546
+ * Every tracked row in exactly one delivery state.
25547
+ *
25548
+ * Takes no boundary on purpose. The boundary answers "what should the drain
25549
+ * pick up now", which is a different question from "what state is this row
25550
+ * in" — and a machine that has never attached has no boundary to pass, so
25551
+ * requiring one would force a caller to invent one and report the whole store
25552
+ * as queued.
25553
+ */
25554
+ /**
25555
+ * The same partition, one row per kind that a lane carries.
25556
+ *
25557
+ * A kind with nothing to report is ABSENT rather than a row of zeros: the
25558
+ * scope decides which rows exist at all, so a kind that has never been
25559
+ * recorded — or whose captures nobody ever owed — produces no group. A caller
25560
+ * rendering a fixed list of kinds must therefore treat a missing one as "no
25561
+ * rows", never as "zero sent"; the two look identical in a bar and mean
25562
+ * different things.
25563
+ */
25564
+ partitionByKind() {
25565
+ return allRows(
25566
+ this.partitionByKindStmt,
25567
+ {}
25568
+ ).map((row) => ({
25569
+ kind: row.kind,
25570
+ queued: row.queued ?? 0,
25571
+ inProgress: row.inProgress ?? 0,
25572
+ synced: row.synced ?? 0,
25573
+ failed: row.failed ?? 0,
25574
+ refused: row.refused ?? 0,
25575
+ detached: row.detached ?? 0,
25576
+ total: row.total ?? 0
25577
+ }));
25578
+ }
25579
+ partition() {
25580
+ const row = getRow(this.partitionStmt, {});
25581
+ return {
25582
+ queued: row?.queued ?? 0,
25583
+ inProgress: row?.inProgress ?? 0,
25584
+ synced: row?.synced ?? 0,
25585
+ failed: row?.failed ?? 0,
25586
+ refused: row?.refused ?? 0,
25587
+ detached: row?.detached ?? 0,
25588
+ total: row?.total ?? 0
25589
+ };
25590
+ }
25591
+ /** `pending` counts only what is inside the backlog; sent and skipped are totals. */
25592
+ counts(before) {
25593
+ const row = getRow(this.countsStmt, { before });
25594
+ const captures = getRow(this.captureSkipCountStmt);
25595
+ return {
25596
+ pending: row?.pending ?? 0,
25597
+ sent: row?.sent ?? 0,
25598
+ skipped: row?.skipped ?? 0,
25599
+ refused: row?.refused ?? 0,
25600
+ detached: row?.detached ?? 0,
25601
+ capturesSkipped: captures?.skipped ?? 0
25602
+ };
25603
+ }
25604
+ /**
25605
+ * The deployment the current stamps were made against, and where its backlog
25606
+ * ends.
25607
+ *
25608
+ * READ-ONLY. An absent row reads as an absent deployment, which is what a
25609
+ * machine that has never drained is — and every writer below seeds the row
25610
+ * before it needs one, so nothing depends on this creating it. Keeping the
25611
+ * write off the gate path matters because the gate runs on every pass while a
25612
+ * write has to take the database's write lock.
25613
+ */
25614
+ deployment() {
25615
+ const row = getRow(
25616
+ this.fingerprintStmt
25617
+ );
25618
+ return {
25619
+ fingerprint: row?.fingerprint ?? void 0,
25620
+ backlogBefore: row?.backlogBefore ?? void 0
25621
+ };
25622
+ }
25623
+ /**
25624
+ * Point the ledger at a different deployment, discarding what it recorded
25625
+ * about the previous one.
25626
+ *
25627
+ * Delivery is a fact about ONE recipient: rows sent to the deployment a
25628
+ * machine has just left are undelivered as far as the new one is concerned.
25629
+ * All four in one transaction, so a crash between them cannot leave stamps
25630
+ * attributed to the wrong deployment, a boundary that belongs to another, or
25631
+ * a disown with no re-mark to follow it.
25632
+ *
25633
+ * The boundary is written HERE and only here, which is what freezes it: a
25634
+ * re-attach to the SAME deployment (a key rotation) leaves the fingerprint
25635
+ * unchanged, so this never runs and the backlog does not widen back over rows
25636
+ * the live path has since delivered.
25637
+ *
25638
+ * `backfillCapturesBefore` is the caller's OWN "now" at the instant a human
25639
+ * granted existing-history consent for the deployment this call is arming —
25640
+ * a DIFFERENT instant from `backlogBefore`: the re-mark boundary is the GRANT
25641
+ * instant, `backlogBefore` is the ATTACH instant, and the two can be far
25642
+ * apart. Passed only when that grant is valid, since this method has no way
25643
+ * to check consent itself and must not mark a row owed for a machine that
25644
+ * never agreed to it. Applied AFTER the disown above, in the SAME
25645
+ * transaction: what the disown clears is every marker below `backlogBefore`,
25646
+ * which includes this deployment's OWN pre-attach rows — `aka attach` calls
25647
+ * `seedCaptureBacklogOwed` at the attach instant, so every row it marks sits
25648
+ * on the cleared side of that bound — and the re-mark in the same
25649
+ * transaction is what puts those rows back. A crash between the two cannot
25650
+ * strand the ledger disowned with nothing re-marked — the transaction either
25651
+ * lands whole or not at all, and a fingerprint mismatch that has not yet
25652
+ * committed re-enters this method on the very next pass. Omit it (the
25653
+ * structural-only tests do) to exercise the disown in isolation.
25654
+ *
25655
+ * The disown is bounded by `backlogBefore`, which is what keeps it from
25656
+ * touching a marker the NEW deployment's OWN live path has already set: B's
25657
+ * live path can mark a capture owed from the moment `aka attach` writes the
25658
+ * descriptor, before the drain's first pass ever reaches this method, and
25659
+ * such a row sits at or after the bound rather than below it. What keeps the
25660
+ * disown from eating THIS SAME CALL's own re-mark is the order, not the
25661
+ * bound — disown runs first, re-mark second, both inside the one
25662
+ * transaction above.
25663
+ */
25664
+ rearmFor(fingerprint, backlogBefore, backfillCapturesBefore) {
25665
+ this.ensureRowStmt.run();
25666
+ withTransaction(
25667
+ this.db,
25668
+ () => {
25669
+ const previous = getRow(this.fingerprintStmt)?.fingerprint;
25670
+ this.rearmStmt.run();
25671
+ if (previous !== null && previous !== void 0 && previous !== fingerprint) {
25672
+ this.disownCapturesStmt.run({ attachedAt: backlogBefore });
25673
+ }
25674
+ if (backfillCapturesBefore !== void 0) {
25675
+ this.markCaptureBacklogOwedStmt.run({ before: backfillCapturesBefore });
25676
+ }
25677
+ this.setFingerprintStmt.run({ fingerprint, backlogBefore });
25678
+ },
25679
+ "IMMEDIATE"
25680
+ );
25681
+ }
25682
+ /**
25683
+ * End the attached period: hand its rows to the live path, and release the
25684
+ * boundary so the next attachment can freeze a new one.
25685
+ *
25686
+ * WITHOUT THIS, a detach and a re-attach to the same deployment leave a window
25687
+ * nothing delivers. The fingerprint is unchanged, so the boundary is never
25688
+ * re-frozen and stays at the FIRST attachment — while nothing forwards at all
25689
+ * during the detached period, because the machine is not attached. Rows
25690
+ * recorded in that window sit after the boundary and before the re-attach, so
25691
+ * neither path takes them, and the pending count reports none outstanding.
25692
+ *
25693
+ * WHAT IT RECORDS, and what it deliberately does not. These rows were the
25694
+ * closing attachment's to deliver and are no longer outstanding — that is what
25695
+ * lets the boundary move. It is NOT a claim that any of them arrived, and the
25696
+ * distinction is not academic: this used to write a delivery TIME, which every
25697
+ * read treats as delivery, so one detach turned a window of undelivered rows
25698
+ * into a window of delivered ones and no surface could tell. It writes the
25699
+ * skip sentinel and a reason of its own instead, so "no longer owed" and
25700
+ * "received" stop being the same fact.
25701
+ *
25702
+ * A change of deployment still frees them (see the re-arm), because the next
25703
+ * deployment has seen none of this machine's history — so the rows reach it
25704
+ * exactly as they did when this wrote a delivery time.
25705
+ *
25706
+ * ONE TRANSACTION, so a crash cannot release the boundary while leaving the
25707
+ * window unstamped — that half-state would re-send the whole attached period
25708
+ * on the next attach, which is the failure the boundary exists to prevent.
25709
+ */
25710
+ closeAttachedWindow(attachedAtMs, atMs) {
25711
+ this.ensureRowStmt.run();
25712
+ withTransaction(
25713
+ this.db,
25714
+ () => {
25715
+ const row = getRow(this.fingerprintStmt);
25716
+ const from = row?.backlogBefore ?? attachedAtMs;
25717
+ this.closeWindowStmt.run({ at: atMs, attachedAt: from });
25718
+ this.releaseBoundaryStmt.run();
25719
+ },
25720
+ "IMMEDIATE"
25721
+ );
25722
+ }
25723
+ /**
25724
+ * Freeze a boundary for the deployment already on file, KEEPING the stamps.
25725
+ *
25726
+ * The re-attach half of the above. Distinct from `rearmFor`, which is for a
25727
+ * different deployment and therefore discards what was delivered to the old
25728
+ * one: here the recipient is the same, so everything already sent to it stays
25729
+ * sent.
25730
+ */
25731
+ freezeBoundary(backlogBefore) {
25732
+ this.ensureRowStmt.run();
25733
+ this.freezeBoundaryStmt.run({ backlogBefore });
25734
+ }
25735
+ /** Take the claim, or report that someone live already holds it. */
25736
+ claim(pid, host, nowMs, staleAfterMs) {
25737
+ this.ensureRowStmt.run();
25738
+ let taken = false;
25739
+ withTransaction(
25740
+ this.db,
25741
+ () => {
25742
+ const result = this.claimStmt.run({
25743
+ pid,
25744
+ host,
25745
+ now: nowMs,
25746
+ staleBefore: nowMs - staleAfterMs
25747
+ });
25748
+ taken = result.changes === 1;
25749
+ },
25750
+ "IMMEDIATE"
25751
+ );
25752
+ return taken;
25753
+ }
25754
+ /** Say the holder is still alive. A no-op once the claim has moved on. */
25755
+ heartbeat(pid, nowMs) {
25756
+ this.heartbeatStmt.run({ now: nowMs, pid });
25757
+ }
25758
+ /** Give the claim up. Scoped to this holder, so a taken-over claim is left be. */
25759
+ release(pid) {
25760
+ this.releaseStmt.run({ pid });
25761
+ }
25762
+ /** Who holds the claim, if anyone. Read-only, for the same reason as above. */
25763
+ lease() {
25764
+ return getRow(this.leaseStmt);
25765
+ }
25766
+ };
25767
+
25768
+ // ../../packages/persistence/src/migrations.ts
25769
+ function describeObject(object2) {
25770
+ return object2.kind === "column" ? `column ${object2.table}.${object2.name}` : `table ${object2.name}`;
25771
+ }
25772
+ function splitStatements(sql) {
25773
+ return sql.split(/-->\s*statement-breakpoint/).map((s) => s.trim()).filter((s) => s.length > 0);
25774
+ }
25775
+ function createdIndexName(statement) {
25776
+ const body = statement.replace(/^(?:\s*--[^\n]*\n?)+/, "").trimStart();
25777
+ return /^CREATE (?:UNIQUE )?INDEX (?:IF NOT EXISTS )?`([^`]+)`/.exec(body)?.[1];
25778
+ }
25779
+ var LEGACY_DROP_MIGRATION_TAG = "0014_drop_legacy_events_findings";
25780
+ function applyMigrations(db, file2, options = {}) {
25781
+ const legacyCount = db.prepare("PRAGMA user_version").get().user_version;
25782
+ db.exec(
25783
+ "CREATE TABLE IF NOT EXISTS migration_ledger (tag TEXT PRIMARY KEY, applied_at INTEGER NOT NULL)"
25784
+ );
25785
+ const applied = new Set(
25786
+ db.prepare("SELECT tag FROM migration_ledger").all().map((r) => r.tag)
25787
+ );
25788
+ const preLedgerStore = applied.size === 0 && legacyCount > 0;
25789
+ const record2 = db.prepare(
25790
+ "INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)"
25791
+ );
25792
+ for (const [index, migration] of SQLITE_MIGRATIONS.entries()) {
25793
+ if (applied.has(migration.tag)) continue;
25794
+ if (options.skipTags?.has(migration.tag) === true) continue;
25795
+ if (migration.tag === LEGACY_DROP_MIGRATION_TAG) continue;
25796
+ const evidence = evidenceObjects(migration.sql);
25797
+ const present = evidence.filter((o) => evidenceExists(db, o));
25798
+ if (present.length > 0 && present.length < evidence.length) {
25799
+ const missing = evidence.filter((o) => !present.includes(o));
25800
+ 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.`;
25801
+ akaWarn(message);
25802
+ throw new Error(`[aka] ${message}`);
25803
+ }
25804
+ const alreadyApplied = evidence.length > 0 ? present.length === evidence.length : preLedgerStore && index < legacyCount;
25805
+ const wantsFkOff = /PRAGMA foreign_keys\s*=\s*OFF/i.test(migration.sql);
25806
+ const statements = splitStatements(migration.sql);
25807
+ if (wantsFkOff) db.exec("PRAGMA foreign_keys = OFF");
25808
+ try {
25809
+ withTransaction(
25810
+ db,
25811
+ () => {
25812
+ for (const statement of statements) {
25813
+ const indexName = createdIndexName(statement);
25814
+ if (indexName === void 0) {
25815
+ if (alreadyApplied) continue;
25816
+ } else if (indexExists(db, indexName)) {
25817
+ continue;
25818
+ }
25819
+ db.exec(statement);
25820
+ }
25821
+ if (wantsFkOff && !alreadyApplied) {
25822
+ const violations = db.prepare("PRAGMA foreign_key_check").all();
25823
+ if (violations.length > 0) {
25824
+ throw new Error(
25825
+ `[aka] sqlite migration ${migration.tag} left ${String(violations.length)} foreign-key violation(s); rolling back.`
25826
+ );
25827
+ }
25828
+ }
25829
+ record2.run(migration.tag, Date.now());
25830
+ },
25831
+ "IMMEDIATE"
25832
+ );
25833
+ } finally {
25834
+ if (wantsFkOff) db.exec("PRAGMA foreign_keys = ON");
25835
+ }
25836
+ }
25837
+ if (legacyCount < SQLITE_MIGRATIONS.length) {
25838
+ db.exec(`PRAGMA user_version = ${String(SQLITE_MIGRATIONS.length)}`);
25839
+ }
25840
+ ensureSyncedAtColumn(db, "audit_events");
25841
+ ensureScanLedgerTable(db);
25842
+ ensureHistorySyncTable(db);
25843
+ ensureBlockedDetectionsTable(db);
25844
+ ensureRuleProbeCacheTable(db);
25845
+ ensureWriteGateTrigger(db);
25846
+ ensureTokenUsageColumns(db);
25847
+ reconcileSourceProjectIds(db);
25848
+ if (!applied.has(LEGACY_DROP_MIGRATION_TAG)) {
25849
+ const drained = runLegacyHistoryBackfill(db);
25850
+ if (drained) applyLegacyDropMigration(db, file2);
25851
+ }
25852
+ }
25853
+ function readLegacyTables(db) {
25854
+ let holdsRows = false;
25855
+ const marks = [];
25856
+ for (const table of ["events", "findings"]) {
25857
+ try {
25858
+ const row = db.prepare(`SELECT count(*) AS n, ifnull(max(rowid), -1) AS hi FROM ${table}`).get();
25859
+ if (row === void 0) {
25860
+ holdsRows = true;
25861
+ marks.push(`${table}:unreadable`);
25862
+ continue;
25863
+ }
25864
+ if (row.n > 0) holdsRows = true;
25865
+ marks.push(`${table}:${String(row.n)}:${String(row.hi)}`);
25866
+ } catch {
25867
+ holdsRows = true;
25868
+ marks.push(`${table}:unreadable`);
25869
+ }
25870
+ }
25871
+ return { holdsRows, mark: marks.join("|") };
25872
+ }
25873
+ function applyLegacyDropMigration(db, file2) {
25874
+ const migration = SQLITE_MIGRATIONS.find((m) => m.tag === LEGACY_DROP_MIGRATION_TAG);
25875
+ if (!migration) return;
25876
+ const before = file2 === void 0 ? void 0 : readLegacyTables(db);
25877
+ if (file2 !== void 0 && before?.holdsRows === true) {
25878
+ try {
25879
+ backupBeforeLegacyDrop(db, file2);
25880
+ } catch (error61) {
25881
+ akaWarn(`legacy events/findings backup failed; deferring the drop: ${String(error61)}`);
25882
+ return;
25883
+ }
25884
+ }
25885
+ try {
25886
+ withTransaction(
25887
+ db,
25888
+ () => {
25889
+ const alreadyDropped = db.prepare("SELECT 1 FROM migration_ledger WHERE tag = ?").get(migration.tag);
25890
+ if (alreadyDropped) return;
25891
+ if (before !== void 0 && readLegacyTables(db).mark !== before.mark) {
25892
+ akaWarn(
25893
+ "legacy events/findings rows changed after the pre-drop snapshot decision; deferring the drop so the next open can copy them first."
25894
+ );
25895
+ return;
25896
+ }
25897
+ for (const statement of splitStatements(migration.sql)) {
25898
+ db.exec(statement);
25899
+ }
25900
+ db.prepare("INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)").run(
25901
+ migration.tag,
25902
+ Date.now()
25903
+ );
25904
+ },
25905
+ "IMMEDIATE"
25906
+ );
25907
+ } catch (error61) {
25908
+ akaWarn(`legacy events/findings drop failed; deferring: ${String(error61)}`);
25909
+ }
25910
+ }
25911
+ function backupBeforeLegacyDrop(db, file2) {
25912
+ reapStalePartials(file2);
25913
+ const backup = backupPath(file2, "pre-drop");
25914
+ snapshotStore(db, backup);
25915
+ return backup;
25916
+ }
25917
+ var TOKEN_USAGE_COLUMNS = [
25918
+ {
25919
+ name: "input_tokens",
25920
+ ddl: "ALTER TABLE audit_events ADD COLUMN input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.input_tokens')) VIRTUAL"
25921
+ },
25922
+ {
25923
+ name: "output_tokens",
25924
+ ddl: "ALTER TABLE audit_events ADD COLUMN output_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.output_tokens')) VIRTUAL"
25925
+ },
25926
+ {
25927
+ name: "cache_creation_input_tokens",
25928
+ ddl: "ALTER TABLE audit_events ADD COLUMN cache_creation_input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.cache_creation_input_tokens')) VIRTUAL"
25929
+ },
25930
+ {
25931
+ name: "cache_read_input_tokens",
25932
+ ddl: "ALTER TABLE audit_events ADD COLUMN cache_read_input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.cache_read_input_tokens')) VIRTUAL"
25933
+ },
25934
+ {
25935
+ name: "model",
25936
+ ddl: "ALTER TABLE audit_events ADD COLUMN model text GENERATED ALWAYS AS (json_extract(attributes, '$.model')) VIRTUAL"
25937
+ },
25938
+ {
25939
+ name: "provider",
25940
+ ddl: "ALTER TABLE audit_events ADD COLUMN provider text GENERATED ALWAYS AS (json_extract(attributes, '$.provider')) VIRTUAL"
24972
25941
  }
24973
25942
  ];
24974
25943
  function ensureTokenUsageColumns(db) {
@@ -25229,10 +26198,62 @@ function ensureSyncedAtColumn(db, table) {
25229
26198
  if (!columns.includes("outbox_owed")) {
25230
26199
  db.exec(`ALTER TABLE ${table} ADD COLUMN outbox_owed integer`);
25231
26200
  }
26201
+ if (!columns.includes("sync_failed_at")) {
26202
+ db.exec(`ALTER TABLE ${table} ADD COLUMN sync_failed_at integer`);
26203
+ }
26204
+ if (!columns.includes("sync_failure")) {
26205
+ withTransaction(
26206
+ db,
26207
+ () => {
26208
+ db.exec(`ALTER TABLE ${table} ADD COLUMN sync_failure text`);
26209
+ db.exec(
26210
+ `UPDATE ${table} SET synced_at = NULL
26211
+ WHERE synced_at = -1
26212
+ AND event_type IN (${COUNTED_EVENT_TYPES.map((t) => `'${t}'`).join(", ")})`
26213
+ );
26214
+ },
26215
+ "IMMEDIATE"
26216
+ );
26217
+ }
25232
26218
  db.exec(
25233
- `CREATE INDEX IF NOT EXISTS idx_audit_events_sync
25234
- ON audit_events (event_type, synced_at, sync_claimed_at, started_at)`
26219
+ `CREATE TRIGGER IF NOT EXISTS aka_sync_failure_guard
26220
+ BEFORE UPDATE OF sync_failure ON ${table}
26221
+ WHEN ${syncFailureRejectCondition()}
26222
+ BEGIN SELECT RAISE(ABORT, 'sync_failure is not one of the recorded reasons'); END`
25235
26223
  );
26224
+ const syncIndexColumns = [
26225
+ "event_type",
26226
+ "synced_at",
26227
+ "sync_claimed_at",
26228
+ "started_at",
26229
+ // Appended LAST on purpose. The delivery-state read now projects it, so it
26230
+ // has to be in the index for the read to stay covered — but putting it
26231
+ // ahead of `started_at` would reorder the prefix the structural drain's
26232
+ // reads match on.
26233
+ "sync_failure"
26234
+ // `outbox_owed` is DELIBERATELY ABSENT, and it was measured both ways.
26235
+ //
26236
+ // The delivery-state read tests it — a capture's state depends on whether a
26237
+ // live forward marked it owed — so carrying it here makes that read covering
26238
+ // rather than a row fetch per row: 16 ms against 40 ms on a real 6 GB store.
26239
+ // But a sixth column changes what the planner charges for this index, and
26240
+ // with no ANALYZE statistics it plans from schema shape alone: measured, it
26241
+ // then stops choosing the per-session index for the token rollup and walks
26242
+ // every `llm_call` in the store through the event-type index instead. That
26243
+ // read grows with the store; this one does not.
26244
+ //
26245
+ // 40 ms on the largest store measured, once per render, is a cost worth
26246
+ // paying to leave every other read's plan where it was.
26247
+ ];
26248
+ const currentSyncIndex = indexColumns(db, "idx_audit_events_sync");
26249
+ const syncIndexMatches = currentSyncIndex.length === syncIndexColumns.length && currentSyncIndex.every((column, i) => column === syncIndexColumns[i]);
26250
+ if (!syncIndexMatches) {
26251
+ db.exec("DROP INDEX IF EXISTS idx_audit_events_sync");
26252
+ db.exec(
26253
+ `CREATE INDEX idx_audit_events_sync
26254
+ ON audit_events (${syncIndexColumns.join(", ")})`
26255
+ );
26256
+ }
25236
26257
  db.exec(
25237
26258
  `CREATE INDEX IF NOT EXISTS idx_audit_outbox_owed
25238
26259
  ON audit_events (event_type, synced_at, sync_claimed_at, started_at) WHERE outbox_owed = 1`
@@ -25454,7 +26475,11 @@ function buildAuditEvent(row) {
25454
26475
  link: linkParsed?.success ? linkParsed.data : null,
25455
26476
  targetId: row.target_id,
25456
26477
  internal: intToBool(row.internal),
25457
- flagged: intToBool(row.flagged)
26478
+ flagged: intToBool(row.flagged),
26479
+ // Only meaningful when the title came out empty — a row whose body was
26480
+ // expired but whose title fell back to `tool_name` still has something to
26481
+ // render, and flagging it would make the view apologise for nothing.
26482
+ bodyExpired: row.content_expired_at !== null && (row.title ?? "") === ""
25458
26483
  };
25459
26484
  }
25460
26485
  var TIMELINE_COLUMNS = `
@@ -25462,6 +26487,7 @@ var TIMELINE_COLUMNS = `
25462
26487
  event_type,
25463
26488
  started_at,
25464
26489
  coalesce(content, json_extract(attributes, '$.tool_name')) AS title,
26490
+ content_expired_at,
25465
26491
  coalesce(json_extract(attributes, '$.detail'), json_extract(attributes, '$.target')) AS detail,
25466
26492
  coalesce(json_extract(attributes, '$.tool_name'), json_extract(attributes, '$.tool')) AS tool,
25467
26493
  json_extract(attributes, '$.severity') AS severity,
@@ -26127,6 +27153,88 @@ var SqliteAuditEventsRepository = class {
26127
27153
  }
26128
27154
  };
26129
27155
 
27156
+ // ../../packages/persistence/src/repositories/body-retention.ts
27157
+ var DEFAULT_BATCH_SIZE = 500;
27158
+ var DEFAULT_MAX_ROWS = 5e4;
27159
+ var SYNC_LANE_TYPES_SQL = OUTBOX_CAPTURE_TYPE_LIST;
27160
+ var SqliteBodyRetentionRepository = class {
27161
+ constructor(db) {
27162
+ this.db = db;
27163
+ const select = (laneClause) => `
27164
+ SELECT id, LENGTH(CAST(content AS BLOB)) AS bytes
27165
+ FROM audit_events
27166
+ WHERE content IS NOT NULL
27167
+ AND started_at < :cutoff
27168
+ AND event_type IN (${CAPTURE_EVENT_TYPES_SQL})
27169
+ ${laneClause}
27170
+ ORDER BY started_at
27171
+ LIMIT :limit`;
27172
+ this.candidatesStmt = this.db.prepare(select(""));
27173
+ this.candidatesSyncSafeStmt = this.db.prepare(
27174
+ select(`AND (event_type NOT IN (${SYNC_LANE_TYPES_SQL}) OR synced_at IS NOT NULL)`)
27175
+ );
27176
+ this.heldBySyncStmt = this.db.prepare(`
27177
+ SELECT COUNT(*) AS n
27178
+ FROM audit_events
27179
+ WHERE content IS NOT NULL
27180
+ AND started_at < :cutoff
27181
+ AND event_type IN (${SYNC_LANE_TYPES_SQL})
27182
+ AND synced_at IS NULL`);
27183
+ this.expireStmt = this.db.prepare(
27184
+ `UPDATE audit_events SET content = NULL, content_expired_at = :now WHERE id = :id`
27185
+ );
27186
+ }
27187
+ db;
27188
+ candidatesStmt;
27189
+ candidatesSyncSafeStmt;
27190
+ heldBySyncStmt;
27191
+ expireStmt;
27192
+ /** How many bytes a pass with these options would free, changing nothing. */
27193
+ preview(opts) {
27194
+ const limit = opts.maxRows ?? DEFAULT_MAX_ROWS;
27195
+ const stmt = opts.sweepSyncLane ? this.candidatesStmt : this.candidatesSyncSafeStmt;
27196
+ const rows = stmt.all({ cutoff: opts.cutoff, limit });
27197
+ return {
27198
+ rowsExpired: rows.length,
27199
+ bytesFreed: rows.reduce((sum, r) => sum + r.bytes, 0),
27200
+ rowsHeldBySync: this.countHeldBySync(opts)
27201
+ };
27202
+ }
27203
+ /** Clear eligible bodies, in bounded batches. */
27204
+ expire(opts) {
27205
+ const batchSize = opts.batchSize ?? DEFAULT_BATCH_SIZE;
27206
+ const maxRows = opts.maxRows ?? DEFAULT_MAX_ROWS;
27207
+ const stmt = opts.sweepSyncLane ? this.candidatesStmt : this.candidatesSyncSafeStmt;
27208
+ let rowsExpired = 0;
27209
+ let bytesFreed = 0;
27210
+ let done = true;
27211
+ while (rowsExpired < maxRows) {
27212
+ const remaining = Math.min(batchSize, maxRows - rowsExpired);
27213
+ const batch = stmt.all({ cutoff: opts.cutoff, limit: remaining });
27214
+ if (batch.length === 0) break;
27215
+ withTransaction(
27216
+ this.db,
27217
+ () => {
27218
+ for (const row of batch) this.expireStmt.run({ id: row.id, now: opts.now });
27219
+ },
27220
+ "IMMEDIATE"
27221
+ );
27222
+ rowsExpired += batch.length;
27223
+ bytesFreed += batch.reduce((sum, r) => sum + r.bytes, 0);
27224
+ if (batch.length < remaining) break;
27225
+ if (rowsExpired >= maxRows) {
27226
+ done = stmt.all({ cutoff: opts.cutoff, limit: 1 }).length === 0;
27227
+ }
27228
+ }
27229
+ return { rowsExpired, bytesFreed, rowsHeldBySync: this.countHeldBySync(opts), done };
27230
+ }
27231
+ countHeldBySync(opts) {
27232
+ if (opts.sweepSyncLane) return 0;
27233
+ const row = this.heldBySyncStmt.get({ cutoff: opts.cutoff });
27234
+ return row.n;
27235
+ }
27236
+ };
27237
+
26130
27238
  // ../../packages/persistence/src/repositories/classified-data.ts
26131
27239
  var SqliteClassifiedDataRepository = class {
26132
27240
  constructor(db) {
@@ -26955,7 +28063,15 @@ function toFlatFindingRow(r) {
26955
28063
  ...r.tool_name === null ? {} : { toolName: r.tool_name },
26956
28064
  eventId: r.event_id,
26957
28065
  ...r.session_id === null ? {} : { sessionId: r.session_id },
26958
- status: deriveInstanceStatus(r)
28066
+ status: deriveInstanceStatus(r),
28067
+ delivery: deriveFindingDelivery({
28068
+ kind: r.kind,
28069
+ syncedAt: r.synced_at,
28070
+ syncClaimedAt: r.sync_claimed_at,
28071
+ syncFailedAt: r.sync_failed_at,
28072
+ syncFailure: r.sync_failure,
28073
+ outboxOwed: r.outbox_owed
28074
+ })
26959
28075
  };
26960
28076
  }
26961
28077
  function encodeGroupCursor(group) {
@@ -27019,7 +28135,10 @@ var FINDING_ROW_COLUMNS_SQL = `f.id AS id, d.rule_id AS rule_id, d.category AS c
27019
28135
  e.tool_name AS tool_name,
27020
28136
  f.audit_event_id AS event_id, e.root_session_id AS session_id,
27021
28137
  e.event_type AS kind, f.finding_key AS finding_key,
27022
- ${latestResolutionStatusSql("f")} AS latest_status`;
28138
+ ${latestResolutionStatusSql("f")} AS latest_status,
28139
+ e.synced_at AS synced_at, e.sync_claimed_at AS sync_claimed_at,
28140
+ e.sync_failed_at AS sync_failed_at, e.sync_failure AS sync_failure,
28141
+ e.outbox_owed AS outbox_owed`;
27023
28142
  var DAY_MS3 = 864e5;
27024
28143
  var SqliteFindingsRepository = class {
27025
28144
  constructor(db) {
@@ -27264,6 +28383,7 @@ var SqliteFindingsRepository = class {
27264
28383
  providers: query.provider,
27265
28384
  actions: query.action,
27266
28385
  statuses: query.status,
28386
+ deliveries: query.deployment,
27267
28387
  tools: query.tool,
27268
28388
  repo: query.repo,
27269
28389
  file: query.file,
@@ -27331,6 +28451,7 @@ var SqliteFindingsRepository = class {
27331
28451
  providers: query.provider,
27332
28452
  actions: query.action,
27333
28453
  statuses: query.status,
28454
+ deliveries: query.deployment,
27334
28455
  tools: query.tool,
27335
28456
  q: query.q
27336
28457
  };
@@ -27594,7 +28715,9 @@ var SqliteFindingsRepository = class {
27594
28715
  )
27595
28716
  );
27596
28717
  for (const row of grouped) {
27597
- if (row.action_taken in byAction) byAction[row.action_taken] = row.c;
28718
+ if (Object.hasOwn(byAction, row.action_taken)) {
28719
+ byAction[row.action_taken] = row.c;
28720
+ }
27598
28721
  }
27599
28722
  const bySeverity = { critical: 0, high: 0, medium: 0, low: 0 };
27600
28723
  const sevRows = allRows(
@@ -27611,7 +28734,9 @@ var SqliteFindingsRepository = class {
27611
28734
  )
27612
28735
  );
27613
28736
  for (const row of sevRows) {
27614
- if (row.severity in bySeverity) bySeverity[row.severity] = row.c;
28737
+ if (Object.hasOwn(bySeverity, row.severity)) {
28738
+ bySeverity[row.severity] = row.c;
28739
+ }
27615
28740
  }
27616
28741
  const categories = ENFORCEABLE_CATEGORIES;
27617
28742
  const enabledRows = allRows(
@@ -27660,525 +28785,6 @@ function isoDay(ms) {
27660
28785
  return new Date(ms).toISOString().slice(0, 10);
27661
28786
  }
27662
28787
 
27663
- // ../../packages/persistence/src/repositories/history-sync.ts
27664
- var STRUCTURAL_EVENT_TYPES = ["session", "llm_call", "tool_call"];
27665
- var TYPE_LIST = STRUCTURAL_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
27666
- var OUTBOX_CAPTURE_EVENT_TYPES = ["prompt", "response", "tool_use"];
27667
- var CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
27668
- var SKIPPED = -1;
27669
- var ROW_COLUMNS = `id,
27670
- parent_id AS parentId,
27671
- root_session_id AS rootSessionId,
27672
- event_type AS eventType,
27673
- host_id AS hostId,
27674
- harness_id AS harnessId,
27675
- source_project_id AS sourceProjectId,
27676
- started_at AS startedAt,
27677
- ended_at AS endedAt,
27678
- severity,
27679
- priority,
27680
- content,
27681
- content_hash AS contentHash,
27682
- attributes`;
27683
- var SqliteHistorySyncRepository = class {
27684
- constructor(db) {
27685
- this.db = db;
27686
- this.ensureRowStmt = db.prepare(`INSERT OR IGNORE INTO history_sync (id) VALUES (1)`);
27687
- this.sessionsStmt = db.prepare(
27688
- `SELECT COALESCE(root_session_id, id) AS sessionId, MIN(started_at) AS earliest
27689
- FROM audit_events
27690
- WHERE synced_at IS NULL
27691
- AND event_type IN (${TYPE_LIST})
27692
- AND started_at < :before
27693
- GROUP BY sessionId
27694
- ORDER BY earliest
27695
- LIMIT :limit`
27696
- );
27697
- this.rowsStmt = db.prepare(
27698
- `SELECT ${ROW_COLUMNS}
27699
- FROM audit_events
27700
- WHERE synced_at IS NULL
27701
- AND event_type IN (${TYPE_LIST})
27702
- AND started_at < :before
27703
- AND COALESCE(root_session_id, id) = :sessionId
27704
- ORDER BY (event_type = 'session') DESC, started_at
27705
- LIMIT :limit`
27706
- );
27707
- this.captureRowsStmt = db.prepare(
27708
- `SELECT ${ROW_COLUMNS}
27709
- FROM audit_events
27710
- WHERE synced_at IS NULL
27711
- AND sync_claimed_at IS NULL
27712
- AND outbox_owed = 1
27713
- AND event_type IN (${CAPTURE_TYPE_LIST})
27714
- AND started_at < :before
27715
- ORDER BY started_at
27716
- LIMIT :limit`
27717
- );
27718
- this.markOwedStmt = db.prepare(
27719
- `UPDATE audit_events SET outbox_owed = 1 WHERE id = :id AND synced_at IS NULL`
27720
- );
27721
- this.markCaptureBacklogOwedStmt = db.prepare(
27722
- `UPDATE audit_events SET outbox_owed = 1
27723
- WHERE synced_at IS NULL
27724
- AND event_type IN (${CAPTURE_TYPE_LIST})
27725
- AND started_at < :before`
27726
- );
27727
- this.stampStmt = db.prepare(
27728
- `UPDATE audit_events SET synced_at = :at, sync_claimed_at = NULL WHERE id = :id`
27729
- );
27730
- this.claimRowStmt = db.prepare(
27731
- `UPDATE audit_events SET sync_claimed_at = :at WHERE id = :id AND synced_at IS NULL`
27732
- );
27733
- this.releaseRowStmt = db.prepare(
27734
- `UPDATE audit_events SET sync_claimed_at = NULL WHERE id = :id`
27735
- );
27736
- this.releaseStaleClaimsStmt = db.prepare(
27737
- `UPDATE audit_events SET sync_claimed_at = NULL
27738
- WHERE sync_claimed_at IS NOT NULL AND sync_claimed_at < :staleBefore`
27739
- );
27740
- this.partitionStmt = db.prepare(
27741
- `SELECT
27742
- SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NULL THEN 1 ELSE 0 END) AS queued,
27743
- SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NOT NULL THEN 1 ELSE 0 END) AS inProgress,
27744
- SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS synced,
27745
- SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0 THEN 1 ELSE 0 END) AS failed,
27746
- COUNT(*) AS total
27747
- FROM audit_events
27748
- WHERE event_type IN (${TYPE_LIST})`
27749
- );
27750
- this.countsStmt = db.prepare(
27751
- `SELECT
27752
- SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
27753
- SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
27754
- SUM(CASE WHEN synced_at = ${String(SKIPPED)} THEN 1 ELSE 0 END) AS skipped
27755
- FROM audit_events
27756
- WHERE event_type IN (${TYPE_LIST})`
27757
- );
27758
- this.captureSkipCountStmt = db.prepare(
27759
- `SELECT COUNT(*) AS skipped
27760
- FROM audit_events
27761
- WHERE synced_at = ${String(SKIPPED)}
27762
- AND event_type IN (${CAPTURE_TYPE_LIST})`
27763
- );
27764
- this.fingerprintStmt = db.prepare(
27765
- `SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
27766
- FROM history_sync WHERE id = 1`
27767
- );
27768
- this.setFingerprintStmt = db.prepare(
27769
- `UPDATE history_sync
27770
- SET endpoint_fingerprint = :fingerprint, backlog_before = :backlogBefore
27771
- WHERE id = 1`
27772
- );
27773
- this.disownCapturesStmt = db.prepare(
27774
- `UPDATE audit_events SET outbox_owed = NULL
27775
- WHERE outbox_owed IS NOT NULL
27776
- AND event_type IN (${CAPTURE_TYPE_LIST})
27777
- AND started_at < :attachedAt`
27778
- );
27779
- this.rearmStmt = db.prepare(
27780
- `UPDATE audit_events SET synced_at = NULL
27781
- WHERE synced_at > 0 AND event_type IN (${TYPE_LIST})`
27782
- );
27783
- this.claimStmt = db.prepare(
27784
- `UPDATE history_sync
27785
- SET owner_pid = :pid, owner_host = :host, acquired_at = :now, heartbeat_at = :now
27786
- WHERE id = 1
27787
- AND (owner_pid IS NULL
27788
- OR heartbeat_at IS NULL
27789
- OR heartbeat_at < :staleBefore
27790
- OR heartbeat_at > :now)`
27791
- );
27792
- this.heartbeatStmt = db.prepare(
27793
- `UPDATE history_sync SET heartbeat_at = :now WHERE id = 1 AND owner_pid = :pid`
27794
- );
27795
- this.releaseStmt = db.prepare(
27796
- `UPDATE history_sync
27797
- SET owner_pid = NULL, owner_host = NULL, acquired_at = NULL, heartbeat_at = NULL
27798
- WHERE id = 1 AND owner_pid = :pid`
27799
- );
27800
- this.closeWindowStmt = db.prepare(
27801
- `UPDATE audit_events SET synced_at = :at
27802
- WHERE synced_at IS NULL
27803
- AND event_type IN (${TYPE_LIST})
27804
- AND started_at >= :attachedAt`
27805
- );
27806
- this.releaseBoundaryStmt = db.prepare(
27807
- `UPDATE history_sync SET backlog_before = NULL WHERE id = 1`
27808
- );
27809
- this.freezeBoundaryStmt = db.prepare(
27810
- `UPDATE history_sync SET backlog_before = :backlogBefore WHERE id = 1`
27811
- );
27812
- this.leaseStmt = db.prepare(
27813
- `SELECT owner_pid AS ownerPid, owner_host AS ownerHost,
27814
- acquired_at AS acquiredAt, heartbeat_at AS heartbeatAt
27815
- FROM history_sync WHERE id = 1`
27816
- );
27817
- this.inspectionsStmt = db.prepare(
27818
- `SELECT d.rule_id AS ruleId,
27819
- d.name AS ruleName,
27820
- d.version AS ruleVersion,
27821
- d.category AS category,
27822
- d.severity AS severity,
27823
- f.span_start AS spanStart,
27824
- f.span_end AS spanEnd,
27825
- f.masked_match AS maskedMatch,
27826
- f.action_taken AS actionTaken,
27827
- f.confidence AS confidence
27828
- FROM inspection_findings f
27829
- JOIN inspection_definitions d ON d.id = f.inspection_definition_id
27830
- WHERE f.audit_event_id = :auditEventId
27831
- ORDER BY f.span_start, f.id`
27832
- );
27833
- }
27834
- db;
27835
- ensureRowStmt;
27836
- sessionsStmt;
27837
- rowsStmt;
27838
- stampStmt;
27839
- countsStmt;
27840
- fingerprintStmt;
27841
- setFingerprintStmt;
27842
- rearmStmt;
27843
- claimStmt;
27844
- heartbeatStmt;
27845
- releaseStmt;
27846
- leaseStmt;
27847
- inspectionsStmt;
27848
- closeWindowStmt;
27849
- releaseBoundaryStmt;
27850
- freezeBoundaryStmt;
27851
- captureRowsStmt;
27852
- markOwedStmt;
27853
- markCaptureBacklogOwedStmt;
27854
- captureSkipCountStmt;
27855
- disownCapturesStmt;
27856
- partitionStmt;
27857
- claimRowStmt;
27858
- releaseRowStmt;
27859
- releaseStaleClaimsStmt;
27860
- /**
27861
- * The masked detections recorded against one tool call.
27862
- *
27863
- * These travel with the event because a tool call's target is not
27864
- * re-inspectable from the event alone — unlike a capture, where the text
27865
- * itself is re-scannable. What crosses is the masked match and the rule that
27866
- * produced it, never the value.
27867
- */
27868
- inspectionsFor(auditEventId) {
27869
- return allRows(this.inspectionsStmt, { auditEventId });
27870
- }
27871
- /**
27872
- * Sessions with structural rows still to send, oldest first.
27873
- *
27874
- * BOUNDED BY THE BACKLOG BOUNDARY, which is the whole correctness of this
27875
- * read. Anything recorded after the machine attached is the live forward
27876
- * path's to deliver; this drain exists for what was recorded before it, and a
27877
- * row both paths send is at best a duplicate request and at worst — for a
27878
- * session root — an overwrite of the inventory ids the live path resolved.
27879
- */
27880
- pendingSessions(limit, before) {
27881
- return allRows(this.sessionsStmt, { limit, before }).map(
27882
- (r) => r.sessionId
27883
- );
27884
- }
27885
- /** One session's undelivered structural rows within the backlog, root first. */
27886
- pendingRows(sessionId, limit, before) {
27887
- return allRows(this.rowsStmt, { sessionId, limit, before });
27888
- }
27889
- /**
27890
- * Captures this machine still owes the deployment, oldest first.
27891
- *
27892
- * Selected by the `outbox_owed` marker the attached forward path writes, not
27893
- * by a time window — see captureRowsStmt for why a window could not express
27894
- * this. `before` is the grace window that leaves a just-recorded capture to
27895
- * the live path.
27896
- */
27897
- pendingCaptureRows(limit, before) {
27898
- return allRows(this.captureRowsStmt, { limit, before });
27899
- }
27900
- /**
27901
- * Record that a capture is OWED to the deployment.
27902
- *
27903
- * Written by the attached forward path when a live send did not confirm
27904
- * delivery, and read by the drain as the whole of its eligibility test. It is
27905
- * a fact rather than an inference: the machine was attached, the send did not
27906
- * land, so the row is owed — which no time window can state, because the same
27907
- * window that holds the rows a past attachment left owed also holds every
27908
- * capture recorded while the machine was DETACHED, and those were never
27909
- * offered to anyone.
27910
- *
27911
- * Idempotent, and never un-set: `markSynced` settling the row is what takes it
27912
- * out of the drain's read.
27913
- */
27914
- markCaptureOwed(id) {
27915
- this.markOwedStmt.run({ id });
27916
- }
27917
- /**
27918
- * Mark every capture already on disk as owed, as of `before`.
27919
- *
27920
- * The consent-time backfill, called once from `aka attach` when a human
27921
- * grants existing-history consent — never from an ongoing drain pass, and
27922
- * never inferred from a boundary that could later move. `before` is the
27923
- * caller's own "now" at the moment consent was granted, so what this marks
27924
- * is exactly the backlog the consent prompt already counted, not whatever a
27925
- * later re-attach or key rotation might widen it to.
27926
- *
27927
- * Returns how many rows matched, for the caller to log or test against. Not a
27928
- * count of NEWLY marked rows — a row still unsynced from an earlier call
27929
- * matches again and is counted again, the same as `UPDATE`'s own `changes`.
27930
- */
27931
- markCaptureBacklogOwed(before) {
27932
- return Number(this.markCaptureBacklogOwedStmt.run({ before }).changes);
27933
- }
27934
- /** Record delivery. Called only AFTER the far side has accepted the rows. */
27935
- markSynced(ids, atMs) {
27936
- this.stampAll(ids, atMs);
27937
- }
27938
- /**
27939
- * Record that a row will never be sent.
27940
- *
27941
- * Reserved for a local defect — a row that cannot be rebuilt into a valid
27942
- * payload. A row that merely failed to reach the deployment stays NULL, so it
27943
- * is retried; marking those would turn one outage into permanent data loss.
27944
- */
27945
- markSkipped(ids) {
27946
- this.stampAll(ids, SKIPPED);
27947
- }
27948
- eachInTransaction(ids, run) {
27949
- if (ids.length === 0) return;
27950
- withTransaction(
27951
- this.db,
27952
- () => {
27953
- for (const id of ids) run(id);
27954
- },
27955
- "IMMEDIATE"
27956
- );
27957
- }
27958
- stampAll(ids, value) {
27959
- if (ids.length === 0) return;
27960
- withTransaction(
27961
- this.db,
27962
- () => {
27963
- for (const id of ids) this.stampStmt.run({ at: value, id });
27964
- },
27965
- "IMMEDIATE"
27966
- );
27967
- }
27968
- /**
27969
- * Claim rows as in-flight.
27970
- *
27971
- * Advisory in exactly the sense the lease is: it records that a send is in
27972
- * progress so a surface can say so, and a lost claim costs a row showing as
27973
- * queued while it is actually being sent. It is not exclusion — the far side
27974
- * settles a duplicate on the row id.
27975
- */
27976
- claimRows(ids, atMs) {
27977
- this.eachInTransaction(ids, (id) => this.claimRowStmt.run({ at: atMs, id }));
27978
- }
27979
- /** Give back a claim without settling — the send failed, the row is queued again. */
27980
- releaseRows(ids) {
27981
- this.eachInTransaction(ids, (id) => this.releaseRowStmt.run({ id }));
27982
- }
27983
- /**
27984
- * Clear claims older than `staleBefore`, and report how many were cleared.
27985
- *
27986
- * A process killed between claiming and settling leaves rows claimed with
27987
- * nothing left to settle them. Without this they read as "sending" for ever.
27988
- */
27989
- releaseStaleClaims(staleBefore) {
27990
- return Number(this.releaseStaleClaimsStmt.run({ staleBefore }).changes);
27991
- }
27992
- /**
27993
- * Every tracked row in exactly one delivery state.
27994
- *
27995
- * Takes no boundary on purpose. The boundary answers "what should the drain
27996
- * pick up now", which is a different question from "what state is this row
27997
- * in" — and a machine that has never attached has no boundary to pass, so
27998
- * requiring one would force a caller to invent one and report the whole store
27999
- * as queued.
28000
- */
28001
- partition() {
28002
- const row = getRow(this.partitionStmt, {});
28003
- return {
28004
- queued: row?.queued ?? 0,
28005
- inProgress: row?.inProgress ?? 0,
28006
- synced: row?.synced ?? 0,
28007
- failed: row?.failed ?? 0,
28008
- total: row?.total ?? 0
28009
- };
28010
- }
28011
- /** `pending` counts only what is inside the backlog; sent and skipped are totals. */
28012
- counts(before) {
28013
- const row = getRow(
28014
- this.countsStmt,
28015
- { before }
28016
- );
28017
- const captures = getRow(this.captureSkipCountStmt);
28018
- return {
28019
- pending: row?.pending ?? 0,
28020
- sent: row?.sent ?? 0,
28021
- skipped: row?.skipped ?? 0,
28022
- capturesSkipped: captures?.skipped ?? 0
28023
- };
28024
- }
28025
- /**
28026
- * The deployment the current stamps were made against, and where its backlog
28027
- * ends.
28028
- *
28029
- * READ-ONLY. An absent row reads as an absent deployment, which is what a
28030
- * machine that has never drained is — and every writer below seeds the row
28031
- * before it needs one, so nothing depends on this creating it. Keeping the
28032
- * write off the gate path matters because the gate runs on every pass while a
28033
- * write has to take the database's write lock.
28034
- */
28035
- deployment() {
28036
- const row = getRow(
28037
- this.fingerprintStmt
28038
- );
28039
- return {
28040
- fingerprint: row?.fingerprint ?? void 0,
28041
- backlogBefore: row?.backlogBefore ?? void 0
28042
- };
28043
- }
28044
- /**
28045
- * Point the ledger at a different deployment, discarding what it recorded
28046
- * about the previous one.
28047
- *
28048
- * Delivery is a fact about ONE recipient: rows sent to the deployment a
28049
- * machine has just left are undelivered as far as the new one is concerned.
28050
- * All four in one transaction, so a crash between them cannot leave stamps
28051
- * attributed to the wrong deployment, a boundary that belongs to another, or
28052
- * a disown with no re-mark to follow it.
28053
- *
28054
- * The boundary is written HERE and only here, which is what freezes it: a
28055
- * re-attach to the SAME deployment (a key rotation) leaves the fingerprint
28056
- * unchanged, so this never runs and the backlog does not widen back over rows
28057
- * the live path has since delivered.
28058
- *
28059
- * `backfillCapturesBefore` is the caller's OWN "now" at the instant a human
28060
- * granted existing-history consent for the deployment this call is arming —
28061
- * a DIFFERENT instant from `backlogBefore`: the re-mark boundary is the GRANT
28062
- * instant, `backlogBefore` is the ATTACH instant, and the two can be far
28063
- * apart. Passed only when that grant is valid, since this method has no way
28064
- * to check consent itself and must not mark a row owed for a machine that
28065
- * never agreed to it. Applied AFTER the disown above, in the SAME
28066
- * transaction: what the disown clears is every marker below `backlogBefore`,
28067
- * which includes this deployment's OWN pre-attach rows — `aka attach` calls
28068
- * `seedCaptureBacklogOwed` at the attach instant, so every row it marks sits
28069
- * on the cleared side of that bound — and the re-mark in the same
28070
- * transaction is what puts those rows back. A crash between the two cannot
28071
- * strand the ledger disowned with nothing re-marked — the transaction either
28072
- * lands whole or not at all, and a fingerprint mismatch that has not yet
28073
- * committed re-enters this method on the very next pass. Omit it (the
28074
- * structural-only tests do) to exercise the disown in isolation.
28075
- *
28076
- * The disown is bounded by `backlogBefore`, which is what keeps it from
28077
- * touching a marker the NEW deployment's OWN live path has already set: B's
28078
- * live path can mark a capture owed from the moment `aka attach` writes the
28079
- * descriptor, before the drain's first pass ever reaches this method, and
28080
- * such a row sits at or after the bound rather than below it. What keeps the
28081
- * disown from eating THIS SAME CALL's own re-mark is the order, not the
28082
- * bound — disown runs first, re-mark second, both inside the one
28083
- * transaction above.
28084
- */
28085
- rearmFor(fingerprint, backlogBefore, backfillCapturesBefore) {
28086
- this.ensureRowStmt.run();
28087
- withTransaction(
28088
- this.db,
28089
- () => {
28090
- const previous = getRow(this.fingerprintStmt)?.fingerprint;
28091
- this.rearmStmt.run();
28092
- if (previous !== null && previous !== void 0 && previous !== fingerprint) {
28093
- this.disownCapturesStmt.run({ attachedAt: backlogBefore });
28094
- }
28095
- if (backfillCapturesBefore !== void 0) {
28096
- this.markCaptureBacklogOwedStmt.run({ before: backfillCapturesBefore });
28097
- }
28098
- this.setFingerprintStmt.run({ fingerprint, backlogBefore });
28099
- },
28100
- "IMMEDIATE"
28101
- );
28102
- }
28103
- /**
28104
- * End the attached period: hand its rows to the live path, and release the
28105
- * boundary so the next attachment can freeze a new one.
28106
- *
28107
- * WITHOUT THIS, a detach and a re-attach to the same deployment leave a window
28108
- * nothing delivers. The fingerprint is unchanged, so the boundary is never
28109
- * re-frozen and stays at the FIRST attachment — while nothing forwards at all
28110
- * during the detached period, because the machine is not attached. Rows
28111
- * recorded in that window sit after the boundary and before the re-attach, so
28112
- * neither path takes them, and the pending count reports none outstanding.
28113
- *
28114
- * Stamping the attached window is not a claim that every one of those rows
28115
- * reached the deployment — the live path drops on failure and says so
28116
- * elsewhere. It records that they were ITS to deliver, which is exactly the
28117
- * status quo: they sit outside the frozen boundary today and are equally never
28118
- * re-sent. Making it explicit is what lets the boundary move.
28119
- *
28120
- * ONE TRANSACTION, so a crash cannot release the boundary while leaving the
28121
- * window unstamped — that half-state would re-send the whole attached period
28122
- * on the next attach, which is the failure the boundary exists to prevent.
28123
- */
28124
- closeAttachedWindow(attachedAtMs, atMs) {
28125
- this.ensureRowStmt.run();
28126
- withTransaction(
28127
- this.db,
28128
- () => {
28129
- const row = getRow(this.fingerprintStmt);
28130
- const from = row?.backlogBefore ?? attachedAtMs;
28131
- this.closeWindowStmt.run({ at: atMs, attachedAt: from });
28132
- this.releaseBoundaryStmt.run();
28133
- },
28134
- "IMMEDIATE"
28135
- );
28136
- }
28137
- /**
28138
- * Freeze a boundary for the deployment already on file, KEEPING the stamps.
28139
- *
28140
- * The re-attach half of the above. Distinct from `rearmFor`, which is for a
28141
- * different deployment and therefore discards what was delivered to the old
28142
- * one: here the recipient is the same, so everything already sent to it stays
28143
- * sent.
28144
- */
28145
- freezeBoundary(backlogBefore) {
28146
- this.ensureRowStmt.run();
28147
- this.freezeBoundaryStmt.run({ backlogBefore });
28148
- }
28149
- /** Take the claim, or report that someone live already holds it. */
28150
- claim(pid, host, nowMs, staleAfterMs) {
28151
- this.ensureRowStmt.run();
28152
- let taken = false;
28153
- withTransaction(
28154
- this.db,
28155
- () => {
28156
- const result = this.claimStmt.run({
28157
- pid,
28158
- host,
28159
- now: nowMs,
28160
- staleBefore: nowMs - staleAfterMs
28161
- });
28162
- taken = result.changes === 1;
28163
- },
28164
- "IMMEDIATE"
28165
- );
28166
- return taken;
28167
- }
28168
- /** Say the holder is still alive. A no-op once the claim has moved on. */
28169
- heartbeat(pid, nowMs) {
28170
- this.heartbeatStmt.run({ now: nowMs, pid });
28171
- }
28172
- /** Give the claim up. Scoped to this holder, so a taken-over claim is left be. */
28173
- release(pid) {
28174
- this.releaseStmt.run({ pid });
28175
- }
28176
- /** Who holds the claim, if anyone. Read-only, for the same reason as above. */
28177
- lease() {
28178
- return getRow(this.leaseStmt);
28179
- }
28180
- };
28181
-
28182
28788
  // ../../packages/persistence/src/repositories/inspection-definitions.ts
28183
28789
  var SqliteInspectionDefinitionsRepository = class {
28184
28790
  constructor(db) {
@@ -28409,6 +29015,7 @@ function overlayManagedSettings(settings, managed, now = () => /* @__PURE__ */ n
28409
29015
  if (values.vaultInlineReveal !== void 0) merged.vaultInlineReveal = values.vaultInlineReveal;
28410
29016
  if (values.dataSharesInPlace !== void 0) merged.dataSharesInPlace = values.dataSharesInPlace;
28411
29017
  if (values.redactFallback !== void 0) merged.redactFallback = values.redactFallback;
29018
+ if (values.bodyRetention !== void 0) merged.bodyRetention = values.bodyRetention;
28412
29019
  if (values.vaultConsent !== void 0) {
28413
29020
  merged.vaultConsent = values.vaultConsent ? (
28414
29021
  // Keep an existing valid grant so its acknowledgedAt survives; mint one
@@ -30916,7 +31523,7 @@ var SqliteSecurityRepository = class {
30916
31523
  ELSE 0
30917
31524
  END) AS open_at_rest
30918
31525
  FROM inspection_findings f
30919
- JOIN audit_events e ON e.id = f.audit_event_id
31526
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
30920
31527
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
30921
31528
  LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
30922
31529
  ON latest.finding_key = f.finding_key
@@ -31142,7 +31749,7 @@ var SqliteSecurityRepository = class {
31142
31749
  this.db.prepare(
31143
31750
  `SELECT e.repo AS repo, count(*) AS c
31144
31751
  FROM inspection_findings f
31145
- JOIN audit_events e ON e.id = f.audit_event_id
31752
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31146
31753
  WHERE e.started_at >= :from AND e.started_at < :to
31147
31754
  AND e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
31148
31755
  AND e.repo IS NOT NULL
@@ -31266,7 +31873,7 @@ var SqliteSecurityRepository = class {
31266
31873
  d.severity AS severity,
31267
31874
  COUNT(*) AS count
31268
31875
  FROM inspection_findings f
31269
- JOIN audit_events e ON e.id = f.audit_event_id
31876
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31270
31877
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
31271
31878
  LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
31272
31879
  ON latest.finding_key = f.finding_key
@@ -31301,7 +31908,7 @@ var SqliteSecurityRepository = class {
31301
31908
  `SELECT e.started_at AS occurred_at, d.severity AS severity, f.action_taken AS action_taken,
31302
31909
  d.rule_id AS rule_id, d.category AS category
31303
31910
  FROM inspection_findings f
31304
- JOIN audit_events e ON e.id = f.audit_event_id
31911
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31305
31912
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
31306
31913
  WHERE e.started_at >= :from AND e.started_at < :to
31307
31914
  AND e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
@@ -32142,6 +32749,7 @@ function openWithPragmas(file2) {
32142
32749
  db.exec("PRAGMA journal_mode = WAL");
32143
32750
  db.exec("PRAGMA busy_timeout = 2000");
32144
32751
  db.exec("PRAGMA foreign_keys = ON");
32752
+ registerSqlFunctions(db);
32145
32753
  } catch (err) {
32146
32754
  closeQuietly(db);
32147
32755
  throw err;
@@ -32171,7 +32779,7 @@ function backupLegacyStore(db, file2) {
32171
32779
  discardStore(file2, backup);
32172
32780
  return backup;
32173
32781
  }
32174
- function openAndInitialize(file2, base) {
32782
+ function openAndInitialize(file2, base, skipTags) {
32175
32783
  let db = openWithPragmas(file2);
32176
32784
  try {
32177
32785
  if (isForeignSqliteLineage(db)) {
@@ -32181,7 +32789,7 @@ function openAndInitialize(file2, base) {
32181
32789
  `Detected an older, incompatible (tenant-bearing) ${DB_FILENAME}; backed it up to ${backup} and created a fresh store.`
32182
32790
  );
32183
32791
  }
32184
- applyMigrations(db, file2);
32792
+ applyMigrations(db, file2, { skipTags });
32185
32793
  tightenPerms(file2);
32186
32794
  const policies = new SqlitePoliciesRepository(db);
32187
32795
  const installedPacks = new SqliteInstalledPacksRepository(db, base);
@@ -32196,6 +32804,7 @@ function openAndInitialize(file2, base) {
32196
32804
  exceptions: new SqliteExceptionsRepository(db),
32197
32805
  resolutions: new SqliteResolutionsRepository(db),
32198
32806
  ruleProbeCache: new SqliteRuleProbeCacheRepository(db),
32807
+ bodyRetention: new SqliteBodyRetentionRepository(db),
32199
32808
  security: new SqliteSecurityRepository(db),
32200
32809
  detections: new SqliteDetectionsRepository(db),
32201
32810
  shares: new SqliteSharesRepository(db),
@@ -32218,7 +32827,8 @@ function openAndInitialize(file2, base) {
32218
32827
  throw err;
32219
32828
  }
32220
32829
  }
32221
- function openLocalDatabase(dir) {
32830
+ var DEFERRED_TAGS = new Set(DEFERRED_MIGRATION_TAGS);
32831
+ function openLocalDatabase(dir, options = {}) {
32222
32832
  ensureDataDirSync(dir);
32223
32833
  const file2 = join7(dir, DB_FILENAME);
32224
32834
  reapStalePartials(file2);
@@ -32230,6 +32840,7 @@ function openLocalDatabase(dir) {
32230
32840
  installedPacks,
32231
32841
  scanLedger,
32232
32842
  historySync,
32843
+ bodyRetention,
32233
32844
  secretVault,
32234
32845
  exceptions,
32235
32846
  resolutions,
@@ -32253,7 +32864,8 @@ function openLocalDatabase(dir) {
32253
32864
  // `dir` is always `<base>/data` — every caller resolves it through
32254
32865
  // `dataDir()` — so its parent is the `~/.aka` base the layout splits into
32255
32866
  // settings/ and data/, and the pack-policy floor needs both halves.
32256
- dirname2(dir)
32867
+ dirname2(dir),
32868
+ options.applyDeferredMigrations === true ? void 0 : DEFERRED_TAGS
32257
32869
  );
32258
32870
  function captureRowId(event) {
32259
32871
  return captureId(
@@ -32446,6 +33058,7 @@ function openLocalDatabase(dir) {
32446
33058
  installedPacks,
32447
33059
  scanLedger,
32448
33060
  historySync,
33061
+ bodyRetention,
32449
33062
  secretVault,
32450
33063
  exceptions,
32451
33064
  resolutions,
@@ -32486,8 +33099,35 @@ function openLocalDatabase(dir) {
32486
33099
 
32487
33100
  // ../../packages/persistence/src/egress-wire.ts
32488
33101
  import { createHash as createHash3 } from "crypto";
33102
+ var PROJECT_KEY_DIGEST_VERSION = "v2";
33103
+ var SCP_FORM = /^(?:[^@/]+@)?([^/:]+):(.+)$/;
33104
+ var DOS_DRIVE = /^[A-Za-z]:[\\/]/;
33105
+ var FILE_URL = /^file:\/\//i;
33106
+ var SCHEME_FORM = /^[a-z][a-z0-9+.-]*:\/\/(?:[^@/]+@)?([^/:]+)(?::\d+)?(\/.*)?$/i;
33107
+ var SLASH = "/".charCodeAt(0);
33108
+ var GIT_SUFFIX = ".git";
33109
+ function trimSlashes(path) {
33110
+ let start = 0;
33111
+ let end = path.length;
33112
+ while (start < end && path.charCodeAt(start) === SLASH) start += 1;
33113
+ while (end > start && path.charCodeAt(end - 1) === SLASH) end -= 1;
33114
+ return path.slice(start, end);
33115
+ }
33116
+ function canonicalGitUrl(url2) {
33117
+ const trimmed = url2.trim();
33118
+ if (DOS_DRIVE.test(trimmed) || FILE_URL.test(trimmed)) return trimmed;
33119
+ const scheme = SCHEME_FORM.exec(trimmed);
33120
+ const scp = scheme === null ? SCP_FORM.exec(trimmed) : null;
33121
+ const host = (scheme?.[1] ?? scp?.[1])?.toLowerCase();
33122
+ if (host === void 0) return trimmed;
33123
+ const path = (scheme === null ? scp?.[2] : scheme[2]) ?? "";
33124
+ const bare = trimSlashes(path);
33125
+ const cleaned = bare.endsWith(GIT_SUFFIX) ? bare.slice(0, -GIT_SUFFIX.length) : bare;
33126
+ return cleaned === "" ? host : `${host}/${cleaned}`;
33127
+ }
32489
33128
  function hashProjectKey(projectKey) {
32490
- return createHash3("sha256").update(projectKey, "utf8").digest("hex");
33129
+ const canonical = projectKey.startsWith("git:") ? `git:${canonicalGitUrl(projectKey.slice("git:".length))}` : projectKey;
33130
+ return createHash3("sha256").update(`${PROJECT_KEY_DIGEST_VERSION}:${canonical}`, "utf8").digest("hex");
32491
33131
  }
32492
33132
  function toIngestHit(hit) {
32493
33133
  return {
@@ -32563,18 +33203,50 @@ function readFingerprintKey(dataDir2) {
32563
33203
  return parseKeyFile(raw);
32564
33204
  }
32565
33205
 
33206
+ // ../../packages/persistence/src/forward-health.ts
33207
+ import { readFileSync as readFileSync7 } from "fs";
33208
+ import { join as join9 } from "path";
33209
+ var FAILURES = /* @__PURE__ */ new Set([
33210
+ "unauthorized",
33211
+ "forbidden",
33212
+ "unreachable"
33213
+ ]);
33214
+ var BREAKER_COOLDOWN_MS = 3e4;
33215
+ function parseForwardHealth(raw, nowMs) {
33216
+ try {
33217
+ const parsed2 = JSON.parse(raw);
33218
+ if (typeof parsed2 !== "object" || parsed2 === null) return null;
33219
+ const record2 = parsed2;
33220
+ const failures = typeof record2.consecutiveFailures === "number" && record2.consecutiveFailures >= 0 ? record2.consecutiveFailures : 0;
33221
+ const openedAtMs = typeof record2.openedAtMs === "number" && Number.isFinite(record2.openedAtMs) && record2.openedAtMs <= nowMs ? record2.openedAtMs : null;
33222
+ const lastFailure = typeof record2.lastFailure === "string" && FAILURES.has(record2.lastFailure) ? record2.lastFailure : null;
33223
+ return { consecutiveFailures: failures, openedAtMs, lastFailure };
33224
+ } catch {
33225
+ return null;
33226
+ }
33227
+ }
33228
+ function isForwardPaused(health, nowMs) {
33229
+ const openedAtMs = health?.openedAtMs ?? null;
33230
+ if (openedAtMs === null) return false;
33231
+ return nowMs - openedAtMs < BREAKER_COOLDOWN_MS;
33232
+ }
33233
+
32566
33234
  // ../../packages/persistence/src/history-backfill.ts
32567
33235
  import { existsSync as existsSync4 } from "fs";
32568
- import { join as join9 } from "path";
33236
+ import { join as join10 } from "path";
32569
33237
 
32570
33238
  // ../../packages/persistence/src/history-preview.ts
32571
33239
  import { existsSync as existsSync5 } from "fs";
32572
- import { join as join10 } from "path";
33240
+ import { join as join11 } from "path";
32573
33241
  import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
32574
33242
 
33243
+ // ../../packages/persistence/src/history-sync-state.ts
33244
+ import { readFileSync as readFileSync8 } from "fs";
33245
+ import { join as join12 } from "path";
33246
+
32575
33247
  // ../../packages/persistence/src/store-symlinks.ts
32576
33248
  import { existsSync as existsSync6, lstatSync as lstatSync3, readlinkSync, realpathSync, statSync as statSync4 } from "fs";
32577
- import { dirname as dirname3, join as join11, resolve } from "path";
33249
+ import { dirname as dirname3, join as join13, resolve } from "path";
32578
33250
  var STORE_DB = "the store database (including the prompt corpus)";
32579
33251
  var STORE_SETTINGS = "your settings file";
32580
33252
  function storeContents(home) {
@@ -32583,7 +33255,7 @@ function storeContents(home) {
32583
33255
  [settingsDir(home), STORE_SETTINGS],
32584
33256
  [dataDir(home), STORE_DB],
32585
33257
  [keysDir(home), "the vault key"],
32586
- [join11(settingsDir(home), "settings.json"), STORE_SETTINGS],
33258
+ [join13(settingsDir(home), "settings.json"), STORE_SETTINGS],
32587
33259
  [dbPath(home), STORE_DB]
32588
33260
  ]);
32589
33261
  }
@@ -32635,19 +33307,19 @@ import {
32635
33307
  // ../../packages/persistence/src/vault/key-provider.ts
32636
33308
  import { execFileSync } from "child_process";
32637
33309
  import { randomBytes as randomBytes2 } from "crypto";
32638
- import { chmodSync as chmodSync3, readFileSync as readFileSync7, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
32639
- import { join as join12 } from "path";
33310
+ import { chmodSync as chmodSync3, readFileSync as readFileSync9, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
33311
+ import { join as join14 } from "path";
32640
33312
 
32641
33313
  // ../../packages/persistence/src/vault/vault.ts
32642
33314
  import { randomBytes as randomBytes3, randomUUID as randomUUID12 } from "crypto";
32643
33315
 
32644
33316
  // ../../packages/persistence/src/warn-era-cap.ts
32645
33317
  import { existsSync as existsSync7, writeFileSync as writeFileSync4 } from "fs";
32646
- import { join as join13 } from "path";
33318
+ import { join as join15 } from "path";
32647
33319
  var MARKER = "warn-era-capped";
32648
33320
  function capWarnEraEnforcementOnce(db, policyMode, dataDir2) {
32649
33321
  if (policyMode !== "warn") return { capped: 0, skipped: "not-warn" };
32650
- const marker = join13(dataDir2, MARKER);
33322
+ const marker = join15(dataDir2, MARKER);
32651
33323
  if (existsSync7(marker)) return { capped: 0, skipped: "already-run" };
32652
33324
  const capped = db.policies.capCategoryActions();
32653
33325
  writeFileSync4(marker, `${new Date(Date.now()).toISOString()}
@@ -32707,7 +33379,7 @@ function resolveProvider() {
32707
33379
  function loadConfig(base = defaultDataDir(), resolveProviderFn = resolveProvider) {
32708
33380
  try {
32709
33381
  ensureLayoutDirSync(base);
32710
- const settingsFile = join14(settingsDir(base), "settings.json");
33382
+ const settingsFile = join16(settingsDir(base), "settings.json");
32711
33383
  if (existsSync8(settingsFile)) tightenFile(settingsFile);
32712
33384
  } catch {
32713
33385
  }
@@ -32731,9 +33403,9 @@ function resolveProviderSafe(resolveProviderFn) {
32731
33403
  }
32732
33404
 
32733
33405
  // ../../packages/plugin-sdk/src/config-inventory.ts
32734
- import { readdirSync as readdirSync2, readFileSync as readFileSync9, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
33406
+ import { readdirSync as readdirSync2, readFileSync as readFileSync11, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
32735
33407
  import { homedir as homedir2 } from "os";
32736
- import { basename as basename3, join as join16 } from "path";
33408
+ import { basename as basename3, join as join18 } from "path";
32737
33409
 
32738
33410
  // ../../packages/detections/src/egress/registry.ts
32739
33411
  var EXTRACTOR_VERSION = "1";
@@ -35516,8 +36188,8 @@ function bundledDetections() {
35516
36188
  }
35517
36189
 
35518
36190
  // ../../packages/plugin-sdk/src/repo.ts
35519
- import { existsSync as existsSync9, readFileSync as readFileSync8, statSync as statSync6 } from "fs";
35520
- import { basename as basename2, dirname as dirname4, isAbsolute, join as join15, sep as sep2 } from "path";
36191
+ import { existsSync as existsSync9, readFileSync as readFileSync10, statSync as statSync6 } from "fs";
36192
+ import { basename as basename2, dirname as dirname4, isAbsolute, join as join17, sep as sep2 } from "path";
35521
36193
 
35522
36194
  // ../../packages/plugin-sdk/src/events.ts
35523
36195
  import { createHash as createHash5, randomUUID as randomUUID13 } from "crypto";
@@ -35528,8 +36200,8 @@ import { fileURLToPath } from "url";
35528
36200
  import { Worker } from "worker_threads";
35529
36201
 
35530
36202
  // ../../packages/plugin-sdk/src/host-floor.ts
35531
- import { readFileSync as readFileSync11 } from "fs";
35532
- import { join as join18 } from "path";
36203
+ import { readFileSync as readFileSync13 } from "fs";
36204
+ import { join as join20 } from "path";
35533
36205
 
35534
36206
  // ../../packages/plugin-sdk/src/model-governance.ts
35535
36207
  import {
@@ -35537,11 +36209,11 @@ import {
35537
36209
  fstatSync,
35538
36210
  mkdirSync as mkdirSync2,
35539
36211
  openSync as openSync2,
35540
- readFileSync as readFileSync10,
36212
+ readFileSync as readFileSync12,
35541
36213
  readSync,
35542
36214
  writeFileSync as writeFileSync5
35543
36215
  } from "fs";
35544
- import { join as join17 } from "path";
36216
+ import { join as join19 } from "path";
35545
36217
  var SESSION_MODEL_MARKER = "session-model";
35546
36218
  var DATE_SUFFIX = /-\d{8}$/;
35547
36219
  function normalizeModelId(model) {
@@ -35559,7 +36231,7 @@ function recordSessionModel(dataDir2, sessionId, model) {
35559
36231
  if (model === void 0 || model === "") return;
35560
36232
  try {
35561
36233
  mkdirSync2(dataDir2, { recursive: true, mode: DATA_DIR_MODE });
35562
- writeFileSync5(join17(dataDir2, SESSION_MODEL_MARKER), JSON.stringify({ sessionId, model }), {
36234
+ writeFileSync5(join19(dataDir2, SESSION_MODEL_MARKER), JSON.stringify({ sessionId, model }), {
35563
36235
  encoding: "utf8",
35564
36236
  mode: DATA_FILE_MODE
35565
36237
  });
@@ -35613,15 +36285,15 @@ var HOST_FLOORS = {
35613
36285
 
35614
36286
  // ../../packages/plugin-sdk/src/ignore-layers.ts
35615
36287
  var import_ignore = __toESM(require_ignore(), 1);
35616
- import { readFileSync as readFileSync12 } from "fs";
35617
- import { join as join19 } from "path";
36288
+ import { readFileSync as readFileSync14 } from "fs";
36289
+ import { join as join21 } from "path";
35618
36290
 
35619
36291
  // ../../packages/plugin-sdk/src/inventory-resolver.ts
35620
36292
  import { arch, hostname as hostname4, platform, release } from "os";
35621
36293
 
35622
36294
  // ../../packages/plugin-sdk/src/nudge.ts
35623
- import { mkdirSync as mkdirSync3, readFileSync as readFileSync13, writeFileSync as writeFileSync6 } from "fs";
35624
- import { join as join20 } from "path";
36295
+ import { mkdirSync as mkdirSync3, readFileSync as readFileSync15, writeFileSync as writeFileSync6 } from "fs";
36296
+ import { join as join22 } from "path";
35625
36297
 
35626
36298
  // ../../packages/plugin-sdk/src/paths.ts
35627
36299
  import { readdirSync as readdirSync3, realpathSync as realpathSync3 } from "fs";
@@ -35629,7 +36301,7 @@ import { basename as basename4, dirname as dirname5, sep as sep3 } from "path";
35629
36301
 
35630
36302
  // ../../packages/plugin-sdk/src/project-files.ts
35631
36303
  import { existsSync as existsSync11, readdirSync as readdirSync4 } from "fs";
35632
- import { basename as basename5, join as join21 } from "path";
36304
+ import { basename as basename5, join as join23 } from "path";
35633
36305
 
35634
36306
  // ../../packages/plugin-sdk/src/provider-env-antigravity.ts
35635
36307
  var optionalBaseUrl2 = external_exports.preprocess((v) => {
@@ -35665,16 +36337,16 @@ var THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1e3;
35665
36337
 
35666
36338
  // ../../packages/plugin-sdk/src/throttle.ts
35667
36339
  import { mkdirSync as mkdirSync4, statSync as statSync8, writeFileSync as writeFileSync7 } from "fs";
35668
- import { join as join22 } from "path";
36340
+ import { join as join24 } from "path";
35669
36341
 
35670
36342
  // src/hooks/model-switch-run.ts
35671
36343
  import { randomUUID as randomUUID16 } from "crypto";
35672
36344
 
35673
36345
  // src/hooks/model-guard.ts
35674
36346
  import { randomUUID as randomUUID15 } from "crypto";
35675
- import { readFileSync as readFileSync14, statSync as statSync9 } from "fs";
36347
+ import { readFileSync as readFileSync16, statSync as statSync9 } from "fs";
35676
36348
  import { homedir as homedir3 } from "os";
35677
- import { dirname as dirname6, join as join23 } from "path";
36349
+ import { dirname as dirname6, join as join25 } from "path";
35678
36350
  function decidePreModelSwitch(toModel, prohibitedModels) {
35679
36351
  if (toModel === void 0 || toModel === "") return null;
35680
36352
  if (!isModelProhibited(toModel, prohibitedModels)) return null;
@@ -35775,7 +36447,7 @@ function emit(output2) {
35775
36447
 
35776
36448
  // src/hooks/store-health.ts
35777
36449
  import { mkdirSync as mkdirSync5, readFileSync as readFileSync20, writeFileSync as writeFileSync8 } from "fs";
35778
- import { dirname as dirname7, join as join30 } from "path";
36450
+ import { dirname as dirname7, join as join31 } from "path";
35779
36451
 
35780
36452
  // ../../packages/remote/src/http.ts
35781
36453
  import { request as httpRequest } from "http";
@@ -35960,10 +36632,10 @@ function parsed(schema, body, route) {
35960
36632
  }
35961
36633
  function withoutTrailingSlashes(endpoint) {
35962
36634
  let end = endpoint.length;
35963
- while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH) end -= 1;
36635
+ while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH2) end -= 1;
35964
36636
  return endpoint.slice(0, end);
35965
36637
  }
35966
- var SLASH = "/".charCodeAt(0);
36638
+ var SLASH2 = "/".charCodeAt(0);
35967
36639
  function createRemoteClient(options) {
35968
36640
  const base = withoutTrailingSlashes(options.endpoint);
35969
36641
  const url2 = (route) => `${base}${route}`;
@@ -36145,11 +36817,11 @@ function withTimeout(promise2, ms) {
36145
36817
  }
36146
36818
 
36147
36819
  // ../../packages/plugin-runtime/src/attached/forward-drops.ts
36148
- import { readFileSync as readFileSync15 } from "fs";
36149
- import { join as join24 } from "path";
36820
+ import { readFileSync as readFileSync17 } from "fs";
36821
+ import { join as join26 } from "path";
36150
36822
  var FORWARD_DROPS_FILENAME = ATTACHED_FORWARD_DROPS_FILENAME;
36151
36823
  function forwardDropsPath(dataDir2) {
36152
- return join24(dataDir2, FORWARD_DROPS_FILENAME);
36824
+ return join26(dataDir2, FORWARD_DROPS_FILENAME);
36153
36825
  }
36154
36826
  function recordForwardDrops(dataDir2, count, nowMs) {
36155
36827
  if (count <= 0) return;
@@ -36167,7 +36839,7 @@ function recordForwardDrops(dataDir2, count, nowMs) {
36167
36839
  }
36168
36840
  function readForwardDrops(dataDir2) {
36169
36841
  try {
36170
- const parsed2 = JSON.parse(readFileSync15(forwardDropsPath(dataDir2), "utf8"));
36842
+ const parsed2 = JSON.parse(readFileSync17(forwardDropsPath(dataDir2), "utf8"));
36171
36843
  if (typeof parsed2 !== "object" || parsed2 === null) return null;
36172
36844
  const record2 = parsed2;
36173
36845
  if (typeof record2.droppedForwards !== "number" || !Number.isFinite(record2.droppedForwards)) {
@@ -36185,9 +36857,8 @@ function readForwardDrops(dataDir2) {
36185
36857
 
36186
36858
  // ../../packages/plugin-runtime/src/attached/forward-policy.ts
36187
36859
  import { randomUUID as randomUUID17 } from "crypto";
36188
- import { readFileSync as readFileSync16 } from "fs";
36189
36860
  import { readFile, rename, writeFile } from "fs/promises";
36190
- import { join as join25 } from "path";
36861
+ import { join as join27 } from "path";
36191
36862
  function isInvalidRequest(err) {
36192
36863
  return typeof err === "object" && err !== null && err.name === "RemoteRequestInvalid";
36193
36864
  }
@@ -36201,31 +36872,12 @@ function isServerRejection(err) {
36201
36872
  var FORWARD_BUDGET_MS = 1500;
36202
36873
  var DECISION_PATH_BUDGET_MS = 800;
36203
36874
  var BREAKER_FAILURE_THRESHOLD = 3;
36204
- var BREAKER_COOLDOWN_MS = 3e4;
36205
36875
  var CLOSED = { consecutiveFailures: 0, openedAtMs: null, lastFailure: null };
36206
- var FAILURES = /* @__PURE__ */ new Set([
36207
- "unauthorized",
36208
- "forbidden",
36209
- "unreachable"
36210
- ]);
36211
36876
  var FORWARD_STATE_FILENAME = ATTACHED_FORWARD_STATE_FILENAME;
36212
36877
  var STATE_FILENAME = FORWARD_STATE_FILENAME;
36213
- function parseBreakerState(raw, nowMs) {
36214
- try {
36215
- const parsed2 = JSON.parse(raw);
36216
- if (typeof parsed2 !== "object" || parsed2 === null) return null;
36217
- const record2 = parsed2;
36218
- const failures = typeof record2.consecutiveFailures === "number" && record2.consecutiveFailures >= 0 ? record2.consecutiveFailures : 0;
36219
- const openedAtMs = typeof record2.openedAtMs === "number" && Number.isFinite(record2.openedAtMs) && record2.openedAtMs <= nowMs ? record2.openedAtMs : null;
36220
- const lastFailure = typeof record2.lastFailure === "string" && FAILURES.has(record2.lastFailure) ? record2.lastFailure : null;
36221
- return { consecutiveFailures: failures, openedAtMs, lastFailure };
36222
- } catch {
36223
- return null;
36224
- }
36225
- }
36226
36878
  function createForwardPolicy(deps) {
36227
36879
  const now = deps.now ?? (() => Date.now());
36228
- const file2 = join25(deps.dir, STATE_FILENAME);
36880
+ const file2 = join27(deps.dir, STATE_FILENAME);
36229
36881
  let state = null;
36230
36882
  let loading = null;
36231
36883
  async function readState() {
@@ -36235,7 +36887,7 @@ function createForwardPolicy(deps) {
36235
36887
  } catch {
36236
36888
  return { ...CLOSED };
36237
36889
  }
36238
- return parseBreakerState(raw, now()) ?? { ...CLOSED };
36890
+ return parseForwardHealth(raw, now()) ?? { ...CLOSED };
36239
36891
  }
36240
36892
  async function load() {
36241
36893
  if (state !== null) return state;
@@ -36281,7 +36933,7 @@ function createForwardPolicy(deps) {
36281
36933
  };
36282
36934
  const at = now();
36283
36935
  if (current.openedAtMs !== null) {
36284
- if (at - current.openedAtMs < BREAKER_COOLDOWN_MS) {
36936
+ if (isForwardPaused(current, at)) {
36285
36937
  return { ok: false, reason: "breaker-open" };
36286
36938
  }
36287
36939
  await persist({
@@ -36818,7 +37470,18 @@ var AttachedDataGateway = class {
36818
37470
  // and the spread above would otherwise drop the field silently — which is
36819
37471
  // exactly what it did, leaving the whole control inert on every device
36820
37472
  // while every test around it stayed green.
36821
- prohibitedModels: cached2.prohibitedModels
37473
+ prohibitedModels: cached2.prohibitedModels,
37474
+ // NAMED for the same reason as the line above, and it is the same defect
37475
+ // if it is not: `...local` above spreads the DEVICE's bundle, so a field
37476
+ // only the cache carries is dropped in silence. That is what left
37477
+ // `prohibitedModels` inert on every attached device with every test
37478
+ // around it green.
37479
+ //
37480
+ // Taken from the cache rather than merged here, because merging it needs
37481
+ // the device's own SETTING — which is not a bundle field and is not in
37482
+ // scope at this seam. The runtime does that merge, raise-only, where both
37483
+ // values are in hand (createPluginRuntime's ensureInitialized).
37484
+ redactFallback: cached2.redactFallback
36822
37485
  // ALSO HONOURED FROM THE CACHE, and not a bundle field at all: each
36823
37486
  // merged policy's own `provenance`. `mergeRaiseOnly` spreads the policies
36824
37487
  // it emits, so an 'authored' policy arriving from the control plane
@@ -36946,10 +37609,6 @@ function toolAuditEvent(input2) {
36946
37609
  };
36947
37610
  }
36948
37611
 
36949
- // ../../packages/plugin-runtime/src/attached/history-state.ts
36950
- import { readFileSync as readFileSync17 } from "fs";
36951
- import { join as join26 } from "path";
36952
-
36953
37612
  // ../../packages/plugin-runtime/src/attached/history-sync.ts
36954
37613
  import { createHash as createHash6 } from "crypto";
36955
37614
  import { hostname as hostname5 } from "os";
@@ -36958,6 +37617,10 @@ import { hostname as hostname5 } from "os";
36958
37617
  var CORRELATION_ID = EventMetadata.shape.correlationId;
36959
37618
  var TRACE_ID = EventMetadata.shape.traceId;
36960
37619
  var EXCEPTION_ID = EventMetadata.shape.exceptionIds.unwrap().element;
37620
+ var REDACT_DEGRADED_TO = EventMetadata.shape.redactDegradedTo.unwrap();
37621
+
37622
+ // ../../packages/plugin-runtime/src/attached/history-sync.ts
37623
+ var CAPTURE_BATCH_BYTES = 1024 * 1024;
36961
37624
 
36962
37625
  // ../../packages/plugin-runtime/src/attached/history-sync-trigger.ts
36963
37626
  import { spawn } from "child_process";
@@ -36984,7 +37647,7 @@ function createPluginBlock(build, policyStore) {
36984
37647
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
36985
37648
  import { randomUUID as randomUUID18 } from "crypto";
36986
37649
  import { readFile as readFile2, rm, writeFile as writeFile2 } from "fs/promises";
36987
- import { join as join27 } from "path";
37650
+ import { join as join28 } from "path";
36988
37651
 
36989
37652
  // ../../packages/plugin-runtime/src/attached/atomic-publish.ts
36990
37653
  import { rename as rename2 } from "fs/promises";
@@ -37008,7 +37671,7 @@ async function publishByRename(tmp, file2, move = rename2) {
37008
37671
 
37009
37672
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
37010
37673
  function createPolicyStore(dir = dataDir()) {
37011
- const file2 = join27(dir, "policy-cache.json");
37674
+ const file2 = join28(dir, "policy-cache.json");
37012
37675
  async function read() {
37013
37676
  try {
37014
37677
  const raw = await readFile2(file2, "utf8");
@@ -37239,11 +37902,11 @@ function readStorePosture(dbPath2) {
37239
37902
  // ../../packages/plugin-runtime/src/attached/posture-store.ts
37240
37903
  import { randomUUID as randomUUID19 } from "crypto";
37241
37904
  import { readFile as readFile3, rm as rm2, writeFile as writeFile3 } from "fs/promises";
37242
- import { join as join28 } from "path";
37905
+ import { join as join29 } from "path";
37243
37906
  var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
37244
37907
  function createPostureStore(dir = settingsDir(), legacyDir) {
37245
- const file2 = join28(dir, "posture-state.json");
37246
- const legacyFile = legacyDir === void 0 ? null : join28(legacyDir, "posture-state.json");
37908
+ const file2 = join29(dir, "posture-state.json");
37909
+ const legacyFile = legacyDir === void 0 ? null : join29(legacyDir, "posture-state.json");
37247
37910
  async function persist(state) {
37248
37911
  await ensureDataDir(dir);
37249
37912
  const tmp = `${file2}.${randomUUID19()}.tmp`;
@@ -37312,7 +37975,7 @@ function createPostureStore(dir = settingsDir(), legacyDir) {
37312
37975
 
37313
37976
  // ../../packages/plugin-runtime/src/attached/sync-state.ts
37314
37977
  import { readFileSync as readFileSync19 } from "fs";
37315
- import { join as join29 } from "path";
37978
+ import { join as join30 } from "path";
37316
37979
 
37317
37980
  // ../../packages/plugin-runtime/src/attached/status.ts
37318
37981
  var REFUSAL_LINES = {
@@ -37333,6 +37996,14 @@ import { spawn as spawn2 } from "child_process";
37333
37996
  import { fileURLToPath as fileURLToPath3 } from "url";
37334
37997
  var SYNC_THROTTLE_MS = 15 * 60 * 1e3;
37335
37998
 
37999
+ // ../../packages/plugin-runtime/src/content-retention-pass.ts
38000
+ var MAX_ROWS_PER_SWEEP = 50 * 1e3;
38001
+
38002
+ // ../../packages/plugin-runtime/src/content-retention-trigger.ts
38003
+ import { spawn as spawn3 } from "child_process";
38004
+ import { fileURLToPath as fileURLToPath4 } from "url";
38005
+ var CONTENT_RETENTION_THROTTLE_MS = 60 * 60 * 1e3;
38006
+
37336
38007
  // ../../packages/plugin-runtime/src/attached/factory.ts
37337
38008
  import { hostname as hostname6 } from "os";
37338
38009
 
@@ -37797,7 +38468,7 @@ function markerDirs(dataDir2) {
37797
38468
  function alreadyClaimed(dirs, marker, sessionId) {
37798
38469
  return dirs.some((dir) => {
37799
38470
  try {
37800
- return readFileSync20(join30(dir, marker), "utf8") === sessionId;
38471
+ return readFileSync20(join31(dir, marker), "utf8") === sessionId;
37801
38472
  } catch {
37802
38473
  return false;
37803
38474
  }
@@ -37807,7 +38478,7 @@ function recordClaim(dirs, marker, sessionId) {
37807
38478
  for (const dir of dirs) {
37808
38479
  try {
37809
38480
  mkdirSync5(dir, { recursive: true, mode: DATA_DIR_MODE });
37810
- writeFileSync8(join30(dir, marker), sessionId, { mode: DATA_FILE_MODE });
38481
+ writeFileSync8(join31(dir, marker), sessionId, { mode: DATA_FILE_MODE });
37811
38482
  return;
37812
38483
  } catch {
37813
38484
  }