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