@akasecurity/ai-tc-codex 0.9.9 → 0.9.10

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.
@@ -493,11 +493,12 @@ var require_ignore = __commonJS({
493
493
 
494
494
  // ../../packages/plugin-sdk/src/config.ts
495
495
  import { existsSync as existsSync7 } from "fs";
496
- import { join as join12 } from "path";
496
+ import { join as join13 } from "path";
497
497
 
498
498
  // ../../packages/persistence/src/attached-derived.ts
499
499
  import { rmSync } from "fs";
500
500
  import { join } from "path";
501
+ var POLICY_CACHE_FILENAME = "policy-cache.json";
501
502
  var ATTACHED_FORWARD_STATE_FILENAME = "attached-state.json";
502
503
  var ATTACHED_FORWARD_DROPS_FILENAME = "attached-forward-drops.json";
503
504
 
@@ -598,6 +599,30 @@ var SQLITE_MIGRATIONS = [
598
599
  {
599
600
  tag: "0022_audit_inspection_ms",
600
601
  sql: "ALTER TABLE `audit_events` ADD `inspection_ms` integer GENERATED ALWAYS AS (json_extract(attributes, '$.inspection_ms')) VIRTUAL;"
602
+ },
603
+ {
604
+ tag: "0023_secret_vault_user_authorized",
605
+ sql: "ALTER TABLE `secret_vault` ADD `user_authorized` integer DEFAULT 0 NOT NULL;"
606
+ },
607
+ {
608
+ tag: "0024_finding_resolution_key_created_index",
609
+ sql: "DROP INDEX IF EXISTS `idx_finding_resolution_key`;--> statement-breakpoint\nCREATE INDEX `idx_finding_resolution_key_created` ON `finding_resolution` (`finding_key`,`created_at`);"
610
+ },
611
+ {
612
+ tag: "0025_audit_capture_attribute_columns",
613
+ sql: "ALTER TABLE `audit_events` ADD `source_tool` text GENERATED ALWAYS AS (json_extract(attributes, '$.source_tool')) VIRTUAL;--> statement-breakpoint\nALTER TABLE `audit_events` ADD `repo` text GENERATED ALWAYS AS (json_extract(attributes, '$.repo')) VIRTUAL;--> statement-breakpoint\nALTER TABLE `audit_events` ADD `file_path` text GENERATED ALWAYS AS (json_extract(attributes, '$.file_path')) VIRTUAL;--> statement-breakpoint\nALTER TABLE `audit_events` ADD `tool_name` text GENERATED ALWAYS AS (json_extract(attributes, '$.tool_name')) VIRTUAL;"
614
+ },
615
+ {
616
+ tag: "0026_audit_llm_call_usage_columns",
617
+ sql: "ALTER TABLE `audit_events` ADD `service_tier` text GENERATED ALWAYS AS (json_extract(attributes, '$.service_tier')) VIRTUAL;--> statement-breakpoint\nALTER TABLE `audit_events` ADD `ephemeral_1h_input_tokens` integer GENERATED ALWAYS AS (json_extract(attributes, '$.ephemeral_1h_input_tokens')) VIRTUAL;--> statement-breakpoint\nALTER TABLE `audit_events` ADD `ephemeral_5m_input_tokens` integer GENERATED ALWAYS AS (json_extract(attributes, '$.ephemeral_5m_input_tokens')) VIRTUAL;--> statement-breakpoint\nALTER TABLE `audit_events` ADD `web_search_requests` integer GENERATED ALWAYS AS (json_extract(attributes, '$.web_search_requests')) VIRTUAL;"
618
+ },
619
+ {
620
+ tag: "0027_audit_llm_usage_index",
621
+ sql: "CREATE INDEX `idx_audit_llm_usage` ON `audit_events` (`started_at`,`root_session_id`,`provider`,`model`,`service_tier`,`input_tokens`,`output_tokens`,`cache_creation_input_tokens`,`cache_read_input_tokens`,`ephemeral_1h_input_tokens`,`ephemeral_5m_input_tokens`,`web_search_requests`) WHERE event_type = 'llm_call' AND attributes IS NOT NULL;"
622
+ },
623
+ {
624
+ tag: "0028_activity_session_probe_indexes",
625
+ 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"
601
626
  }
602
627
  ];
603
628
 
@@ -22137,6 +22162,26 @@ var AttachTokenResponse = external_exports.union([
22137
22162
  AttachTokenExpired,
22138
22163
  external_exports.object({ status: printable(64) })
22139
22164
  ]);
22165
+ var DeviceCommandKind = external_exports.enum(["shares_rescan"]);
22166
+ var DeviceCommand = external_exports.object({
22167
+ id: printable(128).min(1),
22168
+ kind: DeviceCommandKind,
22169
+ issuedAt: printable(64).min(1),
22170
+ expiresAt: printable(64).min(1)
22171
+ }).strict();
22172
+ var DeviceCommandPollResponse = external_exports.object({ command: DeviceCommand.nullable() });
22173
+ var DeviceCommandFailureReason = external_exports.enum(["scan_failed", "no_projects", "expired"]);
22174
+ var DeviceCommandAckBody = external_exports.discriminatedUnion("outcome", [
22175
+ external_exports.object({
22176
+ outcome: external_exports.literal("reported"),
22177
+ projectsScanned: external_exports.number().int().nonnegative()
22178
+ }).strict(),
22179
+ external_exports.object({
22180
+ outcome: external_exports.literal("failed"),
22181
+ reason: DeviceCommandFailureReason,
22182
+ projectsScanned: external_exports.number().int().nonnegative()
22183
+ }).strict()
22184
+ ]);
22140
22185
 
22141
22186
  // ../../packages/schema/src/zod/registry.ts
22142
22187
  var Namespace = external_exports.string().regex(/^[a-z][a-z0-9-]*$/);
@@ -22303,7 +22348,7 @@ var PackManifest = external_exports.object({
22303
22348
  }).meta({ id: "PackManifest" });
22304
22349
 
22305
22350
  // ../../packages/schema/src/zod/detection.ts
22306
- var OriginEnum = external_exports.enum(["library"]).meta({ id: "OriginEnum" });
22351
+ var OriginEnum = external_exports.enum(["library", "custom"]).meta({ id: "OriginEnum" });
22307
22352
  var DetectionFilterEnum = external_exports.enum(["all", "library", "custom", "customized", "updates"]);
22308
22353
  var LibraryStateEnum = external_exports.enum(["new", "imported", "update"]).meta({ id: "LibraryStateEnum" });
22309
22354
  var DetectionCounts = external_exports.object({
@@ -22440,14 +22485,17 @@ function optional2(key, parsed2, raw) {
22440
22485
  function isStringArray(value) {
22441
22486
  return Array.isArray(value) && value.every((entry) => typeof entry === "string");
22442
22487
  }
22488
+ var ORIGIN_VALUES = { library: true, custom: true };
22489
+ function resolveOrigin(origin) {
22490
+ return origin != null && Object.hasOwn(ORIGIN_VALUES, origin) ? origin : "library";
22491
+ }
22443
22492
  function summaryToDetectionListItem(s) {
22444
22493
  return {
22445
22494
  id: `${s.namespace}/${s.packId}`,
22446
22495
  name: s.name,
22447
22496
  version: s.version,
22448
22497
  enabled: s.enabled,
22449
- origin: "library",
22450
- // v1: every installed pack is library origin
22498
+ origin: resolveOrigin(s.origin),
22451
22499
  namespace: s.namespace,
22452
22500
  packId: s.packId,
22453
22501
  ruleCount: s.ruleCount,
@@ -22499,7 +22547,7 @@ function rowToDetectionDetail(row, findingsLast30d, update) {
22499
22547
  name: row.name,
22500
22548
  version: row.version,
22501
22549
  enabled: row.enabled,
22502
- origin: "library",
22550
+ origin: resolveOrigin(row.origin),
22503
22551
  namespace: row.namespace,
22504
22552
  packId: row.packId,
22505
22553
  ruleCount: row.rules.length,
@@ -22519,16 +22567,20 @@ function splitDetectionId(id) {
22519
22567
  }
22520
22568
  function buildDetectionsList(summaries, query) {
22521
22569
  const withUpdate = summaries.filter((s) => s.latestVersion != null);
22570
+ const originOf = (s) => resolveOrigin(s.origin);
22522
22571
  const counts = {
22523
22572
  all: summaries.length,
22524
- library: summaries.length,
22525
- // all origin=library in v1
22526
- custom: 0,
22573
+ library: summaries.filter((s) => originOf(s) === "library").length,
22574
+ custom: summaries.filter((s) => originOf(s) === "custom").length,
22575
+ // No origin member produces this, so it is 0 BY CONSTRUCTION rather than by
22576
+ // omission: `customized` would mean a LIBRARY pack whose rules were edited in
22577
+ // place, and that state does not exist — editing a library pack forks it. See
22578
+ // OriginEnum.
22527
22579
  customized: 0,
22528
22580
  updates: withUpdate.length
22529
22581
  };
22530
22582
  const filter = query.filter;
22531
- let filtered = filter === "custom" || filter === "customized" ? [] : filter === "updates" ? [...withUpdate] : [...summaries];
22583
+ let filtered = filter === "customized" ? [] : filter === "custom" ? summaries.filter((s) => originOf(s) === "custom") : filter === "library" ? summaries.filter((s) => originOf(s) === "library") : filter === "updates" ? [...withUpdate] : [...summaries];
22532
22584
  if (query.q) {
22533
22585
  const q = query.q.toLowerCase();
22534
22586
  filtered = filtered.filter(
@@ -22608,8 +22660,9 @@ var Event = external_exports.object({
22608
22660
  metadata: EventMetadata.optional()
22609
22661
  }).meta({ id: "Event" });
22610
22662
  var IngestEvent = Event.meta({ id: "IngestEvent" });
22663
+ var INGEST_BATCH_MAX = 100;
22611
22664
  var IngestBatch = external_exports.object({
22612
- events: external_exports.array(IngestEvent).min(1).max(100),
22665
+ events: external_exports.array(IngestEvent).min(1).max(INGEST_BATCH_MAX),
22613
22666
  // Dedup policy for this batch. Id-dedup ALWAYS applies. 'content-hash'
22614
22667
  // additionally rejects any event whose contentHash the store has already
22615
22668
  // recorded — for re-runnable bulk ingest (worktree scan, transcript
@@ -23165,375 +23218,11 @@ var PatchInstalledPackRequest = external_exports.object({
23165
23218
  message: "At least one field must be provided"
23166
23219
  }).meta({ id: "PatchInstalledPackRequest" });
23167
23220
 
23168
- // ../../packages/schema/src/zod/vault.ts
23169
- var POINTER_FORMAT_VERSION = 2;
23170
- var CATEGORY_ALTERNATION = DetectionCategory.options.join("|");
23171
- var POINTER_TOKEN_PATTERN = new RegExp(
23172
- `\\[\\[aka:(?:${CATEGORY_ALTERNATION}):[A-Z2-7]{2,7}\\.[A-Z2-7]{26}\\.[A-Z2-7]{16}\\]\\]`
23173
- );
23174
- var POINTER_TOKEN_ANCHORED = new RegExp(`^${POINTER_TOKEN_PATTERN.source}$`);
23175
- function pointerTokenScanner() {
23176
- return new RegExp(POINTER_TOKEN_PATTERN.source, "g");
23177
- }
23178
- var PointerToken = external_exports.string().regex(POINTER_TOKEN_ANCHORED);
23179
- var ParsedPointer = external_exports.object({
23180
- category: DetectionCategory,
23181
- keyVersion: external_exports.number().int().positive(),
23182
- pointerId: external_exports.string(),
23183
- tag: external_exports.string()
23184
- });
23185
- var VaultEntry = external_exports.object({
23186
- pointerId: external_exports.string(),
23187
- // The keyed HMAC of the raw value under `exception.key`, and the epoch it was
23188
- // derived under. This is what a reveal-to-model grant matches on, and it rotates
23189
- // independently of the vault encryption key below.
23190
- valueFingerprint: external_exports.string().regex(/^[0-9a-f]{64}$/),
23191
- fingerprintKeyVersion: external_exports.number().int().positive(),
23192
- // The vault-key epoch this row's ciphertext was sealed under.
23193
- keyVersion: external_exports.number().int().positive(),
23194
- // Fixed at first mint and never updated: the same value detected later under a
23195
- // different rule's category keeps the category it was minted with, so one
23196
- // value always produces exactly one wire token.
23197
- category: DetectionCategory,
23198
- ruleId: external_exports.string(),
23199
- // Partial-reveal preview for badges and listings. Never the raw value.
23200
- maskedMatch: external_exports.string(),
23201
- provider: external_exports.string().optional(),
23202
- ciphertext: external_exports.string(),
23203
- nonce: external_exports.string(),
23204
- authTag: external_exports.string(),
23205
- // How many times this value has been detected on this machine — the reuse
23206
- // signal the vault dashboard reads. Distinct from VaultDeref.pointerCount.
23207
- occurrenceCount: external_exports.number().int().nonnegative(),
23208
- firstSeen: external_exports.string(),
23209
- lastSeen: external_exports.string()
23210
- });
23211
- var PointerDescriptor = external_exports.object({
23212
- category: DetectionCategory,
23213
- provider: external_exports.string().optional(),
23214
- maskedMatch: external_exports.string(),
23215
- occurrences: external_exports.number().int().nonnegative(),
23216
- firstSeen: external_exports.string(),
23217
- lastSeen: external_exports.string()
23218
- });
23219
- var PointerIdentity = external_exports.object({
23220
- ruleId: external_exports.string(),
23221
- valueFingerprint: external_exports.string().regex(/^[0-9a-f]{64}$/),
23222
- fingerprintKeyVersion: external_exports.number().int().positive()
23223
- });
23224
- var DetokenizeTarget = external_exports.enum(["human", "model"]);
23225
- var VaultDerefReason = external_exports.enum([
23226
- "display",
23227
- "explicit-reveal",
23228
- "view-render",
23229
- "model-input",
23230
- "remediation",
23231
- "purge"
23232
- ]);
23233
- var VaultDerefOutcome = external_exports.enum(["revealed", "refused", "unavailable"]);
23234
- var VaultDeref = external_exports.object({
23235
- id: external_exports.guid(),
23236
- pointerId: external_exports.string(),
23237
- at: external_exports.string(),
23238
- target: DetokenizeTarget,
23239
- reason: VaultDerefReason,
23240
- outcome: VaultDerefOutcome,
23241
- // Present only on a model-target crossing that a reveal grant authorized.
23242
- grantId: external_exports.string().optional(),
23243
- // How many pointers ONE batched render resolved. 1 for unbatched rows. Named
23244
- // apart from VaultEntry.occurrenceCount, which counts detections of a value.
23245
- pointerCount: external_exports.number().int().positive().default(1)
23246
- });
23247
- var VaultSightingKind = external_exports.enum([
23248
- "prompt",
23249
- "tool-input",
23250
- "tool-output",
23251
- "file",
23252
- "transcript"
23253
- ]);
23254
- var VaultSighting = external_exports.object({
23255
- location: external_exports.string(),
23256
- kind: VaultSightingKind,
23257
- firstSeen: external_exports.string(),
23258
- lastSeen: external_exports.string()
23259
- });
23260
- var VaultInventoryEntry = external_exports.object({
23261
- pointerId: external_exports.string(),
23262
- category: DetectionCategory,
23263
- provider: external_exports.string().optional(),
23264
- maskedMatch: external_exports.string(),
23265
- occurrences: external_exports.number().int().nonnegative(),
23266
- firstSeen: external_exports.string(),
23267
- lastSeen: external_exports.string(),
23268
- // The active reveal-to-model grant covering this value, when one exists —
23269
- // the inventory badges it, the row links to revocation.
23270
- revealGrantId: external_exports.string().nullable(),
23271
- sightings: external_exports.array(VaultSighting)
23272
- });
23273
- var DEFAULT_VAULT_INVENTORY_LIMIT = 50;
23274
- var DEFAULT_VAULT_DEREFS_LIMIT = 50;
23275
- var MAX_VAULT_PAGE_LIMIT = 200;
23276
- var ListVaultInventoryQuery = external_exports.object({
23277
- limit: external_exports.coerce.number().int().min(1).max(MAX_VAULT_PAGE_LIMIT).optional(),
23278
- // Opaque; names the last row of the page just served.
23279
- cursor: external_exports.string().optional()
23280
- });
23281
- var ListVaultInventoryResponse = external_exports.object({
23282
- // Vaulted values across the whole store, not just this page — cursor-
23283
- // independent, so paging never changes what the count claims.
23284
- totals: external_exports.object({ values: external_exports.number().int().nonnegative() }),
23285
- items: external_exports.array(VaultInventoryEntry),
23286
- // `null` once the last page is reached.
23287
- nextCursor: external_exports.string().nullable()
23288
- });
23289
- var ListVaultReuseQuery = external_exports.object({
23290
- limit: external_exports.coerce.number().int().min(1).max(MAX_VAULT_PAGE_LIMIT).optional(),
23291
- cursor: external_exports.string().optional()
23292
- });
23293
- var ListVaultReuseResponse = external_exports.object({
23294
- // Reused values across the whole store — the number the section's claim
23295
- // ("values detected in more than one place") is about.
23296
- totals: external_exports.object({ reused: external_exports.number().int().nonnegative() }),
23297
- items: external_exports.array(VaultInventoryEntry),
23298
- nextCursor: external_exports.string().nullable()
23299
- });
23300
- var ListVaultDerefsQuery = external_exports.object({
23301
- // Include the batched, high-volume reasons (display, view-render). Omitted
23302
- // hides them and counts them into `hiddenBatched` instead, so the model
23303
- // crossings stay visible. A real boolean, not `z.stringbool()`: this arrives
23304
- // over a Server Action, which preserves the type, never as a URL param.
23305
- includeBatched: external_exports.boolean().optional(),
23306
- limit: external_exports.coerce.number().int().min(1).max(MAX_VAULT_PAGE_LIMIT).optional(),
23307
- cursor: external_exports.string().optional()
23308
- });
23309
- var ListVaultDerefsResponse = external_exports.object({
23310
- items: external_exports.array(VaultDeref),
23311
- nextCursor: external_exports.string().nullable(),
23312
- // Display/view-render rows the query hid, over the WHOLE trail rather than
23313
- // this page — it is the count the "N hidden" line and its toggle speak for.
23314
- // Always 0 when `includeBatched` was set, since nothing was hidden.
23315
- hiddenBatched: external_exports.number().int().nonnegative()
23316
- });
23317
- var VaultKeyCustody = external_exports.string();
23318
- var VaultInlineReveal = external_exports.enum(["masked", "full", "off"]);
23319
- var VAULT_CONSENT_VERSION = 1;
23320
- var VaultConsent = external_exports.object({
23321
- acknowledgedAt: external_exports.iso.datetime(),
23322
- version: external_exports.number().int().positive()
23323
- });
23324
-
23325
- // ../../packages/schema/src/zod/local.ts
23326
- var WORKSPACE_SETTINGS_SPEC_VERSION = 6;
23327
- var MODEL_JUDGE_PAYLOAD_VERSION = 1;
23328
- var RunMode = external_exports.enum(["standalone", "attached"]);
23329
- var ControlPlaneConnection = external_exports.object({
23330
- endpoint: external_exports.string().min(1),
23331
- // Display name for the deployment, shown instead of the raw endpoint.
23332
- label: external_exports.string().min(1).optional(),
23333
- attachedAt: external_exports.iso.datetime()
23334
- }).meta({ id: "ControlPlaneConnection" });
23335
- var SimpleDetectionPolicy = external_exports.enum(["redact", "warn"]);
23336
- var HistoricalAccess = external_exports.enum(["full", "session-only"]);
23337
- var ModelJudgeConsent = external_exports.object({
23338
- acknowledgedAt: external_exports.iso.datetime(),
23339
- payloadVersion: external_exports.number().int().positive()
23340
- });
23341
- var HistorySyncConsent = external_exports.object({
23342
- acknowledgedAt: external_exports.iso.datetime(),
23343
- payloadVersion: external_exports.number().int().positive(),
23344
- endpoint: external_exports.string()
23345
- });
23346
- var WorkspaceSettings = external_exports.object({
23347
- specVersion: external_exports.number().int().positive().default(WORKSPACE_SETTINGS_SPEC_VERSION),
23348
- runMode: RunMode.default("standalone"),
23349
- // Present only while attached; a detach clears it. Its presence is what makes
23350
- // `runMode: 'attached'` mean anything — see isAttached.
23351
- controlPlane: ControlPlaneConnection.optional(),
23352
- policy: SimpleDetectionPolicy.default("redact"),
23353
- // Consent for scanning pre-install surfaces; opt-in (see HistoricalAccess).
23354
- historicalAccess: HistoricalAccess.default("session-only"),
23355
- // In-place egress extraction on the scan paths; disable to stop all Data
23356
- // Shares writes.
23357
- dataSharesInPlace: external_exports.boolean().default(true),
23358
- // Consent to keep a RECOVERABLE encrypted copy of detected values in the local
23359
- // vault, instead of destroying them. Absent by default: this is a custody
23360
- // change from one-way redaction, so it is never an assumed grant on upgrade.
23361
- // Revoking stops future vaulting; it does not erase what is already stored —
23362
- // purging the vault is the eraser.
23363
- vaultConsent: VaultConsent.optional(),
23364
- // Where the vault master key lives.
23365
- vaultKeyCustody: VaultKeyCustody.default("file"),
23366
- // How a pointer renders in assistant prose on screen (see VaultInlineReveal).
23367
- vaultInlineReveal: VaultInlineReveal.default("masked"),
23368
- // Absent until /aka:setup completes; its presence is what "onboarded" means.
23369
- onboardedAt: external_exports.iso.datetime().optional(),
23370
- // Records that the user consented to sending findings to the model API for
23371
- // the /aka:setup judge, along with the payload-shape version they agreed to.
23372
- // Absent until granted; a stale payloadVersion means the consent no longer
23373
- // covers the current payload and must be re-granted.
23374
- modelJudgeConsent: ModelJudgeConsent.optional(),
23375
- // Records that the user consented to sending the activity already recorded on
23376
- // this machine to the deployment it is attached to, along with the payload
23377
- // shape and the endpoint they agreed to. Absent until granted, and a grant for
23378
- // a different endpoint or an older payload no longer counts.
23379
- historySyncConsent: HistorySyncConsent.optional()
23380
- });
23381
- function defaultWorkspaceSettings() {
23382
- return WorkspaceSettings.parse({});
23383
- }
23384
- function isAttached(settings) {
23385
- return settings.runMode === "attached" && settings.controlPlane !== void 0;
23386
- }
23387
- function toInventoryRow(input2, id, now) {
23388
- return {
23389
- id,
23390
- objectType: input2.objectType,
23391
- location: input2.location ?? null,
23392
- title: input2.title ?? null,
23393
- hostId: input2.hostId ?? null,
23394
- attributes: JSON.stringify(input2.attributes),
23395
- firstSeen: now,
23396
- lastSeen: now
23397
- };
23398
- }
23399
- function toSourceProjectRow(input2, id, now) {
23400
- return {
23401
- id,
23402
- url: input2.url,
23403
- name: input2.name ?? null,
23404
- attributes: JSON.stringify(input2.attributes),
23405
- firstSeen: now,
23406
- lastSeen: now
23407
- };
23408
- }
23409
- function toAuditEventRow(input2) {
23410
- return {
23411
- id: input2.id,
23412
- parentId: input2.parentId ?? null,
23413
- rootSessionId: input2.rootSessionId ?? null,
23414
- eventType: input2.eventType,
23415
- hostId: input2.hostId ?? null,
23416
- harnessId: input2.harnessId ?? null,
23417
- sourceProjectId: input2.sourceProjectId ?? null,
23418
- startedAt: isoToEpochMillis(input2.startedAt),
23419
- endedAt: input2.endedAt ? isoToEpochMillis(input2.endedAt) : null,
23420
- severity: input2.severity ?? null,
23421
- priority: input2.priority ?? null,
23422
- content: input2.content ?? null,
23423
- contentHash: input2.contentHash ?? null,
23424
- attributes: input2.attributes ? JSON.stringify(input2.attributes) : null
23425
- };
23426
- }
23427
- function toClassifiedDataRow(input2, id) {
23428
- return {
23429
- id,
23430
- class: input2.class,
23431
- label: input2.label ?? null,
23432
- attributes: input2.attributes ? JSON.stringify(input2.attributes) : null
23433
- };
23434
- }
23435
- function toInspectionDefinitionRow(input2, id) {
23436
- return {
23437
- id,
23438
- ruleId: input2.ruleId,
23439
- name: input2.name,
23440
- category: input2.category,
23441
- severity: input2.severity,
23442
- definition: input2.definition,
23443
- version: input2.version
23444
- };
23445
- }
23446
- function toInspectionFindingRow(input2) {
23447
- return {
23448
- id: input2.id,
23449
- auditEventId: input2.auditEventId,
23450
- inspectionDefinitionId: input2.inspectionDefinitionId,
23451
- classifiedDataId: input2.classifiedDataId ?? null,
23452
- spanStart: input2.span.start,
23453
- spanEnd: input2.span.end,
23454
- maskedMatch: input2.maskedMatch,
23455
- actionTaken: input2.actionTaken,
23456
- confidence: input2.confidence,
23457
- findingKey: input2.findingKey ?? null,
23458
- firstDetectedAt: input2.firstDetectedAt ? isoToEpochMillis(input2.firstDetectedAt) : null
23459
- };
23460
- }
23461
- function toCaptureAttributes(event) {
23462
- const metadata = event.metadata;
23463
- return {
23464
- source_tool: event.sourceTool,
23465
- ...metadata?.repo !== void 0 ? { repo: metadata.repo } : {},
23466
- ...metadata?.filePath !== void 0 ? { file_path: metadata.filePath } : {},
23467
- ...metadata?.toolName !== void 0 ? { tool_name: metadata.toolName } : {},
23468
- ...metadata?.gitignored !== void 0 ? { gitignored: metadata.gitignored } : {},
23469
- ...metadata?.wholeFile !== void 0 ? { whole_file: metadata.wholeFile } : {},
23470
- ...metadata?.correlationId !== void 0 ? { correlation_id: metadata.correlationId } : {},
23471
- ...metadata?.traceId !== void 0 ? { trace_id: metadata.traceId } : {},
23472
- ...metadata?.exceptionIds !== void 0 ? { exception_ids: metadata.exceptionIds } : {},
23473
- ...metadata?.inspectionMs !== void 0 ? { inspection_ms: metadata.inspectionMs } : {},
23474
- // `model`/`turnIndex` have no dedicated CaptureAttributes field (no writer
23475
- // has ever populated either), but every legacy metadata key still rides
23476
- // the bag rather than being silently dropped — CaptureAttributes'
23477
- // `.catchall(z.unknown())` carries the long tail.
23478
- ...metadata?.model !== void 0 ? { model: metadata.model } : {},
23479
- ...metadata?.turnIndex !== void 0 ? { turn_index: metadata.turnIndex } : {}
23480
- };
23481
- }
23482
- function captureDefinitionVersion(finding) {
23483
- return `capture/${finding.category}/${finding.severity}`;
23484
- }
23485
- function toCaptureDefinitionInput(finding) {
23486
- return {
23487
- ruleId: finding.ruleId,
23488
- version: captureDefinitionVersion(finding),
23489
- name: finding.ruleId,
23490
- category: finding.category,
23491
- severity: finding.severity,
23492
- definition: JSON.stringify({ ruleId: finding.ruleId })
23493
- };
23494
- }
23495
-
23496
- // ../../packages/schema/src/zod/managed.ts
23497
- var MANAGED_SETTINGS_FILENAME = "managed-settings.json";
23498
- var MANAGED_SETTINGS_SPEC_VERSION = 1;
23499
- var ManagedSettingKey = external_exports.enum([
23500
- "runMode",
23501
- "historicalAccess",
23502
- "vaultConsent",
23503
- "vaultKeyCustody",
23504
- "vaultInlineReveal",
23505
- "modelJudgeConsent",
23506
- "dataSharesInPlace"
23507
- ]).meta({ id: "ManagedSettingKey" });
23508
- var ManagedSettingsValues = external_exports.object({
23509
- runMode: external_exports.enum(["standalone", "attached"]).optional(),
23510
- controlPlane: external_exports.object({
23511
- endpoint: external_exports.string().min(1),
23512
- label: external_exports.string().min(1).optional()
23513
- }).optional(),
23514
- historicalAccess: external_exports.enum(["full", "session-only"]).optional(),
23515
- vaultConsent: external_exports.boolean().optional(),
23516
- vaultKeyCustody: external_exports.enum(["file", "keychain"]).optional(),
23517
- vaultInlineReveal: external_exports.enum(["masked", "full", "off"]).optional(),
23518
- modelJudgeConsent: external_exports.boolean().optional(),
23519
- dataSharesInPlace: external_exports.boolean().optional()
23520
- }).meta({ id: "ManagedSettingsValues" });
23521
- var ManagedSettings = external_exports.object({
23522
- specVersion: external_exports.number().int().positive().default(MANAGED_SETTINGS_SPEC_VERSION),
23523
- // Shown on every locked control, so the user can tell an administrative
23524
- // decision from a bug. Absent renders as a generic "your organization".
23525
- organization: external_exports.string().min(1).optional(),
23526
- // What the administrator pinned.
23527
- values: ManagedSettingsValues.default({}),
23528
- // Which of those the user may not change. A key here with no matching value
23529
- // freezes whatever the user last chose; a value with no lock is a DEFAULT
23530
- // the user may still override. The two are separable on purpose.
23531
- lockedFields: external_exports.array(ManagedSettingKey).default([])
23532
- }).meta({ id: "ManagedSettings" });
23533
-
23534
23221
  // ../../packages/schema/src/zod/policy.ts
23535
23222
  var PolicyScope = external_exports.enum(["global", "repo", "user"]).meta({ id: "PolicyScope" });
23536
23223
  var PolicyTarget = external_exports.union([external_exports.object({ ruleId: external_exports.string() }), external_exports.object({ category: DetectionCategory })]).meta({ id: "PolicyTarget" });
23224
+ var PolicyKind = external_exports.enum(["builtin", "custom"]).meta({ id: "PolicyKind" });
23225
+ var PolicyProvenance = external_exports.enum(["builtin", "authored"]).meta({ id: "PolicyProvenance" });
23537
23226
  var Policy = external_exports.object({
23538
23227
  id: external_exports.guid(),
23539
23228
  scope: PolicyScope,
@@ -23543,7 +23232,27 @@ var Policy = external_exports.object({
23543
23232
  customKeywords: external_exports.array(external_exports.string()).optional(),
23544
23233
  // Display name — optional so older policy rows without name still parse.
23545
23234
  // Added for the findings API (policy.name column migration).
23546
- name: external_exports.string().optional()
23235
+ name: external_exports.string().optional(),
23236
+ // Whether an AUTHORED policy governs this row's target — not a claim about
23237
+ // which row this is. A producer that collapses several rows onto one target
23238
+ // must carry the marker onto whichever row survives, or the collapse decides
23239
+ // the answer; a survivor may therefore be a built-in expansion still marked
23240
+ // 'authored' because an authored sibling targeted the same thing.
23241
+ // Optional so an older producer — and an older on-disk cache — still parses;
23242
+ // absent reads as 'builtin', which is the behaviour that predates the field.
23243
+ //
23244
+ // Deliberately NOT `kind`/PolicyKind: that name and that enum answer which
23245
+ // built-in archetype catalog entry a policy is, which every catalog surface
23246
+ // reads and which a caller may state. This one is a statement the PRODUCER
23247
+ // of a bundle makes about a row, and only the bundle builder ever stamps it
23248
+ // — the CRUD routes neither accept nor set it.
23249
+ //
23250
+ // A device consumes this in exactly one direction: an 'authored' policy
23251
+ // arriving from a control plane marks the rules it targets as not
23252
+ // locally re-assignable. That can only ever ADD a refusal, never relax one,
23253
+ // which is what makes it safe to honour from an unsigned cache — the same
23254
+ // test `prohibitedModels` passes and `reversibleRuleIds` fails.
23255
+ provenance: PolicyProvenance.optional()
23547
23256
  }).meta({ id: "Policy" });
23548
23257
  var PolicyBundle = external_exports.object({
23549
23258
  version: external_exports.string(),
@@ -23595,6 +23304,12 @@ var PolicyBundle = external_exports.object({
23595
23304
  customKeywords: external_exports.array(external_exports.string()),
23596
23305
  fetchedAt: external_exports.iso.datetime()
23597
23306
  }).meta({ id: "PolicyBundle" });
23307
+ var POLICY_BUNDLE_SHAPE_ID = [
23308
+ ...Object.keys(PolicyBundle.shape),
23309
+ ...Object.keys(Policy.shape).map((key) => `policies.${key}`),
23310
+ ...PolicyTarget.options.flatMap((member) => "shape" in member ? Object.keys(member.shape) : []).map((key) => `policies.target.${key}`),
23311
+ ...Object.keys(ExceptionBundleEntry.shape).map((key) => `exceptions.${key}`)
23312
+ ].sort().join(",");
23598
23313
  var OBSERVE_ONLY_CATEGORIES = ["config"];
23599
23314
  var ENFORCEABLE_CATEGORIES = DetectionCategory.options.filter((c) => !OBSERVE_ONLY_CATEGORIES.includes(c));
23600
23315
  var CATEGORY_PEAK_SEVERITY = {
@@ -23615,9 +23330,11 @@ function severityFloorPolicy(category) {
23615
23330
  const peak = CATEGORY_PEAK_SEVERITY[category];
23616
23331
  return peak === "critical" || peak === "high" ? "warn" : "monitor";
23617
23332
  }
23618
- var PolicyKind = external_exports.enum(["builtin", "custom"]).meta({ id: "PolicyKind" });
23619
23333
  var KNOWN_BUILTIN_IDS = ["monitor", "warn", "redact", "vault", "block"];
23620
23334
  var BuiltinPolicyId = external_exports.enum(KNOWN_BUILTIN_IDS).meta({ id: "BuiltinPolicyId" });
23335
+ var RedactFallback = BuiltinPolicyId.extract(["monitor", "warn", "block"]).meta({
23336
+ id: "RedactFallback"
23337
+ });
23621
23338
  var BUILTIN_ORDER = KNOWN_BUILTIN_IDS;
23622
23339
  var BUILTIN_POLICY_SPECS = {
23623
23340
  monitor: {
@@ -23654,6 +23371,42 @@ var BUILTIN_POLICY_SPECS = {
23654
23371
  function builtinPolicyToAction(id) {
23655
23372
  return BUILTIN_POLICY_SPECS[id].action;
23656
23373
  }
23374
+ var PALETTE_WEAKEST_FIRST = [
23375
+ ...new Set(KNOWN_BUILTIN_IDS.map(builtinPolicyToAction))
23376
+ ];
23377
+ var BELOW_PALETTE = ACTION_TAKEN_KEYS.filter(
23378
+ (action) => !PALETTE_WEAKEST_FIRST.includes(action)
23379
+ );
23380
+ var ACTION_STRENGTH_ORDER = [
23381
+ ...BELOW_PALETTE,
23382
+ ...PALETTE_WEAKEST_FIRST
23383
+ ];
23384
+ function actionRank(action) {
23385
+ return ACTION_STRENGTH_ORDER.indexOf(action);
23386
+ }
23387
+ function isActionAtLeast(action, floor) {
23388
+ return actionRank(action) >= actionRank(floor);
23389
+ }
23390
+ function strongerAction(a, b) {
23391
+ return actionRank(a) >= actionRank(b) ? a : b;
23392
+ }
23393
+ function weakestBuiltinAtLeast(floor) {
23394
+ return KNOWN_BUILTIN_IDS.find((id) => isActionAtLeast(builtinPolicyToAction(id), floor)) ?? "block";
23395
+ }
23396
+ var PackPolicyFloor = external_exports.object({
23397
+ /**
23398
+ * The weakest archetype the device may assign. Stated as a BuiltinPolicyId
23399
+ * rather than a raw ActionTaken because that is the vocabulary the user
23400
+ * picks from — a floor a UI cannot name is one it cannot explain.
23401
+ */
23402
+ floor: BuiltinPolicyId,
23403
+ /**
23404
+ * True when the organization AUTHORED a policy governing this pack rather
23405
+ * than stating a minimum: it gave the answer, so the pack is not
23406
+ * re-assignable locally in either direction.
23407
+ */
23408
+ locked: external_exports.boolean()
23409
+ }).describe("PackPolicyFloor");
23657
23410
  var CATEGORY_EXPRESSIBLE_IDS = KNOWN_BUILTIN_IDS.filter(
23658
23411
  (id) => !BUILTIN_POLICY_SPECS[id].reversible
23659
23412
  );
@@ -23711,6 +23464,397 @@ var PolicyStatsResponse = external_exports.object({
23711
23464
  detectionsGoverned: external_exports.number().int().nonnegative()
23712
23465
  }).meta({ id: "PolicyStatsResponse" });
23713
23466
 
23467
+ // ../../packages/schema/src/zod/vault.ts
23468
+ var POINTER_FORMAT_VERSION = 2;
23469
+ var CATEGORY_ALTERNATION = DetectionCategory.options.join("|");
23470
+ var POINTER_TOKEN_PATTERN = new RegExp(
23471
+ `\\[\\[aka:(?:${CATEGORY_ALTERNATION}):[A-Z2-7]{2,7}\\.[A-Z2-7]{26}\\.[A-Z2-7]{16}\\]\\]`
23472
+ );
23473
+ var POINTER_TOKEN_ANCHORED = new RegExp(`^${POINTER_TOKEN_PATTERN.source}$`);
23474
+ function pointerTokenScanner() {
23475
+ return new RegExp(POINTER_TOKEN_PATTERN.source, "g");
23476
+ }
23477
+ var PointerToken = external_exports.string().regex(POINTER_TOKEN_ANCHORED);
23478
+ var ParsedPointer = external_exports.object({
23479
+ category: DetectionCategory,
23480
+ keyVersion: external_exports.number().int().positive(),
23481
+ pointerId: external_exports.string(),
23482
+ tag: external_exports.string()
23483
+ });
23484
+ var VaultEntry = external_exports.object({
23485
+ pointerId: external_exports.string(),
23486
+ // The keyed HMAC of the raw value under `exception.key`, and the epoch it was
23487
+ // derived under. This is what a reveal-to-model grant matches on, and it rotates
23488
+ // independently of the vault encryption key below.
23489
+ valueFingerprint: external_exports.string().regex(/^[0-9a-f]{64}$/),
23490
+ fingerprintKeyVersion: external_exports.number().int().positive(),
23491
+ // The vault-key epoch this row's ciphertext was sealed under.
23492
+ keyVersion: external_exports.number().int().positive(),
23493
+ // Fixed at first mint and never updated: the same value detected later under a
23494
+ // different rule's category keeps the category it was minted with, so one
23495
+ // value always produces exactly one wire token.
23496
+ category: DetectionCategory,
23497
+ ruleId: external_exports.string(),
23498
+ // Partial-reveal preview for badges and listings. Never the raw value.
23499
+ maskedMatch: external_exports.string(),
23500
+ provider: external_exports.string().optional(),
23501
+ ciphertext: external_exports.string(),
23502
+ nonce: external_exports.string(),
23503
+ authTag: external_exports.string(),
23504
+ // How many times this value has been detected on this machine — the reuse
23505
+ // signal the vault dashboard reads. Distinct from VaultDeref.pointerCount.
23506
+ occurrenceCount: external_exports.number().int().nonnegative(),
23507
+ // True when a PERSON asked for this value to be replaced — the surfaced-
23508
+ // secrets strike — rather than a pack enforcing its assignment. One value is
23509
+ // one row however many paths vault it, so this is what tells a policy sweep
23510
+ // that the row carries somebody's own instruction and not just an assignment
23511
+ // that has since been lowered. STICKY and MONOTONIC: a later automatic
23512
+ // vaulting of the same value must never clear it — what the user said about
23513
+ // the value does not expire.
23514
+ userAuthorized: external_exports.boolean(),
23515
+ firstSeen: external_exports.string(),
23516
+ lastSeen: external_exports.string()
23517
+ });
23518
+ var PointerDescriptor = external_exports.object({
23519
+ category: DetectionCategory,
23520
+ provider: external_exports.string().optional(),
23521
+ maskedMatch: external_exports.string(),
23522
+ occurrences: external_exports.number().int().nonnegative(),
23523
+ firstSeen: external_exports.string(),
23524
+ lastSeen: external_exports.string()
23525
+ });
23526
+ var PointerIdentity = external_exports.object({
23527
+ ruleId: external_exports.string(),
23528
+ valueFingerprint: external_exports.string().regex(/^[0-9a-f]{64}$/),
23529
+ fingerprintKeyVersion: external_exports.number().int().positive()
23530
+ });
23531
+ var DetokenizeTarget = external_exports.enum(["human", "model"]);
23532
+ var VaultDerefReason = external_exports.enum([
23533
+ "display",
23534
+ "explicit-reveal",
23535
+ "view-render",
23536
+ "model-input",
23537
+ "remediation",
23538
+ "purge"
23539
+ ]);
23540
+ var VaultDerefOutcome = external_exports.enum(["revealed", "refused", "unavailable"]);
23541
+ var VaultDeref = external_exports.object({
23542
+ id: external_exports.guid(),
23543
+ pointerId: external_exports.string(),
23544
+ at: external_exports.string(),
23545
+ target: DetokenizeTarget,
23546
+ reason: VaultDerefReason,
23547
+ outcome: VaultDerefOutcome,
23548
+ // Present only on a model-target crossing that a reveal grant authorized.
23549
+ grantId: external_exports.string().optional(),
23550
+ // How many pointers ONE batched render resolved. 1 for unbatched rows. Named
23551
+ // apart from VaultEntry.occurrenceCount, which counts detections of a value.
23552
+ pointerCount: external_exports.number().int().positive().default(1)
23553
+ });
23554
+ var VaultSightingKind = external_exports.enum([
23555
+ "prompt",
23556
+ "tool-input",
23557
+ "tool-output",
23558
+ "file",
23559
+ "transcript"
23560
+ ]);
23561
+ var VaultSighting = external_exports.object({
23562
+ location: external_exports.string(),
23563
+ kind: VaultSightingKind,
23564
+ firstSeen: external_exports.string(),
23565
+ lastSeen: external_exports.string()
23566
+ });
23567
+ var VaultInventoryEntry = external_exports.object({
23568
+ pointerId: external_exports.string(),
23569
+ category: DetectionCategory,
23570
+ provider: external_exports.string().optional(),
23571
+ maskedMatch: external_exports.string(),
23572
+ occurrences: external_exports.number().int().nonnegative(),
23573
+ firstSeen: external_exports.string(),
23574
+ lastSeen: external_exports.string(),
23575
+ // The active reveal-to-model grant covering this value, when one exists —
23576
+ // the inventory badges it, the row links to revocation.
23577
+ revealGrantId: external_exports.string().nullable(),
23578
+ sightings: external_exports.array(VaultSighting)
23579
+ });
23580
+ var DEFAULT_VAULT_INVENTORY_LIMIT = 50;
23581
+ var DEFAULT_VAULT_DEREFS_LIMIT = 50;
23582
+ var MAX_VAULT_PAGE_LIMIT = 200;
23583
+ var ListVaultInventoryQuery = external_exports.object({
23584
+ limit: external_exports.coerce.number().int().min(1).max(MAX_VAULT_PAGE_LIMIT).optional(),
23585
+ // Opaque; names the last row of the page just served.
23586
+ cursor: external_exports.string().optional()
23587
+ });
23588
+ var ListVaultInventoryResponse = external_exports.object({
23589
+ // Vaulted values across the whole store, not just this page — cursor-
23590
+ // independent, so paging never changes what the count claims.
23591
+ totals: external_exports.object({ values: external_exports.number().int().nonnegative() }),
23592
+ items: external_exports.array(VaultInventoryEntry),
23593
+ // `null` once the last page is reached.
23594
+ nextCursor: external_exports.string().nullable()
23595
+ });
23596
+ var ListVaultReuseQuery = external_exports.object({
23597
+ limit: external_exports.coerce.number().int().min(1).max(MAX_VAULT_PAGE_LIMIT).optional(),
23598
+ cursor: external_exports.string().optional()
23599
+ });
23600
+ var ListVaultReuseResponse = external_exports.object({
23601
+ // Reused values across the whole store — the number the section's claim
23602
+ // ("values detected in more than one place") is about.
23603
+ totals: external_exports.object({ reused: external_exports.number().int().nonnegative() }),
23604
+ items: external_exports.array(VaultInventoryEntry),
23605
+ nextCursor: external_exports.string().nullable()
23606
+ });
23607
+ var ListVaultDerefsQuery = external_exports.object({
23608
+ // Include the batched, high-volume reasons (display, view-render). Omitted
23609
+ // hides them and counts them into `hiddenBatched` instead, so the model
23610
+ // crossings stay visible. A real boolean, not `z.stringbool()`: this arrives
23611
+ // over a Server Action, which preserves the type, never as a URL param.
23612
+ includeBatched: external_exports.boolean().optional(),
23613
+ limit: external_exports.coerce.number().int().min(1).max(MAX_VAULT_PAGE_LIMIT).optional(),
23614
+ cursor: external_exports.string().optional()
23615
+ });
23616
+ var ListVaultDerefsResponse = external_exports.object({
23617
+ items: external_exports.array(VaultDeref),
23618
+ nextCursor: external_exports.string().nullable(),
23619
+ // Display/view-render rows the query hid, over the WHOLE trail rather than
23620
+ // this page — it is the count the "N hidden" line and its toggle speak for.
23621
+ // Always 0 when `includeBatched` was set, since nothing was hidden.
23622
+ hiddenBatched: external_exports.number().int().nonnegative()
23623
+ });
23624
+ var VaultKeyCustody = external_exports.string();
23625
+ var VaultInlineReveal = external_exports.enum(["masked", "full", "off"]);
23626
+ var VAULT_CONSENT_VERSION = 1;
23627
+ var VaultConsent = external_exports.object({
23628
+ acknowledgedAt: external_exports.iso.datetime(),
23629
+ version: external_exports.number().int().positive()
23630
+ });
23631
+
23632
+ // ../../packages/schema/src/zod/local.ts
23633
+ var WORKSPACE_SETTINGS_SPEC_VERSION = 7;
23634
+ var MODEL_JUDGE_PAYLOAD_VERSION = 1;
23635
+ var RunMode = external_exports.enum(["standalone", "attached"]);
23636
+ var ControlPlaneConnection = external_exports.object({
23637
+ endpoint: external_exports.string().min(1),
23638
+ // Display name for the deployment, shown instead of the raw endpoint.
23639
+ label: external_exports.string().min(1).optional(),
23640
+ attachedAt: external_exports.iso.datetime()
23641
+ }).meta({ id: "ControlPlaneConnection" });
23642
+ var SimpleDetectionPolicy = external_exports.enum(["redact", "warn"]);
23643
+ var HistoricalAccess = external_exports.enum(["full", "session-only"]);
23644
+ var ModelJudgeConsent = external_exports.object({
23645
+ acknowledgedAt: external_exports.iso.datetime(),
23646
+ payloadVersion: external_exports.number().int().positive()
23647
+ });
23648
+ var HistorySyncConsent = external_exports.object({
23649
+ acknowledgedAt: external_exports.iso.datetime(),
23650
+ payloadVersion: external_exports.number().int().positive(),
23651
+ endpoint: external_exports.string()
23652
+ });
23653
+ var WorkspaceSettings = external_exports.object({
23654
+ specVersion: external_exports.number().int().positive().default(WORKSPACE_SETTINGS_SPEC_VERSION),
23655
+ runMode: RunMode.default("standalone"),
23656
+ // Present only while attached; a detach clears it. Its presence is what makes
23657
+ // `runMode: 'attached'` mean anything — see isAttached.
23658
+ controlPlane: ControlPlaneConnection.optional(),
23659
+ policy: SimpleDetectionPolicy.default("redact"),
23660
+ // Consent for scanning pre-install surfaces; opt-in (see HistoricalAccess).
23661
+ historicalAccess: HistoricalAccess.default("session-only"),
23662
+ // In-place egress extraction on the scan paths; disable to stop all Data
23663
+ // Shares writes.
23664
+ dataSharesInPlace: external_exports.boolean().default(true),
23665
+ // Consent to keep a RECOVERABLE encrypted copy of detected values in the local
23666
+ // vault, instead of destroying them. Absent by default: this is a custody
23667
+ // change from one-way redaction, so it is never an assumed grant on upgrade.
23668
+ // Revoking stops future vaulting; it does not erase what is already stored —
23669
+ // purging the vault is the eraser.
23670
+ vaultConsent: VaultConsent.optional(),
23671
+ // Where the vault master key lives.
23672
+ vaultKeyCustody: VaultKeyCustody.default("file"),
23673
+ // How a pointer renders in assistant prose on screen (see VaultInlineReveal).
23674
+ vaultInlineReveal: VaultInlineReveal.default("masked"),
23675
+ // What a `redact` policy degrades to on a FIELD the host cannot rewrite in
23676
+ // place. Not a handling policy: the policy has already resolved to redact,
23677
+ // and this only says what happens when the host offers no channel to carry it
23678
+ // out — Antigravity's PreToolUse has no updatedInput at all, and Codex and
23679
+ // Claude Code decline to mask a field that EXECUTES because masking would
23680
+ // change what runs. Per FIELD rather than per host, so a host that can
23681
+ // rewrite some inputs keeps true redaction on those.
23682
+ //
23683
+ // Spelled in the built-in policy vocabulary rather than as a fresh enum, so
23684
+ // an attached machine's merge is `strongerAction` over the one action ladder
23685
+ // and no second rank order exists to drift from it. 'deny' is a host wire
23686
+ // word and stays out of the stored value.
23687
+ redactFallback: RedactFallback.default("warn"),
23688
+ // Absent until /aka:setup completes; its presence is what "onboarded" means.
23689
+ onboardedAt: external_exports.iso.datetime().optional(),
23690
+ // Records that the user consented to sending findings to the model API for
23691
+ // the /aka:setup judge, along with the payload-shape version they agreed to.
23692
+ // Absent until granted; a stale payloadVersion means the consent no longer
23693
+ // covers the current payload and must be re-granted.
23694
+ modelJudgeConsent: ModelJudgeConsent.optional(),
23695
+ // Records that the user consented to the DEFERRED send — the outbox — along
23696
+ // with the payload shape and the endpoint they agreed to. Since payload v2
23697
+ // that covers both the pre-attach backlog and undelivered captures (which
23698
+ // carry prompt/reply text in `content`); the key name predates the widening.
23699
+ // Absent until granted, and a grant for a different endpoint or an older
23700
+ // payload no longer counts.
23701
+ historySyncConsent: HistorySyncConsent.optional()
23702
+ });
23703
+ function defaultWorkspaceSettings() {
23704
+ return WorkspaceSettings.parse({});
23705
+ }
23706
+ function isAttached(settings) {
23707
+ return settings.runMode === "attached" && settings.controlPlane !== void 0;
23708
+ }
23709
+ function toInventoryRow(input2, id, now) {
23710
+ return {
23711
+ id,
23712
+ objectType: input2.objectType,
23713
+ location: input2.location ?? null,
23714
+ title: input2.title ?? null,
23715
+ hostId: input2.hostId ?? null,
23716
+ attributes: JSON.stringify(input2.attributes),
23717
+ firstSeen: now,
23718
+ lastSeen: now
23719
+ };
23720
+ }
23721
+ function toSourceProjectRow(input2, id, now) {
23722
+ return {
23723
+ id,
23724
+ url: input2.url,
23725
+ name: input2.name ?? null,
23726
+ attributes: JSON.stringify(input2.attributes),
23727
+ firstSeen: now,
23728
+ lastSeen: now
23729
+ };
23730
+ }
23731
+ function toAuditEventRow(input2) {
23732
+ return {
23733
+ id: input2.id,
23734
+ parentId: input2.parentId ?? null,
23735
+ rootSessionId: input2.rootSessionId ?? null,
23736
+ eventType: input2.eventType,
23737
+ hostId: input2.hostId ?? null,
23738
+ harnessId: input2.harnessId ?? null,
23739
+ sourceProjectId: input2.sourceProjectId ?? null,
23740
+ startedAt: isoToEpochMillis(input2.startedAt),
23741
+ endedAt: input2.endedAt ? isoToEpochMillis(input2.endedAt) : null,
23742
+ severity: input2.severity ?? null,
23743
+ priority: input2.priority ?? null,
23744
+ content: input2.content ?? null,
23745
+ contentHash: input2.contentHash ?? null,
23746
+ attributes: input2.attributes ? JSON.stringify(input2.attributes) : null
23747
+ };
23748
+ }
23749
+ function toClassifiedDataRow(input2, id) {
23750
+ return {
23751
+ id,
23752
+ class: input2.class,
23753
+ label: input2.label ?? null,
23754
+ attributes: input2.attributes ? JSON.stringify(input2.attributes) : null
23755
+ };
23756
+ }
23757
+ function toInspectionDefinitionRow(input2, id) {
23758
+ return {
23759
+ id,
23760
+ ruleId: input2.ruleId,
23761
+ name: input2.name,
23762
+ category: input2.category,
23763
+ severity: input2.severity,
23764
+ definition: input2.definition,
23765
+ version: input2.version
23766
+ };
23767
+ }
23768
+ function toInspectionFindingRow(input2) {
23769
+ return {
23770
+ id: input2.id,
23771
+ auditEventId: input2.auditEventId,
23772
+ inspectionDefinitionId: input2.inspectionDefinitionId,
23773
+ classifiedDataId: input2.classifiedDataId ?? null,
23774
+ spanStart: input2.span.start,
23775
+ spanEnd: input2.span.end,
23776
+ maskedMatch: input2.maskedMatch,
23777
+ actionTaken: input2.actionTaken,
23778
+ confidence: input2.confidence,
23779
+ findingKey: input2.findingKey ?? null,
23780
+ firstDetectedAt: input2.firstDetectedAt ? isoToEpochMillis(input2.firstDetectedAt) : null
23781
+ };
23782
+ }
23783
+ function toCaptureAttributes(event) {
23784
+ const metadata = event.metadata;
23785
+ return {
23786
+ source_tool: event.sourceTool,
23787
+ ...metadata?.repo !== void 0 ? { repo: metadata.repo } : {},
23788
+ ...metadata?.filePath !== void 0 ? { file_path: metadata.filePath } : {},
23789
+ ...metadata?.toolName !== void 0 ? { tool_name: metadata.toolName } : {},
23790
+ ...metadata?.gitignored !== void 0 ? { gitignored: metadata.gitignored } : {},
23791
+ ...metadata?.wholeFile !== void 0 ? { whole_file: metadata.wholeFile } : {},
23792
+ ...metadata?.correlationId !== void 0 ? { correlation_id: metadata.correlationId } : {},
23793
+ ...metadata?.traceId !== void 0 ? { trace_id: metadata.traceId } : {},
23794
+ ...metadata?.exceptionIds !== void 0 ? { exception_ids: metadata.exceptionIds } : {},
23795
+ ...metadata?.inspectionMs !== void 0 ? { inspection_ms: metadata.inspectionMs } : {},
23796
+ // `model`/`turnIndex` have no dedicated CaptureAttributes field (no writer
23797
+ // has ever populated either), but every legacy metadata key still rides
23798
+ // the bag rather than being silently dropped — CaptureAttributes'
23799
+ // `.catchall(z.unknown())` carries the long tail.
23800
+ ...metadata?.model !== void 0 ? { model: metadata.model } : {},
23801
+ ...metadata?.turnIndex !== void 0 ? { turn_index: metadata.turnIndex } : {}
23802
+ };
23803
+ }
23804
+ function captureDefinitionVersion(finding) {
23805
+ return `capture/${finding.category}/${finding.severity}`;
23806
+ }
23807
+ function toCaptureDefinitionInput(finding) {
23808
+ return {
23809
+ ruleId: finding.ruleId,
23810
+ version: captureDefinitionVersion(finding),
23811
+ name: finding.ruleId,
23812
+ category: finding.category,
23813
+ severity: finding.severity,
23814
+ definition: JSON.stringify({ ruleId: finding.ruleId })
23815
+ };
23816
+ }
23817
+
23818
+ // ../../packages/schema/src/zod/managed.ts
23819
+ var MANAGED_SETTINGS_FILENAME = "managed-settings.json";
23820
+ var MANAGED_SETTINGS_SPEC_VERSION = 1;
23821
+ var ManagedSettingKey = external_exports.enum([
23822
+ "runMode",
23823
+ "historicalAccess",
23824
+ "vaultConsent",
23825
+ "vaultKeyCustody",
23826
+ "vaultInlineReveal",
23827
+ "modelJudgeConsent",
23828
+ "dataSharesInPlace",
23829
+ "redactFallback"
23830
+ ]).meta({ id: "ManagedSettingKey" });
23831
+ var ManagedSettingsValues = external_exports.object({
23832
+ runMode: external_exports.enum(["standalone", "attached"]).optional(),
23833
+ controlPlane: external_exports.object({
23834
+ endpoint: external_exports.string().min(1),
23835
+ label: external_exports.string().min(1).optional()
23836
+ }).optional(),
23837
+ historicalAccess: external_exports.enum(["full", "session-only"]).optional(),
23838
+ vaultConsent: external_exports.boolean().optional(),
23839
+ vaultKeyCustody: external_exports.enum(["file", "keychain"]).optional(),
23840
+ vaultInlineReveal: external_exports.enum(["masked", "full", "off"]).optional(),
23841
+ modelJudgeConsent: external_exports.boolean().optional(),
23842
+ dataSharesInPlace: external_exports.boolean().optional(),
23843
+ redactFallback: RedactFallback.optional()
23844
+ }).meta({ id: "ManagedSettingsValues" });
23845
+ var ManagedSettings = external_exports.object({
23846
+ specVersion: external_exports.number().int().positive().default(MANAGED_SETTINGS_SPEC_VERSION),
23847
+ // Shown on every locked control, so the user can tell an administrative
23848
+ // decision from a bug. Absent renders as a generic "your organization".
23849
+ organization: external_exports.string().min(1).optional(),
23850
+ // What the administrator pinned.
23851
+ values: ManagedSettingsValues.default({}),
23852
+ // Which of those the user may not change. A key here with no matching value
23853
+ // freezes whatever the user last chose; a value with no lock is a DEFAULT
23854
+ // the user may still override. The two are separable on purpose.
23855
+ lockedFields: external_exports.array(ManagedSettingKey).default([])
23856
+ }).meta({ id: "ManagedSettings" });
23857
+
23714
23858
  // ../../packages/schema/src/zod/project-files.ts
23715
23859
  var ProjectFileInput = external_exports.object({
23716
23860
  path: external_exports.string().min(1),
@@ -23956,10 +24100,12 @@ var DismissRecommendedActionResponse = external_exports.object({ id: external_ex
23956
24100
  var RecommendedActionIdParam = external_exports.object({ id: external_exports.string() });
23957
24101
 
23958
24102
  // ../../packages/schema/src/zod/settings-action.ts
24103
+ var HistorySyncConsentChoice = external_exports.enum(["granted", "revoked", "unchanged"]).meta({ id: "HistorySyncConsentChoice" });
24104
+ var ModelJudgeConsentChoice = external_exports.enum(["granted", "revoked", "unchanged"]).meta({ id: "ModelJudgeConsentChoice" });
23959
24105
  var SaveSettingsInput = external_exports.object({
23960
24106
  historicalAccess: external_exports.string(),
23961
- modelJudgeConsent: external_exports.boolean(),
23962
- historySyncConsent: external_exports.boolean(),
24107
+ modelJudgeConsent: ModelJudgeConsentChoice,
24108
+ historySyncConsent: HistorySyncConsentChoice,
23963
24109
  vaultConsent: external_exports.string(),
23964
24110
  vaultInlineReveal: external_exports.string()
23965
24111
  });
@@ -24109,9 +24255,9 @@ function deriveReviewReasons(trust, transports) {
24109
24255
  if (transports.includes("http") || transports.includes("ws")) reasons.push("plaintext_transport");
24110
24256
  return reasons;
24111
24257
  }
24112
- function buildReviewInfo(trust, transports) {
24258
+ function buildReviewInfo(trust, transports, decided) {
24113
24259
  const reasons = deriveReviewReasons(trust, transports);
24114
- return { needsReview: reasons.length > 0, reasons };
24260
+ return { needsReview: reasons.length > 0 && !decided, reasons };
24115
24261
  }
24116
24262
  function distinctTransports(transports) {
24117
24263
  return Array.from(new Set(transports));
@@ -24329,8 +24475,8 @@ function readControlPlaneCredential(settingsDir2, connection) {
24329
24475
  }
24330
24476
 
24331
24477
  // ../../packages/persistence/src/database.ts
24332
- import { randomUUID as randomUUID10 } from "crypto";
24333
- import { join as join4, sep } from "path";
24478
+ import { randomUUID as randomUUID11 } from "crypto";
24479
+ import { dirname as dirname2, join as join7, sep } from "path";
24334
24480
  import { DatabaseSync } from "node:sqlite";
24335
24481
 
24336
24482
  // ../../packages/persistence/src/ids.ts
@@ -24595,6 +24741,10 @@ function allRows(stmt, params) {
24595
24741
  if (Array.isArray(params)) return stmt.all(...params);
24596
24742
  return stmt.all(params);
24597
24743
  }
24744
+ function* iterateRows(stmt, params) {
24745
+ const rows = params === void 0 ? stmt.iterate() : Array.isArray(params) ? stmt.iterate(...params) : stmt.iterate(params);
24746
+ for (const row of rows) yield row;
24747
+ }
24598
24748
  function getRow(stmt, params) {
24599
24749
  if (params === void 0) return stmt.get();
24600
24750
  if (Array.isArray(params)) return stmt.get(...params);
@@ -25063,10 +25213,17 @@ function ensureSyncedAtColumn(db, table) {
25063
25213
  if (!columns.includes("sync_claimed_at")) {
25064
25214
  db.exec(`ALTER TABLE ${table} ADD COLUMN sync_claimed_at integer`);
25065
25215
  }
25216
+ if (!columns.includes("outbox_owed")) {
25217
+ db.exec(`ALTER TABLE ${table} ADD COLUMN outbox_owed integer`);
25218
+ }
25066
25219
  db.exec(
25067
25220
  `CREATE INDEX IF NOT EXISTS idx_audit_events_sync
25068
25221
  ON audit_events (event_type, synced_at, sync_claimed_at, started_at)`
25069
25222
  );
25223
+ db.exec(
25224
+ `CREATE INDEX IF NOT EXISTS idx_audit_outbox_owed
25225
+ ON audit_events (event_type, synced_at, sync_claimed_at, started_at) WHERE outbox_owed = 1`
25226
+ );
25070
25227
  db.exec(
25071
25228
  `CREATE INDEX IF NOT EXISTS idx_audit_claimed
25072
25229
  ON audit_events (sync_claimed_at) WHERE sync_claimed_at IS NOT NULL`
@@ -25171,7 +25328,6 @@ function decodeKeysetCursor(cursor) {
25171
25328
  // ../../packages/persistence/src/repositories/activity.ts
25172
25329
  var DAY_MS = 864e5;
25173
25330
  var LIVE_ACTIVITY_WINDOW_MS = 30 * 6e4;
25174
- var LAST_ACTIVITY_EXPR = `max(started_at, coalesce(ended_at, started_at))`;
25175
25331
  function defaultTimeZone() {
25176
25332
  try {
25177
25333
  return Intl.DateTimeFormat().resolvedOptions().timeZone;
@@ -25226,6 +25382,7 @@ var DB_EVENT_TYPE_TO_KIND = {
25226
25382
  error: "error",
25227
25383
  active: "active"
25228
25384
  };
25385
+ var TIMELINE_EVENT_TYPES = Object.keys(DB_EVENT_TYPE_TO_KIND).map((kind) => `'${kind}'`).join(", ");
25229
25386
  function safeParseStringArray(raw) {
25230
25387
  if (!raw) return [];
25231
25388
  const parsed2 = safeJson(raw, null);
@@ -25299,6 +25456,37 @@ var TIMELINE_COLUMNS = `
25299
25456
  json_extract(attributes, '$.targetId') AS target_id,
25300
25457
  json_extract(attributes, '$.internal') AS internal,
25301
25458
  json_extract(attributes, '$.flagged') AS flagged`;
25459
+ var LLM_USAGE_SELECT = `
25460
+ SELECT root_session_id AS sessionId,
25461
+ provider,
25462
+ model,
25463
+ service_tier AS serviceTier,
25464
+ coalesce(sum(input_tokens), 0) AS inputTokens,
25465
+ coalesce(sum(output_tokens), 0) AS outputTokens,
25466
+ coalesce(sum(cache_creation_input_tokens), 0) AS cacheCreationTokens,
25467
+ coalesce(sum(cache_read_input_tokens), 0) AS cacheReadTokens,
25468
+ coalesce(sum(ephemeral_1h_input_tokens), 0) AS ephemeral1hTokens,
25469
+ coalesce(sum(ephemeral_5m_input_tokens), 0) AS ephemeral5mTokens,
25470
+ coalesce(sum(web_search_requests), 0) AS webSearchRequests`;
25471
+ var LLM_USAGE_SCOPE = `event_type = 'llm_call' AND attributes IS NOT NULL AND root_session_id IS NOT NULL`;
25472
+ var LLM_USAGE_GROUP = `GROUP BY root_session_id, provider, model, service_tier`;
25473
+ function usageLeaves(rows) {
25474
+ return rows.map((row) => {
25475
+ const attributes = {
25476
+ input_tokens: row.inputTokens,
25477
+ output_tokens: row.outputTokens,
25478
+ cache_creation_input_tokens: row.cacheCreationTokens,
25479
+ cache_read_input_tokens: row.cacheReadTokens,
25480
+ ephemeral_1h_input_tokens: row.ephemeral1hTokens,
25481
+ ephemeral_5m_input_tokens: row.ephemeral5mTokens,
25482
+ web_search_requests: row.webSearchRequests
25483
+ };
25484
+ if (row.provider !== null) attributes.provider = row.provider;
25485
+ if (row.model !== null) attributes.model = row.model;
25486
+ if (row.serviceTier !== null) attributes.service_tier = row.serviceTier;
25487
+ return { sessionId: row.sessionId, attributes };
25488
+ });
25489
+ }
25302
25490
  var SESSION_ROOT = `event_type = 'session'`;
25303
25491
  var HAS_ACTIVITY = `EXISTS (
25304
25492
  SELECT 1 FROM audit_events c
@@ -25324,16 +25512,17 @@ var SqliteActivityRepository = class {
25324
25512
  const liveThreshold = this.now() - LIVE_ACTIVITY_WINDOW_MS;
25325
25513
  const liveNow = countScalar(
25326
25514
  this.db,
25327
- `SELECT count(*) AS n FROM audit_events s
25515
+ `SELECT count(*) AS n FROM audit_events s INDEXED BY sqlite_autoindex_audit_events_1
25328
25516
  WHERE s.event_type = 'session' AND s.ended_at IS NULL
25329
- AND max(
25330
- s.started_at,
25331
- coalesce(
25332
- (SELECT max(${LAST_ACTIVITY_EXPR}) FROM audit_events e WHERE e.root_session_id = s.id),
25333
- s.started_at
25334
- )
25335
- ) >= ?`,
25336
- [liveThreshold]
25517
+ AND s.id IN (
25518
+ SELECT id FROM audit_events WHERE event_type = 'session' AND started_at >= ?
25519
+ UNION
25520
+ SELECT root_session_id FROM audit_events INDEXED BY idx_audit_started_at
25521
+ WHERE started_at >= ?
25522
+ UNION
25523
+ SELECT root_session_id FROM audit_events INDEXED BY idx_audit_ended_at
25524
+ WHERE ended_at >= ?)`,
25525
+ [liveThreshold, liveThreshold, liveThreshold]
25337
25526
  );
25338
25527
  const toolCallsToday = countScalar(
25339
25528
  this.db,
@@ -25463,7 +25652,7 @@ var SqliteActivityRepository = class {
25463
25652
  this.db.prepare(
25464
25653
  `SELECT ${TIMELINE_COLUMNS}
25465
25654
  FROM audit_events
25466
- WHERE id = ? OR root_session_id = ?
25655
+ WHERE (id = ? OR root_session_id = ?) AND event_type IN (${TIMELINE_EVENT_TYPES})
25467
25656
  ORDER BY started_at ASC, id ASC`
25468
25657
  ),
25469
25658
  [sessionId, sessionId]
@@ -25476,14 +25665,14 @@ var SqliteActivityRepository = class {
25476
25665
  coalesce(sum(output_tokens), 0) AS output,
25477
25666
  coalesce(sum(cache_creation_input_tokens), 0) AS cache_creation,
25478
25667
  coalesce(sum(cache_read_input_tokens), 0) AS cache_read
25479
- FROM audit_events
25668
+ FROM audit_events INDEXED BY idx_audit_session_type
25480
25669
  WHERE root_session_id = ? AND event_type = 'llm_call'`
25481
25670
  ),
25482
25671
  [sessionId]
25483
25672
  ) ?? { input: 0, output: 0, cache_creation: 0, cache_read: 0 };
25484
25673
  const primaryModel = getRow(
25485
25674
  this.db.prepare(
25486
- `SELECT model, provider FROM audit_events
25675
+ `SELECT model, provider FROM audit_events INDEXED BY idx_audit_session_type
25487
25676
  WHERE root_session_id = ? AND event_type = 'llm_call'
25488
25677
  ORDER BY started_at ASC, id ASC
25489
25678
  LIMIT 1`
@@ -25494,7 +25683,7 @@ var SqliteActivityRepository = class {
25494
25683
  this.db.prepare(
25495
25684
  `SELECT coalesce(json_extract(attributes, '$.tool_name'), json_extract(attributes, '$.tool')) AS tool,
25496
25685
  count(*) AS n
25497
- FROM audit_events
25686
+ FROM audit_events INDEXED BY idx_audit_session
25498
25687
  WHERE root_session_id = ? AND event_type = 'tool_call'
25499
25688
  GROUP BY coalesce(json_extract(attributes, '$.tool_name'), json_extract(attributes, '$.tool'))`
25500
25689
  ),
@@ -25502,7 +25691,7 @@ var SqliteActivityRepository = class {
25502
25691
  );
25503
25692
  const modelRows = allRows(
25504
25693
  this.db.prepare(
25505
- `SELECT DISTINCT model FROM audit_events
25694
+ `SELECT DISTINCT model FROM audit_events INDEXED BY idx_audit_session_type
25506
25695
  WHERE root_session_id = ? AND event_type = 'llm_call' AND model IS NOT NULL AND model <> ''
25507
25696
  ORDER BY model`
25508
25697
  ),
@@ -25511,7 +25700,7 @@ var SqliteActivityRepository = class {
25511
25700
  const derivedModels = modelRows.map((r) => r.model);
25512
25701
  const commits = countScalar(
25513
25702
  this.db,
25514
- `SELECT count(*) AS n FROM audit_events
25703
+ `SELECT count(*) AS n FROM audit_events INDEXED BY idx_audit_session
25515
25704
  WHERE root_session_id = ? AND event_type = 'commit'`,
25516
25705
  [sessionId]
25517
25706
  );
@@ -25547,25 +25736,57 @@ var SqliteActivityRepository = class {
25547
25736
  return Promise.resolve(session);
25548
25737
  }
25549
25738
  /**
25550
- * Cross-session token report — every `llm_call` leaf (optionally windowed to
25551
- * `started_at >= fromMs`) grouped into per-session `SessionTokenReport`s, with
25552
- * USD cost DERIVED at read time via the shared `defaultCostModel` (never
25553
- * stored). `fromMs` lets the Activity page scope the usage panel to its
25554
- * selected time range; omit it for all-time (the CLI/TUI overview). The
25555
- * caller collapses these onto per-model rows with `aggregateTokenUsage`.
25739
+ * Cross-session token report — every `llm_call` in the store (or in a
25740
+ * `started_at >= fromMs` window, the Activity page's range) grouped per
25741
+ * session, with USD cost DERIVED at read time via the shared
25742
+ * `defaultCostModel` (never stored). The caller collapses these onto
25743
+ * per-model rows with `aggregateTokenUsage`.
25744
+ *
25745
+ * Grouped in SQL over `idx_audit_llm_usage` — one entry per call carrying
25746
+ * the members the rollup sums — and priced once per group, which is exact
25747
+ * (see LlmUsageRow). Reading the bags and folding them in JS measured 31 ms
25748
+ * for a seven-day window at 50k calls, and naming the VIRTUAL columns
25749
+ * against the table 40 ms, since each is a json_extract recomputed per row;
25750
+ * the index stores the values once, at write, and answers the same window in
25751
+ * 8.5 ms. `INDEXED BY` is deliberate: with or without ANALYZE statistics the
25752
+ * planner prefers the general event-type index and fetches every row to
25753
+ * recompute the columns it could have read. The index is one every open
25754
+ * store carries, since opening runs the migrations, so the hard requirement
25755
+ * `INDEXED BY` introduces is already met; token-rollup-plans.test.ts pins
25756
+ * the plan. All-time is a scan of the whole index — still one narrow entry
25757
+ * per call, no bag parsed.
25556
25758
  */
25557
25759
  tokenReports(fromMs) {
25558
- const leaves = this.readLlmCallLeaves(fromMs === void 0 ? {} : { fromMs });
25559
- return Promise.resolve(buildTokenReports(leaves, defaultCostModel));
25760
+ const rows = allRows(
25761
+ this.db.prepare(
25762
+ `${LLM_USAGE_SELECT}
25763
+ FROM audit_events INDEXED BY idx_audit_llm_usage
25764
+ WHERE ${LLM_USAGE_SCOPE}${fromMs === void 0 ? "" : " AND started_at >= ?"}
25765
+ ${LLM_USAGE_GROUP}`
25766
+ ),
25767
+ fromMs === void 0 ? void 0 : [fromMs]
25768
+ );
25769
+ return Promise.resolve(buildTokenReports(usageLeaves(rows), defaultCostModel));
25560
25770
  }
25561
25771
  /**
25562
- * One session's token report — its `llm_call` leaves grouped per (provider,
25563
- * model) with derived cost, or `null` when the session made no `llm_call`s
25564
- * (an empty/tool-only session). Feeds the session-detail pane's per-model
25565
- * breakdown + estimated cost.
25772
+ * One session's token report — its `llm_call`s grouped per (provider,
25773
+ * model, tier) with derived cost, or `null` when the session made no
25774
+ * `llm_call`s (an empty/tool-only session). Feeds the session-detail pane's
25775
+ * per-model breakdown + estimated cost. The same rollup as `tokenReports`,
25776
+ * seeking one root through a root-led `llm_call` index; the bag-reading fold
25777
+ * it replaces walked every `llm_call` in the store to find one session's.
25566
25778
  */
25567
25779
  tokenReportForSession(sessionId) {
25568
- const reports = buildTokenReports(this.readLlmCallLeaves({ sessionId }), defaultCostModel);
25780
+ const rows = allRows(
25781
+ this.db.prepare(
25782
+ `${LLM_USAGE_SELECT}
25783
+ FROM audit_events
25784
+ WHERE ${LLM_USAGE_SCOPE} AND root_session_id = ?
25785
+ ${LLM_USAGE_GROUP}`
25786
+ ),
25787
+ [sessionId]
25788
+ );
25789
+ const reports = buildTokenReports(usageLeaves(rows), defaultCostModel);
25569
25790
  return Promise.resolve(reports[0] ?? null);
25570
25791
  }
25571
25792
  /**
@@ -25589,42 +25810,6 @@ var SqliteActivityRepository = class {
25589
25810
  for (const row of rows) seen.add(toHarness(row.harness));
25590
25811
  return Promise.resolve([...seen]);
25591
25812
  }
25592
- /**
25593
- * The raw `llm_call` leaves (session id + parsed attribute bag) for the token
25594
- * rollups, optionally narrowed to one session and/or a `started_at >= fromMs`
25595
- * window. A leaf whose attributes blob is NULL or unparseable is skipped
25596
- * (best-effort read — a corrupt bag never breaks the report). `root_session_id`
25597
- * is the leaf's session (the reconciler sets parent_id = root_session_id).
25598
- */
25599
- readLlmCallLeaves(opts = {}) {
25600
- const conditions = ["event_type = 'llm_call'", "attributes IS NOT NULL"];
25601
- const params = [];
25602
- if (opts.sessionId !== void 0) {
25603
- conditions.push("root_session_id = ?");
25604
- params.push(opts.sessionId);
25605
- }
25606
- if (opts.fromMs !== void 0) {
25607
- conditions.push("started_at >= ?");
25608
- params.push(opts.fromMs);
25609
- }
25610
- const rows = allRows(
25611
- this.db.prepare(
25612
- `SELECT root_session_id AS sessionId, attributes
25613
- FROM audit_events
25614
- WHERE ${conditions.join(" AND ")}`
25615
- ),
25616
- params
25617
- );
25618
- return mapRowsTolerant(
25619
- rows.filter(
25620
- (row) => row.sessionId !== null
25621
- ),
25622
- (row) => ({
25623
- sessionId: row.sessionId,
25624
- attributes: JSON.parse(row.attributes)
25625
- })
25626
- );
25627
- }
25628
25813
  /**
25629
25814
  * Per-session turns/findings/shares + last-activity for a page of session ids,
25630
25815
  * in grouped queries (not one per row). An id with no matching rows still
@@ -25639,20 +25824,23 @@ var SqliteActivityRepository = class {
25639
25824
  const inClause = placeholders(sessionIds.length);
25640
25825
  const lastActivityRows = allRows(
25641
25826
  this.db.prepare(
25642
- `SELECT root_session_id AS id, max(${LAST_ACTIVITY_EXPR}) AS m FROM audit_events
25643
- WHERE root_session_id IN (${inClause})
25644
- GROUP BY root_session_id`
25827
+ `SELECT ids.value AS id,
25828
+ (SELECT max(started_at) FROM audit_events e WHERE e.root_session_id = ids.value) AS ms,
25829
+ (SELECT max(ended_at) FROM audit_events e
25830
+ WHERE e.root_session_id = ids.value AND e.ended_at IS NOT NULL) AS me
25831
+ FROM json_each(?) AS ids`
25645
25832
  ),
25646
- sessionIds
25833
+ [JSON.stringify(sessionIds)]
25647
25834
  );
25648
25835
  for (const row of lastActivityRows) {
25649
- if (row.id === null) continue;
25650
25836
  const entry = result.get(row.id);
25651
- if (entry && row.m !== null) entry.lastActivityMs = row.m;
25837
+ const last = Math.max(row.ms ?? 0, row.me ?? 0);
25838
+ if (entry && last > 0) entry.lastActivityMs = last;
25652
25839
  }
25653
25840
  const turnsRows = allRows(
25654
25841
  this.db.prepare(
25655
- `SELECT root_session_id AS id, count(*) AS n FROM audit_events
25842
+ `SELECT root_session_id AS id, count(*) AS n
25843
+ FROM audit_events INDEXED BY idx_audit_session_prompt
25656
25844
  WHERE root_session_id IN (${inClause}) AND event_type = 'prompt'
25657
25845
  GROUP BY root_session_id`
25658
25846
  ),
@@ -25667,7 +25855,7 @@ var SqliteActivityRepository = class {
25667
25855
  this.db.prepare(
25668
25856
  `SELECT root_session_id AS id,
25669
25857
  count(DISTINCT json_extract(attributes, '$.run_key')) AS n
25670
- FROM audit_events
25858
+ FROM audit_events INDEXED BY idx_audit_session_run_key
25671
25859
  WHERE root_session_id IN (${inClause}) AND event_type = 'llm_call'
25672
25860
  AND json_extract(attributes, '$.run_key') IS NOT NULL
25673
25861
  GROUP BY root_session_id`
@@ -25697,7 +25885,7 @@ var SqliteActivityRepository = class {
25697
25885
  this.db.prepare(
25698
25886
  `SELECT root_session_id AS id,
25699
25887
  count(DISTINCT json_extract(attributes, '$.destination')) AS n
25700
- FROM audit_events
25888
+ FROM audit_events INDEXED BY idx_audit_session_share
25701
25889
  WHERE root_session_id IN (${inClause}) AND event_type = 'share'
25702
25890
  GROUP BY root_session_id`
25703
25891
  ),
@@ -26726,7 +26914,6 @@ var LATEST_RESOLUTION_BY_KEY_SQL = `(
26726
26914
 
26727
26915
  // ../../packages/persistence/src/repositories/findings.ts
26728
26916
  var PREVIEW_INSTANCES_PER_GROUP = 200;
26729
- var SCAN_BATCH_ROWS = 1e3;
26730
26917
  var DEFAULT_LOCATIONS_LIMIT = 100;
26731
26918
  var LOCATION_RULE_IDS_CAP = 20;
26732
26919
  function compareLocationOrder(a, b) {
@@ -26755,6 +26942,25 @@ function deriveInstanceStatus(row) {
26755
26942
  latestResolutionStatus: row.latest_status
26756
26943
  });
26757
26944
  }
26945
+ function toFlatFindingRow(r) {
26946
+ return {
26947
+ id: r.id,
26948
+ ruleId: r.rule_id,
26949
+ category: r.category,
26950
+ severity: r.severity,
26951
+ maskedMatch: r.masked_match,
26952
+ actionTaken: r.action_taken,
26953
+ confidence: r.confidence,
26954
+ occurredAt: epochMillisToIso(r.occurred_at),
26955
+ sourceTool: r.source_tool,
26956
+ repo: r.repo ?? "",
26957
+ file: r.file ?? "",
26958
+ ...r.tool_name === null ? {} : { toolName: r.tool_name },
26959
+ eventId: r.event_id,
26960
+ ...r.session_id === null ? {} : { sessionId: r.session_id },
26961
+ status: deriveInstanceStatus(r)
26962
+ };
26963
+ }
26758
26964
  function encodeGroupCursor(group) {
26759
26965
  const payload = {
26760
26966
  sev: group.severity,
@@ -26830,7 +27036,7 @@ var SqliteFindingsRepository = class {
26830
27036
  this.db.prepare(
26831
27037
  `SELECT f.id, f.audit_event_id AS event_id, d.rule_id, d.category, d.severity,
26832
27038
  f.masked_match, f.action_taken, f.confidence, e.started_at AS occurred_at,
26833
- json_extract(e.attributes, '$.source_tool') AS source_tool,
27039
+ e.source_tool AS source_tool,
26834
27040
  e.event_type AS kind
26835
27041
  FROM audit_events e
26836
27042
  CROSS JOIN inspection_findings f ON f.audit_event_id = e.id
@@ -26938,56 +27144,11 @@ var SqliteFindingsRepository = class {
26938
27144
  predicate,
26939
27145
  params: sessionParams
26940
27146
  });
26941
- const rows = allRows(
26942
- this.db.prepare(
26943
- `SELECT id, rule_id, category, severity, masked_match, action_taken, confidence,
26944
- occurred_at, source_tool, repo, file, tool_name, event_id, session_id,
26945
- kind, finding_key, latest_status
26946
- FROM (
26947
- SELECT f.id AS id, d.rule_id AS rule_id, d.category AS category,
26948
- d.severity AS severity, f.masked_match AS masked_match,
26949
- f.action_taken AS action_taken, f.confidence AS confidence,
26950
- e.started_at AS occurred_at,
26951
- json_extract(e.attributes, '$.source_tool') AS source_tool,
26952
- json_extract(e.attributes, '$.repo') AS repo,
26953
- json_extract(e.attributes, '$.file_path') AS file,
26954
- json_extract(e.attributes, '$.tool_name') AS tool_name,
26955
- f.audit_event_id AS event_id, e.root_session_id AS session_id,
26956
- e.event_type AS kind, f.finding_key AS finding_key,
26957
- latest.status AS latest_status,
26958
- ROW_NUMBER() OVER (
26959
- PARTITION BY d.rule_id
26960
- ORDER BY e.started_at DESC, f.id DESC
26961
- ) AS rn
26962
- FROM inspection_findings f
26963
- JOIN audit_events e ON e.id = f.audit_event_id
26964
- JOIN inspection_definitions d ON d.id = f.inspection_definition_id
26965
- LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
26966
- ON latest.finding_key = f.finding_key
26967
- ${predicate}
26968
- )
26969
- WHERE rn <= :cap
26970
- ORDER BY occurred_at DESC, id DESC`
26971
- ),
26972
- { cap: PREVIEW_INSTANCES_PER_GROUP, ...sessionParams }
26973
- );
26974
- const groupable = rows.map((r) => ({
26975
- id: r.id,
26976
- ruleId: r.rule_id,
26977
- category: r.category,
26978
- severity: r.severity,
26979
- maskedMatch: r.masked_match,
26980
- actionTaken: r.action_taken,
26981
- confidence: r.confidence,
26982
- occurredAt: epochMillisToIso(r.occurred_at),
26983
- sourceTool: r.source_tool,
26984
- repo: r.repo ?? "",
26985
- file: r.file ?? "",
26986
- ...r.tool_name === null ? {} : { toolName: r.tool_name },
26987
- eventId: r.event_id,
26988
- ...r.session_id === null ? {} : { sessionId: r.session_id },
26989
- status: deriveInstanceStatus(r)
26990
- }));
27147
+ const rows = this.previewRows(aggregates, {
27148
+ sessionId: query.sessionId,
27149
+ from: query.from
27150
+ });
27151
+ const groupable = rows.map(toFlatFindingRow);
26991
27152
  const allGroups = buildFindingGroups(groupable, { aggregates });
26992
27153
  const filterOpts = {
26993
27154
  severity: query.severity,
@@ -27073,8 +27234,10 @@ var SqliteFindingsRepository = class {
27073
27234
  *
27074
27235
  * The scan runs from the top of the scope on every request, not from the
27075
27236
  * cursor: `totals` and `facets` describe the whole filtered scope and must not
27076
- * move as the caller pages. Rows are pulled in batches so memory stays flat
27077
- * while the counting runs, and only the page itself is retained.
27237
+ * move as the caller pages. Rows come off ONE statement, iterated rather
27238
+ * than materialized (`scanFindingRows`), so memory stays flat while the
27239
+ * counting runs — a generator streaming the index order, not a sequence of
27240
+ * fetched batches; only the page itself is retained.
27078
27241
  */
27079
27242
  listFindingInstances(query) {
27080
27243
  const opts = {
@@ -27090,6 +27253,10 @@ var SqliteFindingsRepository = class {
27090
27253
  };
27091
27254
  const limit = query.limit ?? DEFAULT_FLAT_FINDINGS_LIMIT;
27092
27255
  const cursor = query.cursor === void 0 ? null : decodeKeysetCursor(query.cursor);
27256
+ const isPastCursor = cursor === null ? () => true : (row) => {
27257
+ const rowMs = isoToEpochMillis(row.occurredAt);
27258
+ return rowMs <= cursor.startedAtMs && (rowMs < cursor.startedAtMs || row.id < cursor.id);
27259
+ };
27093
27260
  const accumulator = createInstanceFacetAccumulator(opts);
27094
27261
  const items = [];
27095
27262
  let total = 0;
@@ -27102,6 +27269,7 @@ var SqliteFindingsRepository = class {
27102
27269
  accumulator.add(row);
27103
27270
  if (!matchesInstanceFilters(row, opts)) continue;
27104
27271
  total += 1;
27272
+ if (!isPastCursor(row)) continue;
27105
27273
  if (items.length < limit) {
27106
27274
  items.push(toInstanceDetail(row));
27107
27275
  last = row;
@@ -27110,15 +27278,6 @@ var SqliteFindingsRepository = class {
27110
27278
  }
27111
27279
  }
27112
27280
  const nextCursor = hasMore && last ? encodeKeysetCursor({ startedAtMs: isoToEpochMillis(last.occurredAt), id: last.id }) : null;
27113
- if (cursor !== null) {
27114
- const resumed = this.pageAfter(cursor, opts, limit, query);
27115
- return Promise.resolve({
27116
- totals: { findings: total },
27117
- facets: accumulator.facets(),
27118
- items: resumed.items,
27119
- nextCursor: resumed.nextCursor
27120
- });
27121
- }
27122
27281
  return Promise.resolve({
27123
27282
  totals: { findings: total },
27124
27283
  facets: accumulator.facets(),
@@ -27126,35 +27285,6 @@ var SqliteFindingsRepository = class {
27126
27285
  nextCursor
27127
27286
  });
27128
27287
  }
27129
- /**
27130
- * The page of matching rows strictly after `cursor`. Separate from the
27131
- * counting pass because that one starts at the top of the scope by design;
27132
- * this one narrows the scan with the same keyset predicate the activity list
27133
- * uses, so a later page costs less than the first rather than more.
27134
- */
27135
- pageAfter(cursor, opts, limit, query) {
27136
- const items = [];
27137
- let last;
27138
- let hasMore = false;
27139
- for (const row of this.scanFindingRows({
27140
- sessionId: query.sessionId,
27141
- from: query.from,
27142
- after: cursor
27143
- })) {
27144
- if (!matchesInstanceFilters(row, opts)) continue;
27145
- if (items.length < limit) {
27146
- items.push(toInstanceDetail(row));
27147
- last = row;
27148
- } else {
27149
- hasMore = true;
27150
- break;
27151
- }
27152
- }
27153
- return {
27154
- items,
27155
- nextCursor: hasMore && last ? encodeKeysetCursor({ startedAtMs: isoToEpochMillis(last.occurredAt), id: last.id }) : null
27156
- };
27157
- }
27158
27288
  /**
27159
27289
  * The same findings folded by location: repository, then file within it.
27160
27290
  *
@@ -27237,25 +27367,111 @@ var SqliteFindingsRepository = class {
27237
27367
  });
27238
27368
  }
27239
27369
  /**
27240
- * Every finding in scope as a FlatFindingRow, newest first, pulled in batches.
27370
+ * Each group's newest instances, for the table's expanded rows.
27371
+ *
27372
+ * ONE index-ordered scan with early termination, and the shape is the point.
27373
+ * The natural spelling — `ROW_NUMBER() OVER (PARTITION BY rule_id ORDER BY
27374
+ * started_at DESC)` then `WHERE rn <= cap` — sorts EVERY finding in scope
27375
+ * through a temp B-tree to keep a bounded preview of each group, and then
27376
+ * sorts the survivors again for the page order. Both sorts grow with the
27377
+ * store while the answer does not.
27378
+ *
27379
+ * Instead the scan walks `audit_events` newest-first off `idx_audit_started_at`
27380
+ * (or the session or window index the scope names — see `findingScanSql`),
27381
+ * which is already the order the page wants, and keeps rows per rule until
27382
+ * each rule has as many as it can show. The aggregate the caller already holds
27383
+ * says how many that is: `min(instanceCount, PREVIEW_INSTANCES_PER_GROUP)`
27384
+ * per rule, summed, is the number of rows this scan has to find, and it stops
27385
+ * on the last one. That sum is bounded by `rules * PREVIEW_INSTANCES_PER_GROUP`
27386
+ * (8,000 at this repo's 40-rule bench corpus), not by a fixed row count — a
27387
+ * store with many firing rules widens it. The bound that DOES hold
27388
+ * unconditionally is the sorted form's floor: this scan visits at most as
27389
+ * many rows as `ROW_NUMBER() OVER (PARTITION BY rule_id …)` would have
27390
+ * sorted, and stops the moment every rule has its cap, where the sorted form
27391
+ * sorts the whole scope regardless. The true worst case — the rarest rule's
27392
+ * wanted instances sitting at the tail of the scope — is one pass over
27393
+ * everything in scope with a block sort of the id tie-break only, never a
27394
+ * sort of the scope, which is still that floor.
27395
+ *
27396
+ * A row whose rule the aggregate did not see is skipped: the two statements
27397
+ * run without a shared snapshot, so a capture landing between them can add a
27398
+ * rule here that has no counts there, and the counts are what the group is
27399
+ * built from.
27400
+ */
27401
+ previewRows(aggregates, scope) {
27402
+ const wanted = /* @__PURE__ */ new Map();
27403
+ let remaining = 0;
27404
+ for (const [ruleId, agg] of aggregates) {
27405
+ const n = Math.min(agg.instanceCount, PREVIEW_INSTANCES_PER_GROUP);
27406
+ wanted.set(ruleId, n);
27407
+ remaining += n;
27408
+ }
27409
+ const rows = [];
27410
+ if (remaining === 0) return rows;
27411
+ const { sql, params } = this.findingScanSql(scope);
27412
+ const taken = /* @__PURE__ */ new Map();
27413
+ for (const r of iterateRows(this.db.prepare(sql), params)) {
27414
+ const want = wanted.get(r.rule_id);
27415
+ if (want === void 0) continue;
27416
+ const have = taken.get(r.rule_id) ?? 0;
27417
+ if (have >= want) continue;
27418
+ taken.set(r.rule_id, have + 1);
27419
+ rows.push(r);
27420
+ remaining -= 1;
27421
+ if (remaining === 0) break;
27422
+ }
27423
+ return rows;
27424
+ }
27425
+ /**
27426
+ * Every finding in scope as a FlatFindingRow, newest first, streamed.
27241
27427
  *
27242
27428
  * A generator so a caller streams the scope without it ever being an array:
27243
27429
  * the flat list counts and facets the whole filtered scope, which on a large
27244
- * store is far more rows than any page. Each batch advances the same keyset
27245
- * predicate the page read uses, so the scan is a sequence of bounded reads
27246
- * rather than one unbounded result set.
27247
- *
27248
- * The latest-resolution lookup is the CORRELATED form, not the derived table
27249
- * the grouped path joins: only `status` is needed, idx_finding_resolution_key
27250
- * makes it a point lookup per row, and the derived table would re-materialize
27251
- * a window over the whole resolution table once per batch.
27430
+ * store is far more rows than any page. The rows come off ONE statement,
27431
+ * iterated rather than materialized, in the index order `findingScanSql`
27432
+ * arranges — so the scan is a single pass with a block sort of the id
27433
+ * tie-break only, never a sort of the scope, where a sequence of
27434
+ * keyset-bounded batches re-sorted everything below the cursor on every
27435
+ * batch and cost the square of the scope.
27252
27436
  *
27253
- * `scope` carries ONLY what no facet counts. A filter dimension narrowed here
27254
- * would be missing from its own facet, which is computed by excluding that
27255
- * dimension — see listFindingInstances.
27437
+ * `sessionId` and `from` carry ONLY what no facet counts — a filter
27438
+ * dimension narrowed here would be missing from its own facet, which is
27439
+ * computed by excluding that dimension (see listFindingInstances). There is
27440
+ * no `after`/cursor parameter: a keyset page is collected inline from this
27441
+ * same pass (`listFindingInstances`' `isPastCursor`) rather than by a second,
27442
+ * narrower statement, since the counting pass already visits every row a
27443
+ * page-2+ request would otherwise re-seek for.
27256
27444
  */
27257
27445
  *scanFindingRows(scope) {
27258
- const conditions = [`e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})`];
27446
+ const { sql, params } = this.findingScanSql(scope);
27447
+ for (const r of iterateRows(this.db.prepare(sql), params)) {
27448
+ yield toFlatFindingRow(r);
27449
+ }
27450
+ }
27451
+ /**
27452
+ * The one statement both instance-level scans run: every finding in scope,
27453
+ * joined to its event and definition, newest first.
27454
+ *
27455
+ * THE PLAN IS THE POINT, and two things in the SQL exist only to pin it —
27456
+ * the same two `recentFindings` documents at length, for the same reason:
27457
+ *
27458
+ * - **`+e.event_type`** makes the capture-kind predicate non-indexable, so
27459
+ * the planner cannot pick `idx_audit_type_t` and then sort. That index
27460
+ * yields `started_at` order per event type, not across the four, so
27461
+ * satisfying the ORDER BY from it would need a merge SQLite does not do.
27462
+ * Freed of it, the planner walks `idx_audit_started_at` backwards — or
27463
+ * `idx_audit_session` for a session scope, which is also `started_at`
27464
+ * ordered within the session — and the order falls out of the index.
27465
+ * - **`CROSS JOIN`** pins `audit_events` as the driving table. With plain
27466
+ * JOINs the planner drives from the findings and sorts everything.
27467
+ *
27468
+ * The latest-resolution lookup is the CORRELATED form: only `status` is
27469
+ * needed, `idx_finding_resolution_key_created` answers it with one backward
27470
+ * index probe per keyed row, and a derived table over the whole resolution
27471
+ * table would be materialized before the first row streamed.
27472
+ */
27473
+ findingScanSql(scope) {
27474
+ const conditions = [`+e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})`];
27259
27475
  const params = [];
27260
27476
  if (scope.sessionId !== void 0 && scope.sessionId !== "") {
27261
27477
  conditions.push("e.root_session_id = ?");
@@ -27269,58 +27485,24 @@ var SqliteFindingsRepository = class {
27269
27485
  d.severity AS severity, f.masked_match AS masked_match,
27270
27486
  f.action_taken AS action_taken, f.confidence AS confidence,
27271
27487
  e.started_at AS occurred_at,
27272
- json_extract(e.attributes, '$.source_tool') AS source_tool,
27273
- json_extract(e.attributes, '$.repo') AS repo,
27274
- json_extract(e.attributes, '$.file_path') AS file,
27275
- json_extract(e.attributes, '$.tool_name') AS tool_name,
27488
+ e.source_tool AS source_tool,
27489
+ e.repo AS repo,
27490
+ e.file_path AS file,
27491
+ e.tool_name AS tool_name,
27276
27492
  f.audit_event_id AS event_id, e.root_session_id AS session_id,
27277
27493
  e.event_type AS kind, f.finding_key AS finding_key,
27278
27494
  ${latestResolutionStatusSql("f")} AS latest_status
27279
- FROM inspection_findings f
27280
- JOIN audit_events e ON e.id = f.audit_event_id
27281
- JOIN inspection_definitions d ON d.id = f.inspection_definition_id
27495
+ FROM audit_events e
27496
+ CROSS JOIN inspection_findings f ON f.audit_event_id = e.id
27497
+ CROSS JOIN inspection_definitions d ON d.id = f.inspection_definition_id
27282
27498
  WHERE ${conditions.join(" AND ")}
27283
- AND (e.started_at < ? OR (e.started_at = ? AND f.id < ?))
27284
- ORDER BY e.started_at DESC, f.id DESC
27285
- LIMIT ?`;
27286
- let after = scope.after ?? { startedAtMs: Number.MAX_SAFE_INTEGER, id: "\uFFFF" };
27287
- for (; ; ) {
27288
- const rows = allRows(this.db.prepare(sql), [
27289
- ...params,
27290
- after.startedAtMs,
27291
- after.startedAtMs,
27292
- after.id,
27293
- SCAN_BATCH_ROWS
27294
- ]);
27295
- for (const r of rows) {
27296
- yield {
27297
- id: r.id,
27298
- ruleId: r.rule_id,
27299
- category: r.category,
27300
- severity: r.severity,
27301
- maskedMatch: r.masked_match,
27302
- actionTaken: r.action_taken,
27303
- confidence: r.confidence,
27304
- occurredAt: epochMillisToIso(r.occurred_at),
27305
- sourceTool: r.source_tool,
27306
- repo: r.repo ?? "",
27307
- file: r.file ?? "",
27308
- ...r.tool_name === null ? {} : { toolName: r.tool_name },
27309
- eventId: r.event_id,
27310
- ...r.session_id === null ? {} : { sessionId: r.session_id },
27311
- status: deriveInstanceStatus(r)
27312
- };
27313
- }
27314
- if (rows.length < SCAN_BATCH_ROWS) return;
27315
- const lastRow = rows[rows.length - 1];
27316
- if (lastRow === void 0) return;
27317
- after = { startedAtMs: lastRow.occurred_at, id: lastRow.id };
27318
- }
27499
+ ORDER BY e.started_at DESC, f.id DESC`;
27500
+ return { sql, params };
27319
27501
  }
27320
27502
  groupAggregates(withSearchText, scope) {
27321
- const innerSearchColumns = withSearchText ? `, group_concat(DISTINCT json_extract(e.attributes, '$.repo')) AS repos,
27322
- group_concat(DISTINCT json_extract(e.attributes, '$.file_path')) AS files,
27323
- group_concat(DISTINCT 'via ' || json_extract(e.attributes, '$.tool_name')) AS tool_names` : `, NULL AS repos, NULL AS files, NULL AS tool_names`;
27503
+ const innerSearchColumns = withSearchText ? `, group_concat(DISTINCT e.repo) AS repos,
27504
+ group_concat(DISTINCT e.file_path) AS files,
27505
+ group_concat(DISTINCT 'via ' || e.tool_name) AS tool_names` : `, NULL AS repos, NULL AS files, NULL AS tool_names`;
27324
27506
  const rows = this.db.prepare(
27325
27507
  `SELECT rule_id,
27326
27508
  sum(tuple_count) AS instance_count,
@@ -27338,7 +27520,7 @@ var SqliteFindingsRepository = class {
27338
27520
  coalesce(latest.status, '') AS status_tuple,
27339
27521
  count(*) AS tuple_count,
27340
27522
  max(e.started_at) AS latest_at,
27341
- group_concat(DISTINCT json_extract(e.attributes, '$.source_tool')) AS source_tools,
27523
+ group_concat(DISTINCT e.source_tool) AS source_tools,
27342
27524
  group_concat(DISTINCT f.action_taken) AS actions_taken
27343
27525
  ${innerSearchColumns}
27344
27526
  FROM inspection_findings f
@@ -27469,6 +27651,8 @@ function isoDay(ms) {
27469
27651
  // ../../packages/persistence/src/repositories/history-sync.ts
27470
27652
  var STRUCTURAL_EVENT_TYPES = ["session", "llm_call", "tool_call"];
27471
27653
  var TYPE_LIST = STRUCTURAL_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
27654
+ var OUTBOX_CAPTURE_EVENT_TYPES = ["prompt", "response", "tool_use"];
27655
+ var CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
27472
27656
  var SKIPPED = -1;
27473
27657
  var ROW_COLUMNS = `id,
27474
27658
  parent_id AS parentId,
@@ -27508,6 +27692,20 @@ var SqliteHistorySyncRepository = class {
27508
27692
  ORDER BY (event_type = 'session') DESC, started_at
27509
27693
  LIMIT :limit`
27510
27694
  );
27695
+ this.captureRowsStmt = db.prepare(
27696
+ `SELECT ${ROW_COLUMNS}
27697
+ FROM audit_events
27698
+ WHERE synced_at IS NULL
27699
+ AND sync_claimed_at IS NULL
27700
+ AND outbox_owed = 1
27701
+ AND event_type IN (${CAPTURE_TYPE_LIST})
27702
+ AND started_at < :before
27703
+ ORDER BY started_at
27704
+ LIMIT :limit`
27705
+ );
27706
+ this.markOwedStmt = db.prepare(
27707
+ `UPDATE audit_events SET outbox_owed = 1 WHERE id = :id AND synced_at IS NULL`
27708
+ );
27511
27709
  this.stampStmt = db.prepare(
27512
27710
  `UPDATE audit_events SET synced_at = :at, sync_claimed_at = NULL WHERE id = :id`
27513
27711
  );
@@ -27539,6 +27737,12 @@ var SqliteHistorySyncRepository = class {
27539
27737
  FROM audit_events
27540
27738
  WHERE event_type IN (${TYPE_LIST})`
27541
27739
  );
27740
+ this.captureSkipCountStmt = db.prepare(
27741
+ `SELECT COUNT(*) AS skipped
27742
+ FROM audit_events
27743
+ WHERE synced_at = ${String(SKIPPED)}
27744
+ AND event_type IN (${CAPTURE_TYPE_LIST})`
27745
+ );
27542
27746
  this.fingerprintStmt = db.prepare(
27543
27747
  `SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
27544
27748
  FROM history_sync WHERE id = 1`
@@ -27548,6 +27752,10 @@ var SqliteHistorySyncRepository = class {
27548
27752
  SET endpoint_fingerprint = :fingerprint, backlog_before = :backlogBefore
27549
27753
  WHERE id = 1`
27550
27754
  );
27755
+ this.disownCapturesStmt = db.prepare(
27756
+ `UPDATE audit_events SET outbox_owed = NULL
27757
+ WHERE outbox_owed IS NOT NULL AND event_type IN (${CAPTURE_TYPE_LIST})`
27758
+ );
27551
27759
  this.rearmStmt = db.prepare(
27552
27760
  `UPDATE audit_events SET synced_at = NULL
27553
27761
  WHERE synced_at > 0 AND event_type IN (${TYPE_LIST})`
@@ -27620,6 +27828,10 @@ var SqliteHistorySyncRepository = class {
27620
27828
  closeWindowStmt;
27621
27829
  releaseBoundaryStmt;
27622
27830
  freezeBoundaryStmt;
27831
+ captureRowsStmt;
27832
+ markOwedStmt;
27833
+ captureSkipCountStmt;
27834
+ disownCapturesStmt;
27623
27835
  partitionStmt;
27624
27836
  claimRowStmt;
27625
27837
  releaseRowStmt;
@@ -27653,6 +27865,34 @@ var SqliteHistorySyncRepository = class {
27653
27865
  pendingRows(sessionId, limit, before) {
27654
27866
  return allRows(this.rowsStmt, { sessionId, limit, before });
27655
27867
  }
27868
+ /**
27869
+ * Captures this machine still owes the deployment, oldest first.
27870
+ *
27871
+ * Selected by the `outbox_owed` marker the attached forward path writes, not
27872
+ * by a time window — see captureRowsStmt for why a window could not express
27873
+ * this. `before` is the grace window that leaves a just-recorded capture to
27874
+ * the live path.
27875
+ */
27876
+ pendingCaptureRows(limit, before) {
27877
+ return allRows(this.captureRowsStmt, { limit, before });
27878
+ }
27879
+ /**
27880
+ * Record that a capture is OWED to the deployment.
27881
+ *
27882
+ * Written by the attached forward path when a live send did not confirm
27883
+ * delivery, and read by the drain as the whole of its eligibility test. It is
27884
+ * a fact rather than an inference: the machine was attached, the send did not
27885
+ * land, so the row is owed — which no time window can state, because the same
27886
+ * window that holds the rows a past attachment left owed also holds every
27887
+ * capture recorded while the machine was DETACHED, and those were never
27888
+ * offered to anyone.
27889
+ *
27890
+ * Idempotent, and never un-set: `markSynced` settling the row is what takes it
27891
+ * out of the drain's read.
27892
+ */
27893
+ markCaptureOwed(id) {
27894
+ this.markOwedStmt.run({ id });
27895
+ }
27656
27896
  /** Record delivery. Called only AFTER the far side has accepted the rows. */
27657
27897
  markSynced(ids, atMs) {
27658
27898
  this.stampAll(ids, atMs);
@@ -27736,10 +27976,12 @@ var SqliteHistorySyncRepository = class {
27736
27976
  this.countsStmt,
27737
27977
  { before }
27738
27978
  );
27979
+ const captures = getRow(this.captureSkipCountStmt);
27739
27980
  return {
27740
27981
  pending: row?.pending ?? 0,
27741
27982
  sent: row?.sent ?? 0,
27742
- skipped: row?.skipped ?? 0
27983
+ skipped: row?.skipped ?? 0,
27984
+ capturesSkipped: captures?.skipped ?? 0
27743
27985
  };
27744
27986
  }
27745
27987
  /**
@@ -27780,7 +28022,11 @@ var SqliteHistorySyncRepository = class {
27780
28022
  withTransaction(
27781
28023
  this.db,
27782
28024
  () => {
28025
+ const previous = getRow(this.fingerprintStmt)?.fingerprint;
27783
28026
  this.rearmStmt.run();
28027
+ if (previous !== null && previous !== void 0 && previous !== fingerprint) {
28028
+ this.disownCapturesStmt.run();
28029
+ }
27784
28030
  this.setFingerprintStmt.run({ fingerprint, backlogBefore });
27785
28031
  },
27786
28032
  "IMMEDIATE"
@@ -27977,7 +28223,259 @@ var SqliteInspectionFindingsRepository = class {
27977
28223
  };
27978
28224
 
27979
28225
  // ../../packages/persistence/src/repositories/installed-packs.ts
27980
- import { createHash as createHash2, randomUUID as randomUUID3 } from "crypto";
28226
+ import { createHash as createHash2, randomUUID as randomUUID4 } from "crypto";
28227
+
28228
+ // ../../packages/persistence/src/policy-floor.ts
28229
+ import { readFileSync as readFileSync5 } from "fs";
28230
+ import { join as join6 } from "path";
28231
+
28232
+ // ../../packages/persistence/src/local-layout.ts
28233
+ import { renameSync as renameSync3 } from "fs";
28234
+ import { mkdir } from "fs/promises";
28235
+ import { homedir } from "os";
28236
+ import { join as join4 } from "path";
28237
+ function defaultDataDir() {
28238
+ return join4(homedir(), ".aka");
28239
+ }
28240
+ function settingsDir(base = defaultDataDir()) {
28241
+ return join4(base, "settings");
28242
+ }
28243
+ function dataDir(base = defaultDataDir()) {
28244
+ return join4(base, "data");
28245
+ }
28246
+ function dbPath(base = defaultDataDir()) {
28247
+ return join4(dataDir(base), "aka.db");
28248
+ }
28249
+ function keysDir(base = defaultDataDir()) {
28250
+ return join4(base, "keys");
28251
+ }
28252
+ async function ensureDataDir(dir = defaultDataDir()) {
28253
+ await mkdir(dir, { recursive: true, mode: DATA_DIR_MODE });
28254
+ tightenDir(dir);
28255
+ }
28256
+ function ensureLayoutDirSync(dir = defaultDataDir()) {
28257
+ ensureDataDirSync(dir);
28258
+ }
28259
+ function migrateLegacyLayout(base = defaultDataDir()) {
28260
+ const moves = [
28261
+ { name: "config.json", dest: settingsDir(base) },
28262
+ { name: "policy-cache.json", dest: dataDir(base) }
28263
+ ];
28264
+ for (const { name, dest } of moves) {
28265
+ try {
28266
+ ensureDataDirSync(dest);
28267
+ const moved = join4(dest, name);
28268
+ renameSync3(join4(base, name), moved);
28269
+ tightenFile(moved);
28270
+ } catch {
28271
+ }
28272
+ }
28273
+ }
28274
+
28275
+ // ../../packages/persistence/src/settings.ts
28276
+ import { readFileSync as readFileSync4 } from "fs";
28277
+ import { join as join5 } from "path";
28278
+
28279
+ // ../../packages/persistence/src/file-lock.ts
28280
+ import { randomUUID as randomUUID3 } from "crypto";
28281
+ import {
28282
+ closeSync,
28283
+ existsSync as existsSync2,
28284
+ openSync,
28285
+ readFileSync as readFileSync2,
28286
+ rmSync as rmSync5,
28287
+ statSync as statSync3,
28288
+ writeFileSync as writeFileSync2
28289
+ } from "fs";
28290
+ import { hostname as hostname3 } from "os";
28291
+ var PARK = new Int32Array(new SharedArrayBuffer(4));
28292
+
28293
+ // ../../packages/persistence/src/managed-settings.ts
28294
+ import { readFileSync as readFileSync3 } from "fs";
28295
+ import { posix, win32 } from "path";
28296
+ function managedSettingsPaths(platform2 = process.platform) {
28297
+ if (platform2 === "darwin") {
28298
+ return [
28299
+ posix.join("/Library", "Application Support", "AKASecurity", MANAGED_SETTINGS_FILENAME),
28300
+ posix.join("/Library", "Managed Preferences", MANAGED_SETTINGS_FILENAME)
28301
+ ];
28302
+ }
28303
+ if (platform2 === "win32") {
28304
+ return [win32.join("C:\\", "ProgramData", "AKASecurity", MANAGED_SETTINGS_FILENAME)];
28305
+ }
28306
+ return [posix.join("/etc", "aka", MANAGED_SETTINGS_FILENAME)];
28307
+ }
28308
+ function readManagedSettings(paths = managedSettingsPaths()) {
28309
+ for (const path of paths) {
28310
+ let text;
28311
+ try {
28312
+ text = readFileSync3(path, "utf8");
28313
+ } catch {
28314
+ continue;
28315
+ }
28316
+ const record2 = parseJsonObject(text);
28317
+ if (!record2) continue;
28318
+ const parsed2 = ManagedSettings.safeParse(record2);
28319
+ if (parsed2.success) return parsed2.data;
28320
+ }
28321
+ return null;
28322
+ }
28323
+ function overlayManagedSettings(settings, managed, now = () => /* @__PURE__ */ new Date()) {
28324
+ if (!managed) return settings;
28325
+ const { values } = managed;
28326
+ const merged = { ...settings };
28327
+ if (values.runMode !== void 0) merged.runMode = values.runMode;
28328
+ if (values.controlPlane !== void 0) {
28329
+ merged.controlPlane = {
28330
+ ...values.controlPlane,
28331
+ // The administrator pinned WHICH deployment, not WHEN this machine
28332
+ // joined it. Keep the user's own attach time when the endpoint is
28333
+ // unchanged, so a managed machine does not appear to re-attach on every
28334
+ // read; stamp a fresh one when the administrator moved it.
28335
+ attachedAt: settings.controlPlane?.endpoint === values.controlPlane.endpoint ? settings.controlPlane.attachedAt : now().toISOString()
28336
+ };
28337
+ }
28338
+ if (values.historicalAccess !== void 0) merged.historicalAccess = values.historicalAccess;
28339
+ if (values.vaultKeyCustody !== void 0) merged.vaultKeyCustody = values.vaultKeyCustody;
28340
+ if (values.vaultInlineReveal !== void 0) merged.vaultInlineReveal = values.vaultInlineReveal;
28341
+ if (values.dataSharesInPlace !== void 0) merged.dataSharesInPlace = values.dataSharesInPlace;
28342
+ if (values.redactFallback !== void 0) merged.redactFallback = values.redactFallback;
28343
+ if (values.vaultConsent !== void 0) {
28344
+ merged.vaultConsent = values.vaultConsent ? (
28345
+ // Keep an existing valid grant so its acknowledgedAt survives; mint one
28346
+ // at the current version otherwise.
28347
+ settings.vaultConsent?.version === VAULT_CONSENT_VERSION ? settings.vaultConsent : { acknowledgedAt: now().toISOString(), version: VAULT_CONSENT_VERSION }
28348
+ ) : void 0;
28349
+ }
28350
+ if (values.modelJudgeConsent !== void 0) {
28351
+ merged.modelJudgeConsent = values.modelJudgeConsent ? settings.modelJudgeConsent?.payloadVersion === MODEL_JUDGE_PAYLOAD_VERSION ? settings.modelJudgeConsent : {
28352
+ acknowledgedAt: now().toISOString(),
28353
+ payloadVersion: MODEL_JUDGE_PAYLOAD_VERSION
28354
+ } : void 0;
28355
+ }
28356
+ return merged;
28357
+ }
28358
+
28359
+ // ../../packages/persistence/src/settings.ts
28360
+ var SETTINGS_FILENAME = "settings.json";
28361
+ function readWorkspaceSettings(base = defaultDataDir()) {
28362
+ return overlayManagedSettings(readUserSettings(base), readManagedSettings());
28363
+ }
28364
+ function readUserSettings(base) {
28365
+ const record2 = readJson(join5(settingsDir(base), SETTINGS_FILENAME));
28366
+ if (!record2) return defaultWorkspaceSettings();
28367
+ try {
28368
+ return WorkspaceSettings.parse(record2);
28369
+ } catch {
28370
+ return defaultWorkspaceSettings();
28371
+ }
28372
+ }
28373
+ function readJson(file2) {
28374
+ let text;
28375
+ try {
28376
+ text = readFileSync4(file2, "utf8");
28377
+ } catch {
28378
+ return null;
28379
+ }
28380
+ return parseJsonObject(text) ?? null;
28381
+ }
28382
+
28383
+ // ../../packages/persistence/src/policy-floor.ts
28384
+ function refusalMessage(pack, attempted, floor, refusal) {
28385
+ switch (refusal) {
28386
+ case "lock":
28387
+ return `refusing to re-assign '${pack}': its policy is set by the connected control plane`;
28388
+ case "disable":
28389
+ return `refusing to disable '${pack}': it is governed by the connected control plane`;
28390
+ case "floor":
28391
+ return `refusing to set '${pack}' to '${attempted ?? "unassigned"}': the connected control plane requires at least '${floor}'`;
28392
+ }
28393
+ }
28394
+ var PolicyFloorError = class extends Error {
28395
+ /** `namespace/packId` of the detection whose write was refused. */
28396
+ pack;
28397
+ /**
28398
+ * The archetype the caller asked for, or null when the write named none —
28399
+ * clearing the assignment, or switching the detection off.
28400
+ */
28401
+ attempted;
28402
+ /** The weakest archetype the control plane permits for this pack. */
28403
+ floor;
28404
+ refusal;
28405
+ constructor(pack, attempted, floor, refusal) {
28406
+ super(refusalMessage(pack, attempted, floor, refusal));
28407
+ this.name = "PolicyFloorError";
28408
+ this.pack = pack;
28409
+ this.attempted = attempted;
28410
+ this.floor = floor;
28411
+ this.refusal = refusal;
28412
+ }
28413
+ };
28414
+ function readCachedPolicyBundle(base = defaultDataDir()) {
28415
+ try {
28416
+ const raw = readFileSync5(join6(dataDir(base), POLICY_CACHE_FILENAME), "utf8");
28417
+ const parsed2 = JSON.parse(raw);
28418
+ if (typeof parsed2 !== "object" || parsed2 === null) return null;
28419
+ return PolicyBundle.parse(parsed2.bundle);
28420
+ } catch {
28421
+ return null;
28422
+ }
28423
+ }
28424
+ function indexEnabled(policies) {
28425
+ const byRuleId = /* @__PURE__ */ new Map();
28426
+ const byCategory = /* @__PURE__ */ new Map();
28427
+ for (const policy of policies) {
28428
+ if (!policy.enabled) continue;
28429
+ if ("ruleId" in policy.target) {
28430
+ if (!byRuleId.has(policy.target.ruleId)) byRuleId.set(policy.target.ruleId, policy.action);
28431
+ } else if (!byCategory.has(policy.target.category)) {
28432
+ byCategory.set(policy.target.category, policy.action);
28433
+ }
28434
+ }
28435
+ return { byRuleId, byCategory };
28436
+ }
28437
+ function hasAuthoredPolicy(policies, rules, byRuleId) {
28438
+ const ruleIds = new Set(rules.map((rule) => rule.id));
28439
+ const categories = new Set(rules.map((rule) => rule.category));
28440
+ const bundleNamesPack = rules.some((rule) => byRuleId.has(rule.id));
28441
+ return policies.some((policy) => {
28442
+ if (!policy.enabled || policy.provenance !== "authored") return false;
28443
+ return "ruleId" in policy.target ? ruleIds.has(policy.target.ruleId) : bundleNamesPack && categories.has(policy.target.category);
28444
+ });
28445
+ }
28446
+ function controlPlanePolicyFloor(rules, base = defaultDataDir()) {
28447
+ const floors = openControlPlaneFloors(base);
28448
+ return floors === null ? null : floors.floorFor(rules);
28449
+ }
28450
+ function openControlPlaneFloors(base = defaultDataDir()) {
28451
+ if (!isAttached(readWorkspaceSettings(base))) return null;
28452
+ const bundle = readCachedPolicyBundle(base);
28453
+ if (bundle === null) return null;
28454
+ const indexes = indexEnabled(bundle.policies);
28455
+ return { floorFor: (rules) => resolveFloor(rules, bundle.policies, indexes) };
28456
+ }
28457
+ function resolveFloor(rules, policies, { byRuleId, byCategory }) {
28458
+ let action = null;
28459
+ for (const rule of rules) {
28460
+ const resolved = byRuleId.get(rule.id) ?? byCategory.get(rule.category);
28461
+ if (resolved === void 0) continue;
28462
+ action = action === null ? resolved : strongerAction(action, resolved);
28463
+ }
28464
+ if (action === null) return null;
28465
+ return {
28466
+ floor: weakestBuiltinAtLeast(action),
28467
+ locked: hasAuthoredPolicy(policies, rules, byRuleId)
28468
+ };
28469
+ }
28470
+ function policyAssignmentRefusal(policyId, floor) {
28471
+ if (floor.locked) return "lock";
28472
+ const effective = policyId ?? DEFAULT_PACK_POLICY_ID;
28473
+ return isActionAtLeast(builtinPolicyToAction(effective), builtinPolicyToAction(floor.floor)) ? null : "floor";
28474
+ }
28475
+ function packEnablementRefusal(enabled, floor) {
28476
+ if (floor === null || enabled) return null;
28477
+ return "disable";
28478
+ }
27981
28479
 
27982
28480
  // ../../packages/persistence/src/semver.ts
27983
28481
  function parse3(version2) {
@@ -28071,8 +28569,19 @@ function ruleIdsOf(rulesJson) {
28071
28569
  return ids;
28072
28570
  }
28073
28571
  var SqliteInstalledPacksRepository = class {
28074
- constructor(db) {
28572
+ /**
28573
+ * `baseDir` is the `~/.aka` LAYOUT BASE, not the data dir — the control-plane
28574
+ * floor needs both halves of it (settings/ says whether this machine is
28575
+ * attached, data/ holds the cached bundle). It is optional because a caller
28576
+ * holding only a DatabaseSync — every test construction site, and any embedder
28577
+ * that opens the store itself — has no layout to point at, and such a caller
28578
+ * gets the pre-existing behaviour: no floor, no lock. Production threads it in
28579
+ * from `openLocalDatabase`, which is the single construction site that owns a
28580
+ * real `~/.aka`.
28581
+ */
28582
+ constructor(db, baseDir) {
28075
28583
  this.db = db;
28584
+ this.baseDir = baseDir;
28076
28585
  this.insertMissingStmt = db.prepare(
28077
28586
  `INSERT INTO installed_packs (id, namespace, pack_id, version, name, rules_json, enabled, created_at, updated_at)
28078
28587
  VALUES (:id, :namespace, :packId, :version, :name, :rulesJson, 1, :now, :now)
@@ -28094,11 +28603,17 @@ var SqliteInstalledPacksRepository = class {
28094
28603
  this.signatureStmt = db.prepare(
28095
28604
  `SELECT namespace, pack_id AS packId, version, rules_json AS rulesJson FROM available_packs`
28096
28605
  );
28606
+ this.packRulesStmt = db.prepare(
28607
+ `SELECT rules_json AS rulesJson FROM installed_packs
28608
+ WHERE namespace = ? AND pack_id = ?`
28609
+ );
28097
28610
  }
28098
28611
  db;
28612
+ baseDir;
28099
28613
  insertMissingStmt;
28100
28614
  upsertAvailableStmt;
28101
28615
  signatureStmt;
28616
+ packRulesStmt;
28102
28617
  /**
28103
28618
  * Record the running binary's detection inventory. Refreshes the
28104
28619
  * available_packs mirror (pruning packs the binary no longer ships) and
@@ -28140,7 +28655,7 @@ var SqliteInstalledPacksRepository = class {
28140
28655
  let behind = false;
28141
28656
  for (const row of rows) {
28142
28657
  const params = {
28143
- id: randomUUID3(),
28658
+ id: randomUUID4(),
28144
28659
  namespace: row.namespace,
28145
28660
  packId: row.packId,
28146
28661
  version: row.version,
@@ -28152,7 +28667,7 @@ var SqliteInstalledPacksRepository = class {
28152
28667
  if (stored === void 0 || !isMirrorDowngrade(row, stored)) {
28153
28668
  this.upsertAvailableStmt.run({
28154
28669
  ...params,
28155
- id: randomUUID3(),
28670
+ id: randomUUID4(),
28156
28671
  recordedBy: meta4?.recordedBy ?? null
28157
28672
  });
28158
28673
  } else {
@@ -28398,9 +28913,65 @@ var SqliteInstalledPacksRepository = class {
28398
28913
  // NOT on the hook path — so, unlike recordInventory, these surface errors to the
28399
28914
  // caller rather than swallowing them. Each returns whether a row matched, so the
28400
28915
  // caller can tell an edit from a no-such-detection.
28916
+ /**
28917
+ * The rules one installed pack owns, reduced to what a floor computation
28918
+ * reads. Display-tolerant parsing on purpose: a pack whose snapshot is
28919
+ * unreadable contributes no rules to a scan either, so it is not a detection
28920
+ * the control plane can be governing, and an empty list correctly imposes no
28921
+ * floor. Enabled state is deliberately not filtered — a disabled pack is one
28922
+ * the user can re-enable, and its assignment stays governed meanwhile.
28923
+ */
28924
+ packFloorRules(namespace, packId) {
28925
+ const row = getRow(this.packRulesStmt, [namespace, packId]);
28926
+ if (!row) return [];
28927
+ return parseRules(row.rulesJson).map((rule) => ({ id: rule.id, category: rule.category }));
28928
+ }
28929
+ /**
28930
+ * What the connected control plane imposes on one installed pack, or null on a
28931
+ * machine that is its own authority (standalone, no cached bundle, or a
28932
+ * repository constructed without a layout base).
28933
+ *
28934
+ * Exposed as a READ so a surface can render the constraint — grey out the
28935
+ * choices below the floor, mark a locked detection as locked — rather than
28936
+ * offer the user a picker whose selections it will then be told it may not
28937
+ * make. The refusal in `setPolicy` does not depend on any surface calling this.
28938
+ */
28939
+ policyFloor(namespace, packId) {
28940
+ if (this.baseDir === void 0) return null;
28941
+ return controlPlanePolicyFloor(this.packFloorRules(namespace, packId), this.baseDir);
28942
+ }
28943
+ /**
28944
+ * The same answer for several packs, keyed `namespace/packId` and carrying an
28945
+ * entry only for a pack the control plane actually governs.
28946
+ *
28947
+ * A surface listing every detection asks per pack, and asking through
28948
+ * `policyFloor` re-reads the settings, re-reads and re-parses the whole cached
28949
+ * bundle and rebuilds its indexes once per pack — the entire cost of one
28950
+ * answer, repeated for each row, on every render. This reads all of that once.
28951
+ * Packs whose rules the snapshot cannot produce simply contribute no entry,
28952
+ * exactly as the single-pack read returns null for them.
28953
+ */
28954
+ policyFloors(packs2) {
28955
+ const floors = /* @__PURE__ */ new Map();
28956
+ if (this.baseDir === void 0) return floors;
28957
+ const source = openControlPlaneFloors(this.baseDir);
28958
+ if (source === null) return floors;
28959
+ for (const pack of packs2) {
28960
+ const floor = source.floorFor(this.packFloorRules(pack.namespace, pack.packId));
28961
+ if (floor !== null) floors.set(`${pack.namespace}/${pack.packId}`, floor);
28962
+ }
28963
+ return floors;
28964
+ }
28401
28965
  /**
28402
28966
  * Assign (or clear, with null) the enforcement policy for one installed pack.
28403
- * `policyId` must be a known built-in id (monitor/warn/redact/block).
28967
+ * `policyId` must be a known built-in id (monitor/warn/redact/block/vault).
28968
+ *
28969
+ * On an ATTACHED machine the organization's bundle is a floor this refuses to
28970
+ * write below, and a detection the organization has authored a policy for is
28971
+ * refused outright — see policy-floor.ts for both, and for why the refusal is
28972
+ * a throw rather than a silently substituted value. This is the one device-local
28973
+ * write path for the assignment, so the check belongs here rather than on any
28974
+ * surface that offers the choice.
28404
28975
  */
28405
28976
  setPolicy(namespace, packId, policyId) {
28406
28977
  if (policyId !== null && !BuiltinPolicyId.safeParse(policyId).success) {
@@ -28408,14 +28979,38 @@ var SqliteInstalledPacksRepository = class {
28408
28979
  `Unknown policy '${policyId}'. Must be one of: ${KNOWN_BUILTIN_IDS.join(", ")}.`
28409
28980
  );
28410
28981
  }
28982
+ const requested = policyId;
28983
+ const floor = this.policyFloor(namespace, packId);
28984
+ if (floor !== null) {
28985
+ const refusal = policyAssignmentRefusal(requested, floor);
28986
+ if (refusal !== null) {
28987
+ throw new PolicyFloorError(`${namespace}/${packId}`, requested, floor.floor, refusal);
28988
+ }
28989
+ }
28411
28990
  const res = this.db.prepare(
28412
28991
  `UPDATE installed_packs SET policy_id = :policyId, updated_at = :now
28413
28992
  WHERE namespace = :namespace AND pack_id = :packId`
28414
28993
  ).run({ policyId, now: Date.now(), namespace, packId });
28415
28994
  return Number(res.changes) > 0;
28416
28995
  }
28417
- /** Enable or disable one installed pack. */
28996
+ /**
28997
+ * Enable or disable one installed pack.
28998
+ *
28999
+ * On an ATTACHED machine a detection the organization's bundle governs at all
29000
+ * may not be switched OFF here — see packEnablementRefusal for why that is not
29001
+ * merely another point below the floor, and why re-enabling stays open. Like
29002
+ * the assignment above, the check belongs at this write path rather than on a
29003
+ * surface: this is the one device-local writer of the column, and a refusal
29004
+ * that lived in a page would leave the CLI free.
29005
+ */
28418
29006
  setEnabled(namespace, packId, enabled) {
29007
+ const floor = this.policyFloor(namespace, packId);
29008
+ if (floor !== null) {
29009
+ const refusal = packEnablementRefusal(enabled, floor);
29010
+ if (refusal !== null) {
29011
+ throw new PolicyFloorError(`${namespace}/${packId}`, null, floor.floor, refusal);
29012
+ }
29013
+ }
28419
29014
  const res = this.db.prepare(
28420
29015
  `UPDATE installed_packs SET enabled = :enabled, updated_at = :now
28421
29016
  WHERE namespace = :namespace AND pack_id = :packId`
@@ -28501,7 +29096,7 @@ var SqliteInventoryRepository = class {
28501
29096
  };
28502
29097
 
28503
29098
  // ../../packages/persistence/src/repositories/inventory-assets.ts
28504
- import { randomUUID as randomUUID4 } from "crypto";
29099
+ import { randomUUID as randomUUID5 } from "crypto";
28505
29100
  var CATEGORY_ORDER = ["config", "skill", "mcp", "hook"];
28506
29101
  var VALID_HARNESS_IDS = new Set(HarnessId.options);
28507
29102
  var WORKTREE_CHECKOUT_FILTER = "(url IS NULL OR (url NOT LIKE '%/.claude/worktrees/%' AND url NOT LIKE '%\\.claude\\worktrees\\%'))";
@@ -28990,7 +29585,7 @@ var SqliteInventoryAssetsRepository = class {
28990
29585
  `INSERT INTO file_access_override (id, project_id, path, access, created_at, updated_at)
28991
29586
  VALUES (:id, :projectId, :path, :access, :now, :now)
28992
29587
  ON CONFLICT (project_id, path) DO UPDATE SET access = excluded.access, updated_at = excluded.updated_at`
28993
- ).run({ id: randomUUID4(), projectId, path, access, now: Date.now() });
29588
+ ).run({ id: randomUUID5(), projectId, path, access, now: Date.now() });
28994
29589
  }
28995
29590
  return true;
28996
29591
  }
@@ -29011,7 +29606,7 @@ var SqliteInventoryAssetsRepository = class {
29011
29606
  `INSERT INTO mcp_trust_override (id, asset_id, trust, created_at, updated_at)
29012
29607
  VALUES (:id, :assetId, :trust, :now, :now)
29013
29608
  ON CONFLICT (asset_id) DO UPDATE SET trust = excluded.trust, updated_at = excluded.updated_at`
29014
- ).run({ id: randomUUID4(), assetId, trust, now: Date.now() });
29609
+ ).run({ id: randomUUID5(), assetId, trust, now: Date.now() });
29015
29610
  }
29016
29611
  this.configRowsCache = void 0;
29017
29612
  return "ok";
@@ -29308,7 +29903,7 @@ var SqliteInventoryAssetsRepository = class {
29308
29903
  };
29309
29904
 
29310
29905
  // ../../packages/persistence/src/repositories/policies.ts
29311
- import { randomUUID as randomUUID5 } from "crypto";
29906
+ import { randomUUID as randomUUID6 } from "crypto";
29312
29907
  var SqlitePoliciesRepository = class {
29313
29908
  constructor(db) {
29314
29909
  this.db = db;
@@ -29343,7 +29938,7 @@ var SqlitePoliciesRepository = class {
29343
29938
  failOpenTransaction(this.db, () => {
29344
29939
  for (const [category, action] of Object.entries(DEFAULT_ACTIONS)) {
29345
29940
  stmt.run({
29346
- id: randomUUID5(),
29941
+ id: randomUUID6(),
29347
29942
  target: JSON.stringify({ category }),
29348
29943
  action,
29349
29944
  now: Date.now()
@@ -29363,7 +29958,7 @@ var SqlitePoliciesRepository = class {
29363
29958
  `INSERT INTO policies (id, scope, target, action, enabled, created_at, updated_at)
29364
29959
  VALUES (:id, 'global', :target, :action, 1, :now, :now)
29365
29960
  ON CONFLICT(scope, target) DO UPDATE SET action = excluded.action, enabled = 1, updated_at = excluded.updated_at`
29366
- ).run({ id: randomUUID5(), target: JSON.stringify({ category }), action, now });
29961
+ ).run({ id: randomUUID6(), target: JSON.stringify({ category }), action, now });
29367
29962
  }
29368
29963
  // Caps every global per-category policy currently set to block/redact down
29369
29964
  // to warn (see warn-era-cap.ts). Rule-targeted policies are untouched.
@@ -29431,7 +30026,7 @@ var SqlitePolicyCatalogRepository = class {
29431
30026
  };
29432
30027
 
29433
30028
  // ../../packages/persistence/src/repositories/project-files.ts
29434
- import { randomUUID as randomUUID6 } from "crypto";
30029
+ import { randomUUID as randomUUID7 } from "crypto";
29435
30030
  var SqliteProjectFilesRepository = class {
29436
30031
  constructor(db) {
29437
30032
  this.db = db;
@@ -29463,7 +30058,7 @@ var SqliteProjectFilesRepository = class {
29463
30058
  const stamp = Math.max(now, maxStamp + 1);
29464
30059
  for (const file2 of scan2.files) {
29465
30060
  this.upsertStmt.run({
29466
- id: randomUUID6(),
30061
+ id: randomUUID7(),
29467
30062
  projectId,
29468
30063
  path: file2.path,
29469
30064
  name: file2.name,
@@ -29477,9 +30072,9 @@ var SqliteProjectFilesRepository = class {
29477
30072
  };
29478
30073
 
29479
30074
  // ../../packages/persistence/src/repositories/resolutions.ts
29480
- import { randomUUID as randomUUID7 } from "crypto";
30075
+ import { randomUUID as randomUUID8 } from "crypto";
29481
30076
  var SqliteResolutionsRepository = class {
29482
- constructor(db, now = () => Date.now(), newId = () => randomUUID7()) {
30077
+ constructor(db, now = () => Date.now(), newId = () => randomUUID8()) {
29483
30078
  this.db = db;
29484
30079
  this.now = now;
29485
30080
  this.newId = newId;
@@ -29692,7 +30287,7 @@ var SqliteScanLedgerRepository = class {
29692
30287
  };
29693
30288
 
29694
30289
  // ../../packages/persistence/src/repositories/secret-vault.ts
29695
- import { randomUUID as randomUUID8 } from "crypto";
30290
+ import { randomUUID as randomUUID9 } from "crypto";
29696
30291
  function pageLimit(requested, fallback) {
29697
30292
  if (requested === void 0) return fallback;
29698
30293
  return Math.min(Math.max(1, Math.trunc(requested)), MAX_VAULT_PAGE_LIMIT);
@@ -29738,12 +30333,14 @@ var SELECT_COLUMNS = `
29738
30333
  ciphertext,
29739
30334
  nonce,
29740
30335
  auth_tag AS authTag,
30336
+ user_authorized AS userAuthorized,
29741
30337
  occurrence_count AS occurrenceCount,
29742
30338
  first_seen AS firstSeen,
29743
30339
  last_seen AS lastSeen`;
29744
30340
  function toRow(raw) {
29745
- const { provider, ...rest } = raw;
29746
- return provider === null ? rest : { ...rest, provider };
30341
+ const { provider, userAuthorized, ...rest } = raw;
30342
+ const row = { ...rest, userAuthorized: userAuthorized !== 0 };
30343
+ return provider === null ? row : { ...row, provider };
29747
30344
  }
29748
30345
  var SqliteSecretVaultRepository = class {
29749
30346
  constructor(db) {
@@ -29753,17 +30350,18 @@ var SqliteSecretVaultRepository = class {
29753
30350
  pointer_id, value_fingerprint, fingerprint_key_version, key_version,
29754
30351
  format_version, category, rule_id, masked_match, provider,
29755
30352
  ciphertext, nonce, auth_tag,
29756
- occurrence_count, first_seen, last_seen
30353
+ user_authorized, occurrence_count, first_seen, last_seen
29757
30354
  ) VALUES (
29758
30355
  :pointerId, :valueFingerprint, :fingerprintKeyVersion, :keyVersion,
29759
30356
  :formatVersion, :category, :ruleId, :maskedMatch, :provider,
29760
30357
  :ciphertext, :nonce, :authTag,
29761
- 1, :now, :now
30358
+ :userAuthorized, 1, :now, :now
29762
30359
  )`
29763
30360
  );
29764
30361
  this.bumpStmt = db.prepare(
29765
30362
  `UPDATE secret_vault
29766
- SET occurrence_count = occurrence_count + 1, last_seen = :now
30363
+ SET occurrence_count = occurrence_count + 1, last_seen = :now,
30364
+ user_authorized = max(user_authorized, :userAuthorized)
29767
30365
  WHERE value_fingerprint = :valueFingerprint`
29768
30366
  );
29769
30367
  this.byPointerStmt = db.prepare(
@@ -29783,6 +30381,7 @@ var SqliteSecretVaultRepository = class {
29783
30381
  SET value_fingerprint = :valueFingerprint, fingerprint_key_version = :fingerprintKeyVersion
29784
30382
  WHERE pointer_id = :pointerId`
29785
30383
  );
30384
+ this.deleteByPointerStmt = db.prepare(`DELETE FROM secret_vault WHERE pointer_id = :pointerId`);
29786
30385
  this.derefStmt = db.prepare(
29787
30386
  `INSERT INTO secret_vault_deref (id, pointer_id, at, target, reason, outcome, grant_id, pointer_count)
29788
30387
  VALUES (:id, :pointerId, :at, :target, :reason, :outcome, :grantId, :pointerCount)`
@@ -29796,6 +30395,7 @@ var SqliteSecretVaultRepository = class {
29796
30395
  listStmt;
29797
30396
  replaceCiphertextStmt;
29798
30397
  refreshFingerprintStmt;
30398
+ deleteByPointerStmt;
29799
30399
  derefStmt;
29800
30400
  /**
29801
30401
  * Vault a value, or record another sighting of one already vaulted. Keyed on
@@ -29804,6 +30404,11 @@ var SqliteSecretVaultRepository = class {
29804
30404
  * pointer, category and ciphertext, so the same secret always resolves to one
29805
30405
  * wire token. `minted` is true only when this call created the row.
29806
30406
  *
30407
+ * `userAuthorized` is the one field a repeat call may still change, and only
30408
+ * upwards: it records that a PERSON asked for this value to be replaced, and
30409
+ * the row is shared with every automatic path that vaults the same value. See
30410
+ * `bumpStmt` for why clearing it is the defect this shape exists to refuse.
30411
+ *
29807
30412
  * The read-then-write runs in one IMMEDIATE transaction so two concurrent
29808
30413
  * writers cannot both decide they are minting.
29809
30414
  */
@@ -29830,13 +30435,18 @@ var SqliteSecretVaultRepository = class {
29830
30435
  ciphertext: input2.ciphertext,
29831
30436
  nonce: input2.nonce,
29832
30437
  authTag: input2.authTag,
30438
+ userAuthorized: input2.userAuthorized === true ? 1 : 0,
29833
30439
  now
29834
30440
  })
29835
30441
  );
29836
30442
  minted = true;
29837
30443
  return;
29838
30444
  }
29839
- this.bumpStmt.run({ valueFingerprint: input2.valueFingerprint, now });
30445
+ this.bumpStmt.run({
30446
+ valueFingerprint: input2.valueFingerprint,
30447
+ userAuthorized: input2.userAuthorized === true ? 1 : 0,
30448
+ now
30449
+ });
29840
30450
  },
29841
30451
  "IMMEDIATE"
29842
30452
  );
@@ -29896,6 +30506,42 @@ var SqliteSecretVaultRepository = class {
29896
30506
  );
29897
30507
  return destroyed;
29898
30508
  }
30509
+ /**
30510
+ * Destroy the named entries and report WHICH ones went — the scoped
30511
+ * counterpart to `purgeAll`, for a caller that has already put those specific
30512
+ * values back where they came from. Ids the store does not hold are absent
30513
+ * from the answer rather than an error, so a set assembled from a stale read
30514
+ * is not a fault. The deref audit is left alone, exactly as the purge leaves
30515
+ * it.
30516
+ *
30517
+ * The ids come back rather than a count because the caller's next act is to
30518
+ * write a purge row per destroyed entry, and a record of destruction has to
30519
+ * be a record of what was really destroyed: a selection is a claim about a
30520
+ * read that has since gone stale, and auditing from it invents a purge for an
30521
+ * entry still sitting in the vault.
30522
+ *
30523
+ * One transaction over the whole set rather than a statement per id: the
30524
+ * caller hands this the result of a restore pass it has completed, and a
30525
+ * fault partway through must leave the vault as it was found rather than
30526
+ * destroying a prefix of it. The vault holds the only copy of what a pointer
30527
+ * stands for, so half a delete is not a state anything can recover from.
30528
+ */
30529
+ deleteByPointerIds(pointerIds) {
30530
+ if (pointerIds.length === 0) return [];
30531
+ const deleted = [];
30532
+ withTransaction(
30533
+ this.db,
30534
+ () => {
30535
+ for (const pointerId of pointerIds) {
30536
+ if (Number(this.deleteByPointerStmt.run({ pointerId }).changes) > 0) {
30537
+ deleted.push(pointerId);
30538
+ }
30539
+ }
30540
+ },
30541
+ "IMMEDIATE"
30542
+ );
30543
+ return deleted;
30544
+ }
29899
30545
  /**
29900
30546
  * Record (or re-stamp) one place a pointer has been written. One row per
29901
30547
  * (pointer, location); a re-sighting bumps last_seen. Best-effort bookkeeping
@@ -29908,7 +30554,7 @@ var SqliteSecretVaultRepository = class {
29908
30554
  VALUES (:id, :pointerId, :location, :kind, :now, :now)
29909
30555
  ON CONFLICT (pointer_id, location) DO UPDATE SET last_seen = :now`
29910
30556
  ).run({
29911
- id: randomUUID8(),
30557
+ id: randomUUID9(),
29912
30558
  pointerId: entry.pointerId,
29913
30559
  location: entry.location,
29914
30560
  kind: entry.kind,
@@ -30421,15 +31067,15 @@ var SqliteSecurityRepository = class {
30421
31067
  const from = now - RANGE_DAYS[range] * DAY_MS4;
30422
31068
  const rows = allRows(
30423
31069
  this.db.prepare(
30424
- `SELECT json_extract(e.attributes, '$.repo') AS repo, count(*) AS c
31070
+ `SELECT e.repo AS repo, count(*) AS c
30425
31071
  FROM inspection_findings f
30426
31072
  JOIN audit_events e ON e.id = f.audit_event_id
30427
31073
  WHERE e.started_at >= :from AND e.started_at < :to
30428
31074
  AND e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
30429
- AND json_extract(e.attributes, '$.repo') IS NOT NULL
30430
- AND json_extract(e.attributes, '$.repo') != ''
30431
- GROUP BY repo
30432
- ORDER BY c DESC, repo
31075
+ AND e.repo IS NOT NULL
31076
+ AND e.repo != ''
31077
+ GROUP BY e.repo
31078
+ ORDER BY c DESC, e.repo
30433
31079
  LIMIT :limit`
30434
31080
  ),
30435
31081
  { from, to: now, limit }
@@ -30491,7 +31137,7 @@ var SqliteSecurityRepository = class {
30491
31137
  `SELECT f.finding_key AS finding_key,
30492
31138
  d.rule_id AS rule_id,
30493
31139
  d.severity AS severity,
30494
- json_extract(e.attributes, '$.file_path') AS path,
31140
+ e.file_path AS path,
30495
31141
  COALESCE(f.first_detected_at, e.started_at) AS first_detected_at,
30496
31142
  latest.resolved_at AS latest_resolved_at
30497
31143
  FROM ${LATEST_RESOLUTION_BY_KEY_SQL} latest
@@ -30544,7 +31190,7 @@ var SqliteSecurityRepository = class {
30544
31190
  };
30545
31191
 
30546
31192
  // ../../packages/persistence/src/repositories/shares.ts
30547
- import { randomUUID as randomUUID9 } from "crypto";
31193
+ import { randomUUID as randomUUID10 } from "crypto";
30548
31194
  var MAX_EGRESS_CALL_SITES_PER_PROJECT = 5e3;
30549
31195
  var IN_CHUNK = 500;
30550
31196
  var KIND_ORDER = ["provider", "internal", "external", "ip"];
@@ -30632,7 +31278,7 @@ function buildSummary(dest, endpoints) {
30632
31278
  callSiteCount,
30633
31279
  transports: distinctTransports(transports),
30634
31280
  dataClasses: distinctDataClasses(dataClasses),
30635
- review: buildReviewInfo(dest.trust, transports),
31281
+ review: buildReviewInfo(dest.trust, transports, dest.overrideDecision !== null),
30636
31282
  network: dest.kind === "provider" ? null : parseNetwork(dest.networkJson),
30637
31283
  endpoints: endpoints.map(toEndpointSummary)
30638
31284
  };
@@ -30659,7 +31305,7 @@ function buildDetail(dest, endpoints, callSites) {
30659
31305
  lastSeen: new Date(lastSeenMs).toISOString(),
30660
31306
  transports: distinctTransports(transports),
30661
31307
  dataClasses: distinctDataClasses(endpoints.map((e) => e.dataClass)),
30662
- review: buildReviewInfo(dest.trust, transports),
31308
+ review: buildReviewInfo(dest.trust, transports, dest.overrideDecision !== null),
30663
31309
  network: dest.kind === "provider" ? null : parseNetwork(dest.networkJson),
30664
31310
  note: dest.note,
30665
31311
  endpoints: endpoints.map((ep) => ({
@@ -30688,7 +31334,11 @@ var SqliteSharesRepository = class {
30688
31334
  FROM share_destination d
30689
31335
  LEFT JOIN share_endpoint e ON e.destination_id = d.id
30690
31336
  AND e.transport IN ${PLAINTEXT_TRANSPORT_SQL}
30691
- WHERE d.trust IN ('unverified', 'ip') OR e.id IS NOT NULL`
31337
+ WHERE (d.trust IN ('unverified', 'ip') OR e.id IS NOT NULL)
31338
+ AND NOT EXISTS (
31339
+ SELECT 1 FROM egress_decision_override o
31340
+ WHERE o.host = d.host OR (o.destination_id = d.id AND o.host IS NULL)
31341
+ )`
30692
31342
  );
30693
31343
  const kindCounts = countBy(
30694
31344
  this.db,
@@ -30800,7 +31450,7 @@ var SqliteSharesRepository = class {
30800
31450
  (id, destination_id, host, decision, created_at, updated_at)
30801
31451
  VALUES (:id, :destinationId, :host, :decision, :now, :now)`
30802
31452
  ).run({
30803
- id: randomUUID9(),
31453
+ id: randomUUID10(),
30804
31454
  destinationId,
30805
31455
  host: dest.host,
30806
31456
  decision,
@@ -30949,7 +31599,7 @@ var SqliteSharesRepository = class {
30949
31599
  let destinationId = destIds.get(hit.host);
30950
31600
  if (destinationId === void 0) {
30951
31601
  destStmt.run({
30952
- id: randomUUID9(),
31602
+ id: randomUUID10(),
30953
31603
  kind: hit.kind,
30954
31604
  name: hit.name,
30955
31605
  host: hit.host,
@@ -30965,7 +31615,7 @@ var SqliteSharesRepository = class {
30965
31615
  let endpointId = endpointIds.get(endpointKey);
30966
31616
  if (endpointId === void 0) {
30967
31617
  endpointStmt.run({
30968
- id: randomUUID9(),
31618
+ id: randomUUID10(),
30969
31619
  destinationId,
30970
31620
  method: hit.method,
30971
31621
  transport: hit.transport,
@@ -30978,7 +31628,7 @@ var SqliteSharesRepository = class {
30978
31628
  endpointIds.set(endpointKey, endpointId);
30979
31629
  }
30980
31630
  siteStmt.run({
30981
- id: randomUUID9(),
31631
+ id: randomUUID10(),
30982
31632
  endpointId,
30983
31633
  project: input2.project,
30984
31634
  projectKey: input2.projectKey,
@@ -31343,6 +31993,7 @@ function purgeSampleData(db) {
31343
31993
  }
31344
31994
 
31345
31995
  // ../../packages/persistence/src/database.ts
31996
+ var CAPTURE_GRAIN = new Set(EventKind.options);
31346
31997
  var UNSAFE_TEST_ONLY_RAW_HANDLE = /* @__PURE__ */ Symbol(
31347
31998
  "aka.persistence.unsafeTestOnlyRawHandle"
31348
31999
  );
@@ -31390,7 +32041,7 @@ function backupLegacyStore(db, file2) {
31390
32041
  discardStore(file2, backup);
31391
32042
  return backup;
31392
32043
  }
31393
- function openAndInitialize(file2) {
32044
+ function openAndInitialize(file2, base) {
31394
32045
  let db = openWithPragmas(file2);
31395
32046
  try {
31396
32047
  if (isForeignSqliteLineage(db)) {
@@ -31403,7 +32054,7 @@ function openAndInitialize(file2) {
31403
32054
  applyMigrations(db, file2);
31404
32055
  tightenPerms(file2);
31405
32056
  const policies = new SqlitePoliciesRepository(db);
31406
- const installedPacks = new SqliteInstalledPacksRepository(db);
32057
+ const installedPacks = new SqliteInstalledPacksRepository(db, base);
31407
32058
  const repositories = {
31408
32059
  events: new SqliteEventsRepository(db),
31409
32060
  findings: new SqliteFindingsRepository(db),
@@ -31439,7 +32090,7 @@ function openAndInitialize(file2) {
31439
32090
  }
31440
32091
  function openLocalDatabase(dir) {
31441
32092
  ensureDataDirSync(dir);
31442
- const file2 = join4(dir, DB_FILENAME);
32093
+ const file2 = join7(dir, DB_FILENAME);
31443
32094
  reapStalePartials(file2);
31444
32095
  const {
31445
32096
  db,
@@ -31467,7 +32118,13 @@ function openLocalDatabase(dir) {
31467
32118
  inspectionDefinitions,
31468
32119
  inspectionFindings,
31469
32120
  configInventory
31470
- } = openAndInitialize(file2);
32121
+ } = openAndInitialize(
32122
+ file2,
32123
+ // `dir` is always `<base>/data` — every caller resolves it through
32124
+ // `dataDir()` — so its parent is the `~/.aka` base the layout splits into
32125
+ // settings/ and data/, and the pack-policy floor needs both halves.
32126
+ dirname2(dir)
32127
+ );
31471
32128
  function captureRowId(event) {
31472
32129
  return captureId(
31473
32130
  event.metadata?.sessionId ?? null,
@@ -31480,6 +32137,21 @@ function openLocalDatabase(dir) {
31480
32137
  historySync.markSynced([captureRowId(event)], atMs);
31481
32138
  });
31482
32139
  }
32140
+ function markCaptureOwed(event) {
32141
+ failOpenTransaction(db, () => {
32142
+ historySync.markCaptureOwed(captureRowId(event));
32143
+ });
32144
+ }
32145
+ function markAuditEventsDelivered(events2, atMs) {
32146
+ const stampable = events2.filter((event) => !CAPTURE_GRAIN.has(event.eventType));
32147
+ if (stampable.length === 0) return;
32148
+ failOpenTransaction(db, () => {
32149
+ historySync.markSynced(
32150
+ stampable.map((event) => event.id),
32151
+ atMs
32152
+ );
32153
+ });
32154
+ }
31483
32155
  function recordCapture(event, detected) {
31484
32156
  failOpenTransaction(db, () => {
31485
32157
  const sessionId = event.metadata?.sessionId;
@@ -31566,7 +32238,7 @@ function openLocalDatabase(dir) {
31566
32238
  const definitionId = definitionIds.get(`${finding.ruleId}@${finding.version}`);
31567
32239
  if (!definitionId) continue;
31568
32240
  inspectionFindings.insertFinding({
31569
- id: randomUUID10(),
32241
+ id: randomUUID11(),
31570
32242
  auditEventId: record2.scanEvent.id,
31571
32243
  inspectionDefinitionId: definitionId,
31572
32244
  span: finding.span,
@@ -31662,6 +32334,8 @@ function openLocalDatabase(dir) {
31662
32334
  inspectionFindings,
31663
32335
  recordCapture,
31664
32336
  markCaptureDelivered,
32337
+ markCaptureOwed,
32338
+ markAuditEventsDelivered,
31665
32339
  ensureInventory,
31666
32340
  recordConfigScan,
31667
32341
  recordProjectFiles,
@@ -31680,20 +32354,6 @@ function openLocalDatabase(dir) {
31680
32354
  };
31681
32355
  }
31682
32356
 
31683
- // ../../packages/persistence/src/file-lock.ts
31684
- import { randomUUID as randomUUID11 } from "crypto";
31685
- import {
31686
- closeSync,
31687
- existsSync as existsSync2,
31688
- openSync,
31689
- readFileSync as readFileSync2,
31690
- rmSync as rmSync5,
31691
- statSync as statSync3,
31692
- writeFileSync as writeFileSync2
31693
- } from "fs";
31694
- import { hostname as hostname3 } from "os";
31695
- var PARK = new Int32Array(new SharedArrayBuffer(4));
31696
-
31697
32357
  // ../../packages/persistence/src/finding-key.ts
31698
32358
  import { createHash as createHash3 } from "crypto";
31699
32359
  function normalizeFilePath(filePath) {
@@ -31706,13 +32366,13 @@ function computeFindingKey(input2) {
31706
32366
 
31707
32367
  // ../../packages/persistence/src/fingerprint.ts
31708
32368
  import { createHmac, randomBytes } from "crypto";
31709
- import { existsSync as existsSync3, readFileSync as readFileSync3 } from "fs";
31710
- import { join as join5 } from "path";
32369
+ import { existsSync as existsSync3, readFileSync as readFileSync6 } from "fs";
32370
+ import { join as join8 } from "path";
31711
32371
  import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
31712
32372
  var EXCEPTION_KEY_FILENAME = "exception.key";
31713
32373
  var KEY_MATERIAL_BYTES = 32;
31714
32374
  function keyFilePath(dataDir2) {
31715
- return join5(dataDir2, EXCEPTION_KEY_FILENAME);
32375
+ return join8(dataDir2, EXCEPTION_KEY_FILENAME);
31716
32376
  }
31717
32377
  function parseKeyFile(raw) {
31718
32378
  const parsed2 = JSON.parse(raw);
@@ -31750,7 +32410,7 @@ var FloorUnreadableError = class extends Error {
31750
32410
  }
31751
32411
  };
31752
32412
  function storedKeyVersionFloor(dataDir2) {
31753
- const file2 = join5(dataDir2, DB_FILENAME);
32413
+ const file2 = join8(dataDir2, DB_FILENAME);
31754
32414
  if (!existsSync3(file2)) return 0;
31755
32415
  let db;
31756
32416
  try {
@@ -31805,7 +32465,7 @@ function occupantMessage(file2, kind) {
31805
32465
  function readFingerprintKey(dataDir2) {
31806
32466
  let raw;
31807
32467
  try {
31808
- raw = readFileSync3(keyFilePath(dataDir2), "utf8");
32468
+ raw = readFileSync6(keyFilePath(dataDir2), "utf8");
31809
32469
  } catch (err) {
31810
32470
  if (err.code === "ENOENT") return null;
31811
32471
  throw err instanceof Error ? err : new Error(String(err));
@@ -31829,146 +32489,12 @@ function fingerprintValue(key, raw) {
31829
32489
 
31830
32490
  // ../../packages/persistence/src/history-preview.ts
31831
32491
  import { existsSync as existsSync4 } from "fs";
31832
- import { join as join6 } from "path";
32492
+ import { join as join9 } from "path";
31833
32493
  import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
31834
32494
 
31835
- // ../../packages/persistence/src/local-layout.ts
31836
- import { renameSync as renameSync3 } from "fs";
31837
- import { mkdir } from "fs/promises";
31838
- import { homedir } from "os";
31839
- import { join as join7 } from "path";
31840
- function defaultDataDir() {
31841
- return join7(homedir(), ".aka");
31842
- }
31843
- function settingsDir(base = defaultDataDir()) {
31844
- return join7(base, "settings");
31845
- }
31846
- function dataDir(base = defaultDataDir()) {
31847
- return join7(base, "data");
31848
- }
31849
- function dbPath(base = defaultDataDir()) {
31850
- return join7(dataDir(base), "aka.db");
31851
- }
31852
- function keysDir(base = defaultDataDir()) {
31853
- return join7(base, "keys");
31854
- }
31855
- async function ensureDataDir(dir = defaultDataDir()) {
31856
- await mkdir(dir, { recursive: true, mode: DATA_DIR_MODE });
31857
- tightenDir(dir);
31858
- }
31859
- function ensureLayoutDirSync(dir = defaultDataDir()) {
31860
- ensureDataDirSync(dir);
31861
- }
31862
- function migrateLegacyLayout(base = defaultDataDir()) {
31863
- const moves = [
31864
- { name: "config.json", dest: settingsDir(base) },
31865
- { name: "policy-cache.json", dest: dataDir(base) }
31866
- ];
31867
- for (const { name, dest } of moves) {
31868
- try {
31869
- ensureDataDirSync(dest);
31870
- const moved = join7(dest, name);
31871
- renameSync3(join7(base, name), moved);
31872
- tightenFile(moved);
31873
- } catch {
31874
- }
31875
- }
31876
- }
31877
-
31878
- // ../../packages/persistence/src/managed-settings.ts
31879
- import { readFileSync as readFileSync4 } from "fs";
31880
- import { posix, win32 } from "path";
31881
- function managedSettingsPaths(platform2 = process.platform) {
31882
- if (platform2 === "darwin") {
31883
- return [
31884
- posix.join("/Library", "Application Support", "AKASecurity", MANAGED_SETTINGS_FILENAME),
31885
- posix.join("/Library", "Managed Preferences", MANAGED_SETTINGS_FILENAME)
31886
- ];
31887
- }
31888
- if (platform2 === "win32") {
31889
- return [win32.join("C:\\", "ProgramData", "AKASecurity", MANAGED_SETTINGS_FILENAME)];
31890
- }
31891
- return [posix.join("/etc", "aka", MANAGED_SETTINGS_FILENAME)];
31892
- }
31893
- function readManagedSettings(paths = managedSettingsPaths()) {
31894
- for (const path of paths) {
31895
- let text;
31896
- try {
31897
- text = readFileSync4(path, "utf8");
31898
- } catch {
31899
- continue;
31900
- }
31901
- const record2 = parseJsonObject(text);
31902
- if (!record2) continue;
31903
- const parsed2 = ManagedSettings.safeParse(record2);
31904
- if (parsed2.success) return parsed2.data;
31905
- }
31906
- return null;
31907
- }
31908
- function overlayManagedSettings(settings, managed, now = () => /* @__PURE__ */ new Date()) {
31909
- if (!managed) return settings;
31910
- const { values } = managed;
31911
- const merged = { ...settings };
31912
- if (values.runMode !== void 0) merged.runMode = values.runMode;
31913
- if (values.controlPlane !== void 0) {
31914
- merged.controlPlane = {
31915
- ...values.controlPlane,
31916
- // The administrator pinned WHICH deployment, not WHEN this machine
31917
- // joined it. Keep the user's own attach time when the endpoint is
31918
- // unchanged, so a managed machine does not appear to re-attach on every
31919
- // read; stamp a fresh one when the administrator moved it.
31920
- attachedAt: settings.controlPlane?.endpoint === values.controlPlane.endpoint ? settings.controlPlane.attachedAt : now().toISOString()
31921
- };
31922
- }
31923
- if (values.historicalAccess !== void 0) merged.historicalAccess = values.historicalAccess;
31924
- if (values.vaultKeyCustody !== void 0) merged.vaultKeyCustody = values.vaultKeyCustody;
31925
- if (values.vaultInlineReveal !== void 0) merged.vaultInlineReveal = values.vaultInlineReveal;
31926
- if (values.dataSharesInPlace !== void 0) merged.dataSharesInPlace = values.dataSharesInPlace;
31927
- if (values.vaultConsent !== void 0) {
31928
- merged.vaultConsent = values.vaultConsent ? (
31929
- // Keep an existing valid grant so its acknowledgedAt survives; mint one
31930
- // at the current version otherwise.
31931
- settings.vaultConsent?.version === VAULT_CONSENT_VERSION ? settings.vaultConsent : { acknowledgedAt: now().toISOString(), version: VAULT_CONSENT_VERSION }
31932
- ) : void 0;
31933
- }
31934
- if (values.modelJudgeConsent !== void 0) {
31935
- merged.modelJudgeConsent = values.modelJudgeConsent ? settings.modelJudgeConsent?.payloadVersion === MODEL_JUDGE_PAYLOAD_VERSION ? settings.modelJudgeConsent : {
31936
- acknowledgedAt: now().toISOString(),
31937
- payloadVersion: MODEL_JUDGE_PAYLOAD_VERSION
31938
- } : void 0;
31939
- }
31940
- return merged;
31941
- }
31942
-
31943
- // ../../packages/persistence/src/settings.ts
31944
- import { readFileSync as readFileSync5 } from "fs";
31945
- import { join as join8 } from "path";
31946
- var SETTINGS_FILENAME = "settings.json";
31947
- function readWorkspaceSettings(base = defaultDataDir()) {
31948
- return overlayManagedSettings(readUserSettings(base), readManagedSettings());
31949
- }
31950
- function readUserSettings(base) {
31951
- const record2 = readJson(join8(settingsDir(base), SETTINGS_FILENAME));
31952
- if (!record2) return defaultWorkspaceSettings();
31953
- try {
31954
- return WorkspaceSettings.parse(record2);
31955
- } catch {
31956
- return defaultWorkspaceSettings();
31957
- }
31958
- }
31959
- function readJson(file2) {
31960
- let text;
31961
- try {
31962
- text = readFileSync5(file2, "utf8");
31963
- } catch {
31964
- return null;
31965
- }
31966
- return parseJsonObject(text) ?? null;
31967
- }
31968
-
31969
32495
  // ../../packages/persistence/src/store-symlinks.ts
31970
32496
  import { existsSync as existsSync5, lstatSync as lstatSync3, readlinkSync, realpathSync, statSync as statSync4 } from "fs";
31971
- import { dirname as dirname2, join as join9, resolve } from "path";
32497
+ import { dirname as dirname3, join as join10, resolve } from "path";
31972
32498
  var STORE_DB = "the store database (including the prompt corpus)";
31973
32499
  var STORE_SETTINGS = "your settings file";
31974
32500
  function storeContents(home) {
@@ -31977,7 +32503,7 @@ function storeContents(home) {
31977
32503
  [settingsDir(home), STORE_SETTINGS],
31978
32504
  [dataDir(home), STORE_DB],
31979
32505
  [keysDir(home), "the vault key"],
31980
- [join9(settingsDir(home), "settings.json"), STORE_SETTINGS],
32506
+ [join10(settingsDir(home), "settings.json"), STORE_SETTINGS],
31981
32507
  [dbPath(home), STORE_DB]
31982
32508
  ]);
31983
32509
  }
@@ -32005,7 +32531,7 @@ function linkTarget(path) {
32005
32531
  try {
32006
32532
  return realpathSync(path);
32007
32533
  } catch {
32008
- return resolve(dirname2(path), readlinkSync(path));
32534
+ return resolve(dirname3(path), readlinkSync(path));
32009
32535
  }
32010
32536
  }
32011
32537
  function targetMode(path, platform2) {
@@ -32029,19 +32555,19 @@ import {
32029
32555
  // ../../packages/persistence/src/vault/key-provider.ts
32030
32556
  import { execFileSync } from "child_process";
32031
32557
  import { randomBytes as randomBytes2 } from "crypto";
32032
- import { chmodSync as chmodSync3, readFileSync as readFileSync6, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
32033
- import { join as join10 } from "path";
32558
+ import { chmodSync as chmodSync3, readFileSync as readFileSync7, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
32559
+ import { join as join11 } from "path";
32034
32560
 
32035
32561
  // ../../packages/persistence/src/vault/vault.ts
32036
32562
  import { randomBytes as randomBytes3, randomUUID as randomUUID12 } from "crypto";
32037
32563
 
32038
32564
  // ../../packages/persistence/src/warn-era-cap.ts
32039
32565
  import { existsSync as existsSync6, writeFileSync as writeFileSync4 } from "fs";
32040
- import { join as join11 } from "path";
32566
+ import { join as join12 } from "path";
32041
32567
  var MARKER = "warn-era-capped";
32042
32568
  function capWarnEraEnforcementOnce(db, policyMode, dataDir2) {
32043
32569
  if (policyMode !== "warn") return { capped: 0, skipped: "not-warn" };
32044
- const marker = join11(dataDir2, MARKER);
32570
+ const marker = join12(dataDir2, MARKER);
32045
32571
  if (existsSync6(marker)) return { capped: 0, skipped: "already-run" };
32046
32572
  const capped = db.policies.capCategoryActions();
32047
32573
  writeFileSync4(marker, `${new Date(Date.now()).toISOString()}
@@ -32101,7 +32627,7 @@ function resolveProvider() {
32101
32627
  function loadConfig(base = defaultDataDir(), resolveProviderFn = resolveProvider) {
32102
32628
  try {
32103
32629
  ensureLayoutDirSync(base);
32104
- const settingsFile = join12(settingsDir(base), "settings.json");
32630
+ const settingsFile = join13(settingsDir(base), "settings.json");
32105
32631
  if (existsSync7(settingsFile)) tightenFile(settingsFile);
32106
32632
  } catch {
32107
32633
  }
@@ -32125,9 +32651,9 @@ function resolveProviderSafe(resolveProviderFn) {
32125
32651
  }
32126
32652
 
32127
32653
  // ../../packages/plugin-sdk/src/config-inventory.ts
32128
- import { readdirSync as readdirSync2, readFileSync as readFileSync8, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
32654
+ import { readdirSync as readdirSync2, readFileSync as readFileSync9, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
32129
32655
  import { homedir as homedir2 } from "os";
32130
- import { basename as basename3, join as join14 } from "path";
32656
+ import { basename as basename3, join as join15 } from "path";
32131
32657
 
32132
32658
  // ../../packages/detections/src/egress/registry.ts
32133
32659
  var EXTRACTOR_VERSION = "1";
@@ -35216,8 +35742,8 @@ function bundledDetections() {
35216
35742
  }
35217
35743
 
35218
35744
  // ../../packages/plugin-sdk/src/repo.ts
35219
- import { existsSync as existsSync8, readFileSync as readFileSync7, statSync as statSync6 } from "fs";
35220
- import { basename as basename2, dirname as dirname3, isAbsolute, join as join13, sep as sep2 } from "path";
35745
+ import { existsSync as existsSync8, readFileSync as readFileSync8, statSync as statSync6 } from "fs";
35746
+ import { basename as basename2, dirname as dirname4, isAbsolute, join as join14, sep as sep2 } from "path";
35221
35747
  function resolveRepo(cwd) {
35222
35748
  try {
35223
35749
  const root = findGitRoot(cwd);
@@ -35232,36 +35758,36 @@ function resolveRepo(cwd) {
35232
35758
  function findGitRoot(start) {
35233
35759
  let dir = start;
35234
35760
  for (; ; ) {
35235
- if (existsSync8(join13(dir, ".git"))) return dir;
35236
- const parent = dirname3(dir);
35761
+ if (existsSync8(join14(dir, ".git"))) return dir;
35762
+ const parent = dirname4(dir);
35237
35763
  if (parent === dir) return void 0;
35238
35764
  dir = parent;
35239
35765
  }
35240
35766
  }
35241
35767
  function resolveGitContext(root) {
35242
- const dotGit = join13(root, ".git");
35768
+ const dotGit = join14(root, ".git");
35243
35769
  try {
35244
35770
  if (statSync6(dotGit).isDirectory()) {
35245
- return { configPath: join13(dotGit, "config"), headRoot: root };
35771
+ return { configPath: join14(dotGit, "config"), headRoot: root };
35246
35772
  }
35247
35773
  } catch {
35248
35774
  return void 0;
35249
35775
  }
35250
35776
  const target = /^gitdir:\s*(.+?)\s*$/m.exec(safeRead(dotGit) ?? "")?.[1];
35251
35777
  if (!target) return void 0;
35252
- const gitdir = isAbsolute(target) ? target : join13(root, target);
35253
- if (existsSync8(join13(gitdir, "config"))) {
35254
- return { configPath: join13(gitdir, "config"), headRoot: root };
35778
+ const gitdir = isAbsolute(target) ? target : join14(root, target);
35779
+ if (existsSync8(join14(gitdir, "config"))) {
35780
+ return { configPath: join14(gitdir, "config"), headRoot: root };
35255
35781
  }
35256
- const commonRaw = safeRead(join13(gitdir, "commondir"))?.trim();
35782
+ const commonRaw = safeRead(join14(gitdir, "commondir"))?.trim();
35257
35783
  if (!commonRaw) return void 0;
35258
- const commonGitDir = isAbsolute(commonRaw) ? commonRaw : join13(gitdir, commonRaw);
35259
- const headRoot = basename2(commonGitDir) === ".git" ? dirname3(commonGitDir) : root;
35260
- return { configPath: join13(commonGitDir, "config"), headRoot };
35784
+ const commonGitDir = isAbsolute(commonRaw) ? commonRaw : join14(gitdir, commonRaw);
35785
+ const headRoot = basename2(commonGitDir) === ".git" ? dirname4(commonGitDir) : root;
35786
+ return { configPath: join14(commonGitDir, "config"), headRoot };
35261
35787
  }
35262
35788
  function safeRead(path) {
35263
35789
  try {
35264
- return readFileSync7(path, "utf8");
35790
+ return readFileSync8(path, "utf8");
35265
35791
  } catch {
35266
35792
  return void 0;
35267
35793
  }
@@ -35806,8 +36332,8 @@ function createGuardedScanner(partition, gateway, opts) {
35806
36332
 
35807
36333
  // ../../packages/plugin-sdk/src/ignore-layers.ts
35808
36334
  var import_ignore = __toESM(require_ignore(), 1);
35809
- import { readFileSync as readFileSync9 } from "fs";
35810
- import { join as join15 } from "path";
36335
+ import { readFileSync as readFileSync10 } from "fs";
36336
+ import { join as join16 } from "path";
35811
36337
 
35812
36338
  // ../../packages/plugin-sdk/src/inventory-resolver.ts
35813
36339
  import { arch, hostname as hostname4, platform, release } from "os";
@@ -35818,24 +36344,59 @@ import {
35818
36344
  fstatSync,
35819
36345
  mkdirSync as mkdirSync2,
35820
36346
  openSync as openSync2,
35821
- readFileSync as readFileSync10,
36347
+ readFileSync as readFileSync11,
35822
36348
  readSync,
35823
36349
  writeFileSync as writeFileSync5
35824
36350
  } from "fs";
35825
- import { join as join16 } from "path";
36351
+ import { join as join17 } from "path";
35826
36352
  var TAIL_BYTES = 256 * 1024;
35827
36353
 
35828
36354
  // ../../packages/plugin-sdk/src/nudge.ts
35829
- import { mkdirSync as mkdirSync3, readFileSync as readFileSync11, writeFileSync as writeFileSync6 } from "fs";
35830
- import { join as join17 } from "path";
36355
+ import { mkdirSync as mkdirSync3, readFileSync as readFileSync12, writeFileSync as writeFileSync6 } from "fs";
36356
+ import { join as join18 } from "path";
35831
36357
 
35832
36358
  // ../../packages/plugin-sdk/src/paths.ts
35833
36359
  import { readdirSync as readdirSync3, realpathSync as realpathSync3 } from "fs";
35834
- import { basename as basename4, dirname as dirname4, sep as sep3 } from "path";
36360
+ import { basename as basename4, dirname as dirname5, sep as sep3 } from "path";
36361
+
36362
+ // ../../packages/plugin-sdk/src/policy-resolver.ts
36363
+ function createPolicyResolver(bundle) {
36364
+ const byRule = /* @__PURE__ */ new Map();
36365
+ const byCategory = /* @__PURE__ */ new Map();
36366
+ let reversible = /* @__PURE__ */ new Set();
36367
+ try {
36368
+ for (const policy of bundle.policies) {
36369
+ if (!policy.enabled) continue;
36370
+ if ("ruleId" in policy.target) {
36371
+ if (!byRule.has(policy.target.ruleId)) byRule.set(policy.target.ruleId, policy.action);
36372
+ } else if (!byCategory.has(policy.target.category)) {
36373
+ byCategory.set(policy.target.category, policy.action);
36374
+ }
36375
+ }
36376
+ reversible = new Set(bundle.reversibleRuleIds ?? []);
36377
+ } catch {
36378
+ byRule.clear();
36379
+ byCategory.clear();
36380
+ reversible = /* @__PURE__ */ new Set();
36381
+ }
36382
+ return {
36383
+ actionFor(ruleId, category) {
36384
+ const byRuleAction = byRule.get(ruleId);
36385
+ if (byRuleAction !== void 0) return byRuleAction;
36386
+ const byCategoryAction = byCategory.get(category);
36387
+ if (byCategoryAction !== void 0) return byCategoryAction;
36388
+ const fallback = DEFAULT_ACTIONS[category];
36389
+ return fallback ?? "log";
36390
+ },
36391
+ isReversible(ruleId) {
36392
+ return reversible.has(ruleId);
36393
+ }
36394
+ };
36395
+ }
35835
36396
 
35836
36397
  // ../../packages/plugin-sdk/src/project-files.ts
35837
36398
  import { existsSync as existsSync10, readdirSync as readdirSync4 } from "fs";
35838
- import { basename as basename5, join as join18 } from "path";
36399
+ import { basename as basename5, join as join19 } from "path";
35839
36400
 
35840
36401
  // ../../packages/plugin-sdk/src/provider-env-antigravity.ts
35841
36402
  var optionalBaseUrl2 = external_exports.preprocess((v) => {
@@ -35866,7 +36427,6 @@ var CodexProviderEnvSchema = external_exports.object(codexProviderEnvShape);
35866
36427
  // ../../packages/plugin-sdk/src/runtime.ts
35867
36428
  import { randomUUID as randomUUID14 } from "crypto";
35868
36429
  var ENFORCEMENT_CEILING_ENABLED = false;
35869
- var ACTION_PRIORITY = ["block", "redact", "warn", "log", "allow"];
35870
36430
  function startTiming() {
35871
36431
  try {
35872
36432
  return performance.now();
@@ -35903,28 +36463,22 @@ function createPluginRuntime(gateway, settings, opts) {
35903
36463
  bundlesPacked = true;
35904
36464
  }
35905
36465
  const policyMode = settings.policy;
36466
+ const redactFallback = settings.redactFallback;
35906
36467
  const dataDir2 = opts?.dataDir;
35907
- let policies = [];
35908
36468
  let rules = [];
35909
36469
  let scanner;
35910
36470
  let bundleExceptions = [];
35911
36471
  let initialized = false;
35912
- const ruleActionIndex = /* @__PURE__ */ new Map();
35913
- const categoryActionIndex = /* @__PURE__ */ new Map();
35914
- let reversibleRuleIndex = /* @__PURE__ */ new Set();
36472
+ let resolver = createPolicyResolver({
36473
+ version: "",
36474
+ policies: [],
36475
+ customKeywords: [],
36476
+ fetchedAt: ""
36477
+ });
35915
36478
  async function ensureInitialized() {
35916
36479
  if (initialized) return;
35917
36480
  const bundle = await gateway.getPolicyBundle();
35918
- policies = bundle.policies;
35919
- for (const p of policies) {
35920
- if (!p.enabled) continue;
35921
- if ("ruleId" in p.target) {
35922
- if (!ruleActionIndex.has(p.target.ruleId)) ruleActionIndex.set(p.target.ruleId, p.action);
35923
- } else if (!categoryActionIndex.has(p.target.category)) {
35924
- categoryActionIndex.set(p.target.category, p.action);
35925
- }
35926
- }
35927
- reversibleRuleIndex = new Set(bundle.reversibleRuleIds ?? []);
36481
+ resolver = createPolicyResolver(bundle);
35928
36482
  const bundledProbeKeys = new Set(
35929
36483
  getLoadedRules().map(ruleProbeKey).filter((key) => key !== void 0)
35930
36484
  );
@@ -35977,33 +36531,28 @@ function createPluginRuntime(gateway, settings, opts) {
35977
36531
  return cachedKey;
35978
36532
  }
35979
36533
  function resolveAction(ruleId, category) {
35980
- const byRule = ruleActionIndex.get(ruleId);
35981
- if (byRule !== void 0) return byRule;
35982
- const byCategory = categoryActionIndex.get(category);
35983
- if (byCategory !== void 0) return byCategory;
35984
- const fallback = DEFAULT_ACTIONS[category];
35985
- return fallback ?? "log";
35986
- }
35987
- function actionForFinding(finding, excepted) {
36534
+ return resolver.actionFor(ruleId, category);
36535
+ }
36536
+ function actionForFinding(finding, excepted, rewritable = true) {
35988
36537
  if (excepted?.has(finding)) return "allow";
35989
36538
  const action = resolveAction(finding.ruleId, finding.category);
36539
+ if (!rewritable && action === "redact") return builtinPolicyToAction(redactFallback);
35990
36540
  if (ENFORCEMENT_CEILING_ENABLED && policyMode === "warn" && (action === "block" || action === "redact")) {
35991
36541
  return "warn";
35992
36542
  }
35993
36543
  return action;
35994
36544
  }
35995
- function decide(findings, text, excepted) {
36545
+ function decide(findings, text, excepted, rewritable = true) {
35996
36546
  if (findings.length === 0) return { action: "log", text, findings: [] };
35997
- const actionFor = (finding) => actionForFinding(finding, excepted);
36547
+ const actionFor = (finding) => actionForFinding(finding, excepted, rewritable);
35998
36548
  let worst = "log";
35999
36549
  for (const finding of findings) {
36000
- const action = actionFor(finding);
36001
- if (ACTION_PRIORITY.indexOf(action) < ACTION_PRIORITY.indexOf(worst)) worst = action;
36550
+ worst = strongerAction(worst, actionFor(finding));
36002
36551
  }
36003
36552
  if (worst === "block") return { action: "block", text: null, findings };
36004
36553
  if (worst === "redact") {
36005
36554
  const redactFindings = findings.filter((f) => actionFor(f) === "redact");
36006
- const reversibleFindings = redactFindings.filter((f) => reversibleRuleIndex.has(f.ruleId));
36555
+ const reversibleFindings = redactFindings.filter((f) => resolver.isReversible(f.ruleId));
36007
36556
  return {
36008
36557
  action: "redact",
36009
36558
  text: redact(text, redactFindings),
@@ -36079,7 +36628,7 @@ function createPluginRuntime(gateway, settings, opts) {
36079
36628
  return { excepted: /* @__PURE__ */ new Set(), exceptionIds: [] };
36080
36629
  }
36081
36630
  }
36082
- async function recordBlockedDetections(decision, excepted, ctx, fpCache) {
36631
+ async function recordBlockedDetections(decision, excepted, ctx, fpCache, rewritable = true) {
36083
36632
  const references = [];
36084
36633
  try {
36085
36634
  if (decision.action !== "block" && decision.action !== "redact") return references;
@@ -36087,7 +36636,7 @@ function createPluginRuntime(gateway, settings, opts) {
36087
36636
  if (!key) return references;
36088
36637
  const seen = /* @__PURE__ */ new Set();
36089
36638
  for (const finding of decision.findings) {
36090
- const action = actionForFinding(finding, excepted);
36639
+ const action = actionForFinding(finding, excepted, rewritable);
36091
36640
  if (action !== "block" && action !== "redact") continue;
36092
36641
  const fp = fingerprintOf(key, finding, fpCache);
36093
36642
  const pair = `${finding.ruleId}:${fp}`;
@@ -36114,7 +36663,7 @@ function createPluginRuntime(gateway, settings, opts) {
36114
36663
  }
36115
36664
  return references;
36116
36665
  }
36117
- async function evaluate(text, context, ctx) {
36666
+ async function evaluate(text, context, ctx, rewritable = true) {
36118
36667
  try {
36119
36668
  await ensureInitialized();
36120
36669
  if (!scanner) throw new Error("the runtime initialized without a scanner");
@@ -36123,8 +36672,14 @@ function createPluginRuntime(gateway, settings, opts) {
36123
36672
  const findings = dropShieldedFindings(matched, shielded.spans);
36124
36673
  const fpCache = /* @__PURE__ */ new Map();
36125
36674
  const { excepted, exceptionIds } = await applyExceptions(findings, ctx, fpCache);
36126
- const decision = decide(findings, text, excepted);
36127
- const blockedReferences = await recordBlockedDetections(decision, excepted, ctx, fpCache);
36675
+ const decision = decide(findings, text, excepted, rewritable);
36676
+ const blockedReferences = await recordBlockedDetections(
36677
+ decision,
36678
+ excepted,
36679
+ ctx,
36680
+ fpCache,
36681
+ rewritable
36682
+ );
36128
36683
  if (blockedReferences.length > 0) decision.blockedReferences = blockedReferences;
36129
36684
  return { decision, excepted, exceptionIds };
36130
36685
  } catch {
@@ -36148,12 +36703,16 @@ function createPluginRuntime(gateway, settings, opts) {
36148
36703
  sourceTool: input2.sourceTool,
36149
36704
  metadata: input2.metadata,
36150
36705
  preAuthorizedGrantIds: opts2.preAuthorizedGrantIds
36151
- }
36706
+ },
36707
+ opts2.rewritable
36152
36708
  );
36153
36709
  if (opts2.persist === "with-findings" && decision.findings.length === 0) return decision;
36154
36710
  try {
36155
36711
  const contentHash = contentHashOf(input2.text);
36156
- const storedContent = decision.findings.length > 0 ? redact(input2.text, decision.findings) : input2.text;
36712
+ const maskedFindings = decision.findings.filter(
36713
+ (match) => isActionAtLeast(actionForFinding(match, excepted, opts2.rewritable), "redact")
36714
+ );
36715
+ const storedContent = maskedFindings.length > 0 ? redact(input2.text, maskedFindings) : input2.text;
36157
36716
  const inspectionMs = elapsedMs(timingStartedAt);
36158
36717
  const metadata = exceptionIds.length > 0 || inspectionMs !== void 0 ? {
36159
36718
  ...input2.metadata,
@@ -36190,7 +36749,7 @@ function createPluginRuntime(gateway, settings, opts) {
36190
36749
  severity: match.severity,
36191
36750
  span: match.span,
36192
36751
  maskedMatch,
36193
- actionTaken: actionForFinding(match, excepted),
36752
+ actionTaken: actionForFinding(match, excepted, opts2.rewritable),
36194
36753
  confidence: match.confidence,
36195
36754
  ...findingKey ? { findingKey } : {}
36196
36755
  };
@@ -36230,7 +36789,7 @@ var THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1e3;
36230
36789
 
36231
36790
  // ../../packages/plugin-sdk/src/throttle.ts
36232
36791
  import { mkdirSync as mkdirSync4, statSync as statSync8, writeFileSync as writeFileSync7 } from "fs";
36233
- import { join as join19 } from "path";
36792
+ import { join as join20 } from "path";
36234
36793
 
36235
36794
  // src/present.ts
36236
36795
  var fg = (hex3) => (text) => {
@@ -36421,8 +36980,8 @@ function baseMetadata(input2) {
36421
36980
  }
36422
36981
 
36423
36982
  // src/hooks/store-health.ts
36424
- import { mkdirSync as mkdirSync5, readFileSync as readFileSync17, writeFileSync as writeFileSync8 } from "fs";
36425
- import { dirname as dirname5, join as join26 } from "path";
36983
+ import { mkdirSync as mkdirSync5, readFileSync as readFileSync18, writeFileSync as writeFileSync8 } from "fs";
36984
+ import { dirname as dirname6, join as join27 } from "path";
36426
36985
 
36427
36986
  // ../../packages/plugin-runtime/src/attached/egress-wire.ts
36428
36987
  import { createHash as createHash5 } from "crypto";
@@ -36461,6 +37020,307 @@ function toEgressIngestRequest(input2) {
36461
37020
  };
36462
37021
  }
36463
37022
 
37023
+ // ../../packages/remote/src/http.ts
37024
+ import { request as httpRequest } from "http";
37025
+ import { request as httpsRequest } from "https";
37026
+ var DEFAULT_TIMEOUT_MS = 1e4;
37027
+ var MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
37028
+ var RemoteRequestError = class extends Error {
37029
+ constructor(status) {
37030
+ super(`control-plane request failed with status ${String(status)}`);
37031
+ this.status = status;
37032
+ this.name = "RemoteRequestError";
37033
+ }
37034
+ status;
37035
+ };
37036
+ var RemoteRouteAbsent = class extends Error {
37037
+ constructor(route) {
37038
+ super(`control plane does not serve ${route}`);
37039
+ this.route = route;
37040
+ this.name = "RemoteRouteAbsent";
37041
+ }
37042
+ route;
37043
+ };
37044
+ var RemoteRequestInvalid = class extends Error {
37045
+ constructor(route, cause) {
37046
+ super(`refusing to send a malformed body to ${route}`);
37047
+ this.cause = cause;
37048
+ this.name = "RemoteRequestInvalid";
37049
+ }
37050
+ cause;
37051
+ };
37052
+ var RemoteResponseInvalid = class extends Error {
37053
+ constructor(route, detail) {
37054
+ super(`control plane answered ${route} with ${detail}`);
37055
+ this.name = "RemoteResponseInvalid";
37056
+ }
37057
+ };
37058
+ var RemoteTransportError = class extends Error {
37059
+ /**
37060
+ * The status the peer sent, when headers arrived and only the BODY was
37061
+ * refused.
37062
+ *
37063
+ * Undefined for the ordinary case this class was written for — no answer at
37064
+ * all. It exists because two paths reject after a status has already been
37065
+ * delivered: an oversized body and an aborted response. Discarding it there
37066
+ * reported a deployment answering 401 with a verbose body as a network
37067
+ * outage, which sends the reader to look at their network instead of their
37068
+ * credential.
37069
+ */
37070
+ constructor(reason, status) {
37071
+ super(`control-plane request did not complete: ${reason}`);
37072
+ this.status = status;
37073
+ this.name = "RemoteTransportError";
37074
+ }
37075
+ status;
37076
+ };
37077
+ async function send(options) {
37078
+ const url2 = new URL(options.url);
37079
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
37080
+ const send_ = url2.protocol === "http:" ? httpRequest : httpsRequest;
37081
+ const requestOptions = {
37082
+ method: options.method,
37083
+ headers: {
37084
+ // CALLER HEADERS FIRST, so this module's own are not overridable. Spread
37085
+ // last they win, and two of the values below are ones no caller may
37086
+ // replace: `x-api-key` is the credential, and `content-length` is the
37087
+ // byte count that stops a multi-byte body being truncated by the
37088
+ // receiver. `SendOptions.headers` is a free-form record on an exported
37089
+ // function, so "no caller does that today" is not the guarantee to rely
37090
+ // on. The one header any caller actually passes — `if-none-match` on the
37091
+ // conditional GET — is untouched by this order.
37092
+ ...options.headers,
37093
+ // The credential. One header, matching what the deployment authenticates
37094
+ // on; a second copy in an `Authorization` header would be one more place
37095
+ // it can be logged by an intermediary for no gain.
37096
+ //
37097
+ // Spread conditionally rather than assigned as `undefined`: Node's header
37098
+ // handling and `content-length` bookkeeping treat a present-but-undefined
37099
+ // key differently from an absent one, and "the header is not there" is
37100
+ // the property the attach flow needs.
37101
+ ...options.apiKey === void 0 ? {} : { "x-api-key": options.apiKey },
37102
+ accept: "application/json",
37103
+ ...options.body === void 0 ? {} : {
37104
+ "content-type": "application/json",
37105
+ // Byte length, not string length: a multi-byte body sent with a
37106
+ // character count is truncated by the receiver.
37107
+ "content-length": String(Buffer.byteLength(options.body))
37108
+ }
37109
+ }
37110
+ };
37111
+ return new Promise((resolve2, reject) => {
37112
+ let settled = false;
37113
+ const fail = (reason, status) => {
37114
+ if (settled) return;
37115
+ settled = true;
37116
+ reject(new RemoteTransportError(reason, status));
37117
+ };
37118
+ const req = send_(url2, requestOptions, (res) => {
37119
+ const chunks = [];
37120
+ let size = 0;
37121
+ res.on("data", (chunk) => {
37122
+ size += chunk.length;
37123
+ if (size > MAX_RESPONSE_BYTES) {
37124
+ fail(`response exceeded ${String(MAX_RESPONSE_BYTES)} bytes`, res.statusCode);
37125
+ res.destroy();
37126
+ req.destroy();
37127
+ return;
37128
+ }
37129
+ chunks.push(chunk);
37130
+ });
37131
+ res.on("aborted", () => {
37132
+ fail("the response was aborted", res.statusCode);
37133
+ });
37134
+ res.on("end", () => {
37135
+ if (settled) return;
37136
+ settled = true;
37137
+ resolve2({
37138
+ status: res.statusCode ?? 0,
37139
+ headers: res.headers,
37140
+ body: Buffer.concat(chunks).toString("utf8")
37141
+ });
37142
+ });
37143
+ });
37144
+ const deadline = setTimeout(() => {
37145
+ fail(`no response within ${String(timeoutMs)}ms`);
37146
+ req.destroy();
37147
+ }, timeoutMs);
37148
+ deadline.unref();
37149
+ req.on("upgrade", (_res, socket) => {
37150
+ fail("the deployment answered with a protocol upgrade");
37151
+ socket.destroy();
37152
+ });
37153
+ req.on("close", () => {
37154
+ fail("the connection closed before a response was read");
37155
+ clearTimeout(deadline);
37156
+ });
37157
+ req.on("error", (err) => {
37158
+ fail(err.message);
37159
+ });
37160
+ if (options.body !== void 0) req.write(options.body);
37161
+ req.end();
37162
+ });
37163
+ }
37164
+
37165
+ // ../../packages/remote/src/client.ts
37166
+ var ROUTES = {
37167
+ events: "/v1/events",
37168
+ auditEvents: "/v1/audit-events",
37169
+ auditEventsBatch: "/v1/audit-events/batch",
37170
+ inventory: "/v1/inventory",
37171
+ storePosture: "/v1/store-posture",
37172
+ policyBundle: "/v1/policy-bundle",
37173
+ whoami: "/v1/plugin/whoami",
37174
+ shares: "/v1/shares",
37175
+ commands: "/v1/plugin/commands"
37176
+ };
37177
+ function ackRoute(id) {
37178
+ return `${ROUTES.commands}/${encodeURIComponent(id)}/ack`;
37179
+ }
37180
+ function headerValue(response, name) {
37181
+ const raw = response.headers[name];
37182
+ if (raw === void 0) return void 0;
37183
+ return Array.isArray(raw) ? raw[0] : raw;
37184
+ }
37185
+ function okBody(response) {
37186
+ if (response.status < 200 || response.status >= 300) {
37187
+ throw new RemoteRequestError(response.status);
37188
+ }
37189
+ return response.body;
37190
+ }
37191
+ function parsed(schema, body, route) {
37192
+ let json2;
37193
+ try {
37194
+ json2 = JSON.parse(body);
37195
+ } catch {
37196
+ throw new RemoteResponseInvalid(route, "a body that is not JSON");
37197
+ }
37198
+ const result = schema.safeParse(json2);
37199
+ if (!result.success) {
37200
+ throw new RemoteResponseInvalid(route, "a body this client cannot read");
37201
+ }
37202
+ return result.data;
37203
+ }
37204
+ function withoutTrailingSlashes(endpoint) {
37205
+ let end = endpoint.length;
37206
+ while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH) end -= 1;
37207
+ return endpoint.slice(0, end);
37208
+ }
37209
+ var SLASH = "/".charCodeAt(0);
37210
+ function createRemoteClient(options) {
37211
+ const base = withoutTrailingSlashes(options.endpoint);
37212
+ const url2 = (route) => `${base}${route}`;
37213
+ const common = { apiKey: options.apiKey, timeoutMs: options.timeoutMs };
37214
+ const sendOne = async (event) => {
37215
+ const validated = RecordAuditEventRequest.safeParse(event);
37216
+ if (!validated.success) throw new RemoteRequestInvalid(ROUTES.auditEvents, validated.error);
37217
+ const response = await send({
37218
+ ...common,
37219
+ method: "POST",
37220
+ url: url2(ROUTES.auditEvents),
37221
+ body: JSON.stringify(validated.data)
37222
+ });
37223
+ okBody(response);
37224
+ };
37225
+ return {
37226
+ async ingestEvents(batch) {
37227
+ const response = await send({
37228
+ ...common,
37229
+ method: "POST",
37230
+ url: url2(ROUTES.events),
37231
+ body: JSON.stringify(batch)
37232
+ });
37233
+ return parsed(IngestAck, okBody(response), ROUTES.events);
37234
+ },
37235
+ async ingestInventory(context) {
37236
+ const response = await send({
37237
+ ...common,
37238
+ method: "POST",
37239
+ url: url2(ROUTES.inventory),
37240
+ body: JSON.stringify(context)
37241
+ });
37242
+ return parsed(ResolvedInventory, okBody(response), ROUTES.inventory);
37243
+ },
37244
+ async recordAuditEvent(event) {
37245
+ await sendOne(event);
37246
+ },
37247
+ async recordAuditEvents(events, opts) {
37248
+ const validated = RecordAuditEventBatch.safeParse({ events });
37249
+ if (!validated.success) {
37250
+ throw new RemoteRequestInvalid(ROUTES.auditEventsBatch, validated.error);
37251
+ }
37252
+ const response = await send({
37253
+ ...common,
37254
+ method: "POST",
37255
+ url: url2(ROUTES.auditEventsBatch),
37256
+ body: JSON.stringify(validated.data)
37257
+ });
37258
+ if (response.status === 404) {
37259
+ if (opts?.fallbackToSingleEvents !== true) {
37260
+ throw new RemoteRouteAbsent(ROUTES.auditEventsBatch);
37261
+ }
37262
+ for (const event of validated.data.events) await sendOne(event);
37263
+ return { accepted: validated.data.events.length };
37264
+ }
37265
+ return parsed(AuditEventBatchAck, okBody(response), ROUTES.auditEventsBatch);
37266
+ },
37267
+ async reportStorePosture(snapshot) {
37268
+ const response = await send({
37269
+ ...common,
37270
+ method: "POST",
37271
+ url: url2(ROUTES.storePosture),
37272
+ body: JSON.stringify(snapshot)
37273
+ });
37274
+ okBody(response);
37275
+ },
37276
+ async getPolicyBundle(etag) {
37277
+ const response = await send({
37278
+ ...common,
37279
+ method: "GET",
37280
+ url: url2(ROUTES.policyBundle),
37281
+ ...etag === void 0 ? {} : { headers: { "if-none-match": etag } }
37282
+ });
37283
+ if (response.status === 304) {
37284
+ return { changed: false, etag: headerValue(response, "etag") ?? etag };
37285
+ }
37286
+ const bundle = parsed(PolicyBundle, okBody(response), ROUTES.policyBundle);
37287
+ return { changed: true, bundle, etag: headerValue(response, "etag") };
37288
+ },
37289
+ async whoami() {
37290
+ const response = await send({ ...common, method: "GET", url: url2(ROUTES.whoami) });
37291
+ return parsed(PluginWhoami, okBody(response), ROUTES.whoami);
37292
+ },
37293
+ async recordProjectEgress(request) {
37294
+ const validated = EgressIngestRequest.safeParse(request);
37295
+ if (!validated.success) throw new RemoteRequestInvalid(ROUTES.shares, validated.error);
37296
+ const response = await send({
37297
+ ...common,
37298
+ method: "POST",
37299
+ url: url2(ROUTES.shares),
37300
+ body: JSON.stringify(validated.data)
37301
+ });
37302
+ okBody(response);
37303
+ },
37304
+ async pollCommand() {
37305
+ const response = await send({ ...common, method: "GET", url: url2(ROUTES.commands) });
37306
+ if (response.status === 404) return null;
37307
+ return parsed(DeviceCommandPollResponse, okBody(response), ROUTES.commands).command;
37308
+ },
37309
+ async ackCommand(id, body) {
37310
+ const validated = DeviceCommandAckBody.safeParse(body);
37311
+ const route = ackRoute(id);
37312
+ if (!validated.success) throw new RemoteRequestInvalid(route, validated.error);
37313
+ const response = await send({
37314
+ ...common,
37315
+ method: "POST",
37316
+ url: url2(route),
37317
+ body: JSON.stringify(validated.data)
37318
+ });
37319
+ okBody(response);
37320
+ }
37321
+ };
37322
+ }
37323
+
36464
37324
  // ../../packages/plugin-runtime/src/attached/failure.ts
36465
37325
  function statusOf(err) {
36466
37326
  if (typeof err !== "object" || err === null || !("status" in err)) return null;
@@ -36479,12 +37339,27 @@ function classifyFailure(err) {
36479
37339
  }
36480
37340
  }
36481
37341
 
37342
+ // ../../packages/plugin-runtime/src/attached/with-timeout.ts
37343
+ var REQUEST_TIMEOUT_MS = 2e3;
37344
+ function withTimeout(promise2, ms) {
37345
+ let timer;
37346
+ const timeout = new Promise((_, reject) => {
37347
+ timer = setTimeout(() => {
37348
+ reject(new Error("attached gateway request timed out"));
37349
+ }, ms);
37350
+ });
37351
+ promise2.catch(() => void 0);
37352
+ return Promise.race([promise2, timeout]).finally(() => {
37353
+ clearTimeout(timer);
37354
+ });
37355
+ }
37356
+
36482
37357
  // ../../packages/plugin-runtime/src/attached/forward-drops.ts
36483
- import { readFileSync as readFileSync12 } from "fs";
36484
- import { join as join20 } from "path";
37358
+ import { readFileSync as readFileSync13 } from "fs";
37359
+ import { join as join21 } from "path";
36485
37360
  var FORWARD_DROPS_FILENAME = ATTACHED_FORWARD_DROPS_FILENAME;
36486
37361
  function forwardDropsPath(dataDir2) {
36487
- return join20(dataDir2, FORWARD_DROPS_FILENAME);
37362
+ return join21(dataDir2, FORWARD_DROPS_FILENAME);
36488
37363
  }
36489
37364
  function recordForwardDrops(dataDir2, count, nowMs) {
36490
37365
  if (count <= 0) return;
@@ -36502,7 +37377,7 @@ function recordForwardDrops(dataDir2, count, nowMs) {
36502
37377
  }
36503
37378
  function readForwardDrops(dataDir2) {
36504
37379
  try {
36505
- const parsed2 = JSON.parse(readFileSync12(forwardDropsPath(dataDir2), "utf8"));
37380
+ const parsed2 = JSON.parse(readFileSync13(forwardDropsPath(dataDir2), "utf8"));
36506
37381
  if (typeof parsed2 !== "object" || parsed2 === null) return null;
36507
37382
  const record2 = parsed2;
36508
37383
  if (typeof record2.droppedForwards !== "number" || !Number.isFinite(record2.droppedForwards)) {
@@ -36520,29 +37395,19 @@ function readForwardDrops(dataDir2) {
36520
37395
 
36521
37396
  // ../../packages/plugin-runtime/src/attached/forward-policy.ts
36522
37397
  import { randomUUID as randomUUID15 } from "crypto";
36523
- import { readFileSync as readFileSync13 } from "fs";
37398
+ import { readFileSync as readFileSync14 } from "fs";
36524
37399
  import { readFile, rename, writeFile } from "fs/promises";
36525
- import { join as join21 } from "path";
36526
-
36527
- // ../../packages/plugin-runtime/src/attached/with-timeout.ts
36528
- var REQUEST_TIMEOUT_MS = 2e3;
36529
- function withTimeout(promise2, ms) {
36530
- let timer;
36531
- const timeout = new Promise((_, reject) => {
36532
- timer = setTimeout(() => {
36533
- reject(new Error("attached gateway request timed out"));
36534
- }, ms);
36535
- });
36536
- promise2.catch(() => void 0);
36537
- return Promise.race([promise2, timeout]).finally(() => {
36538
- clearTimeout(timer);
36539
- });
36540
- }
36541
-
36542
- // ../../packages/plugin-runtime/src/attached/forward-policy.ts
37400
+ import { join as join22 } from "path";
36543
37401
  function isInvalidRequest(err) {
36544
37402
  return typeof err === "object" && err !== null && err.name === "RemoteRequestInvalid";
36545
37403
  }
37404
+ function isRouteAbsent(err) {
37405
+ return typeof err === "object" && err !== null && err.name === "RemoteRouteAbsent";
37406
+ }
37407
+ function isServerRejection(err) {
37408
+ const status = statusOf(err);
37409
+ return status !== null && status >= 400 && status <= 499 && status !== 401 && status !== 403 && status !== 404 && status !== 429;
37410
+ }
36546
37411
  var FORWARD_BUDGET_MS = 1500;
36547
37412
  var DECISION_PATH_BUDGET_MS = 800;
36548
37413
  var BREAKER_FAILURE_THRESHOLD = 3;
@@ -36570,7 +37435,7 @@ function parseBreakerState(raw, nowMs) {
36570
37435
  }
36571
37436
  function createForwardPolicy(deps) {
36572
37437
  const now = deps.now ?? (() => Date.now());
36573
- const file2 = join21(deps.dir, STATE_FILENAME);
37438
+ const file2 = join22(deps.dir, STATE_FILENAME);
36574
37439
  let state = null;
36575
37440
  let loading = null;
36576
37441
  async function readState() {
@@ -36610,6 +37475,20 @@ function createForwardPolicy(deps) {
36610
37475
  } catch {
36611
37476
  current = { ...CLOSED };
36612
37477
  }
37478
+ const restoreOpenedAtMs = (openedAtMs) => persist({
37479
+ consecutiveFailures: current.consecutiveFailures,
37480
+ openedAtMs,
37481
+ lastFailure: current.lastFailure
37482
+ });
37483
+ const recordFailure = (cause) => {
37484
+ const failures = current.consecutiveFailures + 1;
37485
+ const shouldOpen = current.openedAtMs !== null || failures >= BREAKER_FAILURE_THRESHOLD;
37486
+ return persist({
37487
+ consecutiveFailures: failures,
37488
+ openedAtMs: shouldOpen ? now() : null,
37489
+ lastFailure: cause
37490
+ });
37491
+ };
36613
37492
  const at = now();
36614
37493
  if (current.openedAtMs !== null) {
36615
37494
  if (at - current.openedAtMs < BREAKER_COOLDOWN_MS) {
@@ -36628,15 +37507,20 @@ function createForwardPolicy(deps) {
36628
37507
  }
36629
37508
  return { ok: true, value };
36630
37509
  } catch (err) {
36631
- if (isInvalidRequest(err)) return { ok: false, reason: "invalid-request" };
37510
+ if (isInvalidRequest(err)) {
37511
+ if (current.openedAtMs !== null) await restoreOpenedAtMs(current.openedAtMs);
37512
+ return { ok: false, reason: "invalid-request" };
37513
+ }
37514
+ if (isRouteAbsent(err)) {
37515
+ if (current.openedAtMs !== null) await restoreOpenedAtMs(null);
37516
+ return { ok: false, reason: "route-absent" };
37517
+ }
37518
+ if (isServerRejection(err)) {
37519
+ await recordFailure("unreachable");
37520
+ return { ok: false, reason: "rejected" };
37521
+ }
36632
37522
  const reason = classifyFailure(err);
36633
- const failures = current.consecutiveFailures + 1;
36634
- const shouldOpen = current.openedAtMs !== null || failures >= BREAKER_FAILURE_THRESHOLD;
36635
- await persist({
36636
- consecutiveFailures: failures,
36637
- openedAtMs: shouldOpen ? now() : null,
36638
- lastFailure: reason
36639
- });
37523
+ await recordFailure(reason);
36640
37524
  return { ok: false, reason };
36641
37525
  }
36642
37526
  }
@@ -36644,13 +37528,11 @@ function createForwardPolicy(deps) {
36644
37528
  }
36645
37529
 
36646
37530
  // ../../packages/plugin-runtime/src/attached/gateway.ts
36647
- var ACTION_STRENGTH = {
36648
- allow: 0,
36649
- log: 1,
36650
- warn: 2,
36651
- redact: 3,
36652
- block: 4
36653
- };
37531
+ function strongerOf(a, b) {
37532
+ if (a === null) return b;
37533
+ if (b === null) return a;
37534
+ return strongerAction(a, b);
37535
+ }
36654
37536
  function ruleCategoryMap(wireRules, localRules) {
36655
37537
  const map2 = /* @__PURE__ */ new Map();
36656
37538
  for (const rule of wireRules ?? []) map2.set(rule.id, rule.category);
@@ -36660,11 +37542,6 @@ function ruleCategoryMap(wireRules, localRules) {
36660
37542
  }
36661
37543
  return map2;
36662
37544
  }
36663
- function strongerOf(a, b) {
36664
- if (a === null) return b;
36665
- if (b === null) return a;
36666
- return ACTION_STRENGTH[a] >= ACTION_STRENGTH[b] ? a : b;
36667
- }
36668
37545
  function policyKey(policy) {
36669
37546
  return "ruleId" in policy.target ? `rule:${policy.target.ruleId}` : `category:${policy.target.category}`;
36670
37547
  }
@@ -36683,7 +37560,7 @@ function mergeRaiseOnly(localPolicies, remotePolicies, categoryByRuleId) {
36683
37560
  const floor = floorFor(policy, categoryByRuleId);
36684
37561
  remoteCategoryAction.set(
36685
37562
  policy.target.category,
36686
- floor !== null && ACTION_STRENGTH[policy.action] < ACTION_STRENGTH[floor] ? floor : policy.action
37563
+ floor !== null && !isActionAtLeast(policy.action, floor) ? floor : policy.action
36687
37564
  );
36688
37565
  }
36689
37566
  for (const policy of localPolicies) {
@@ -36700,7 +37577,7 @@ function mergeRaiseOnly(localPolicies, remotePolicies, categoryByRuleId) {
36700
37577
  }
36701
37578
  merged.set(
36702
37579
  key,
36703
- remoteFloor !== null && ACTION_STRENGTH[policy.action] < ACTION_STRENGTH[remoteFloor] ? { ...policy, action: remoteFloor } : policy
37580
+ remoteFloor !== null && !isActionAtLeast(policy.action, remoteFloor) ? { ...policy, action: remoteFloor } : policy
36704
37581
  );
36705
37582
  }
36706
37583
  const localCategoryAction = /* @__PURE__ */ new Map();
@@ -36720,13 +37597,13 @@ function mergeRaiseOnly(localPolicies, remotePolicies, categoryByRuleId) {
36720
37597
  if (category !== void 0) localFloor = localCategoryAction.get(category) ?? null;
36721
37598
  }
36722
37599
  const effectiveFloor = strongerOf(floor, localFloor);
36723
- const clamped = effectiveFloor !== null && ACTION_STRENGTH[policy.action] < ACTION_STRENGTH[effectiveFloor] ? { ...policy, action: effectiveFloor } : policy;
37600
+ const clamped = effectiveFloor !== null && !isActionAtLeast(policy.action, effectiveFloor) ? { ...policy, action: effectiveFloor } : policy;
36724
37601
  const existing = merged.get(key);
36725
37602
  if (existing === void 0) {
36726
37603
  merged.set(key, clamped);
36727
37604
  continue;
36728
37605
  }
36729
- if (ACTION_STRENGTH[clamped.action] > ACTION_STRENGTH[existing.action]) {
37606
+ if (actionRank(clamped.action) > actionRank(existing.action)) {
36730
37607
  merged.set(key, clamped);
36731
37608
  }
36732
37609
  }
@@ -36759,6 +37636,8 @@ var AttachedDataGateway = class {
36759
37636
  );
36760
37637
  if (forwarded.ok && forwarded.value.accepted + forwarded.value.duplicates > 0) {
36761
37638
  this.deps.local.markCaptureDelivered(record2.event, Date.now());
37639
+ } else {
37640
+ this.deps.local.markCaptureOwed(record2.event);
36762
37641
  }
36763
37642
  }
36764
37643
  async ensureInventory(ctx) {
@@ -36795,9 +37674,10 @@ var AttachedDataGateway = class {
36795
37674
  // a retried tool_call, exactly this path — can never stomp a populated row.
36796
37675
  async recordAuditEvent(event) {
36797
37676
  await this.deps.local.recordAuditEvent(event);
36798
- await this.deps.forward.run(
37677
+ const forwarded = await this.deps.forward.run(
36799
37678
  () => this.deps.client.recordAuditEvent(reKeyForForward(event, this.remoteInventory))
36800
37679
  );
37680
+ if (forwarded.ok) this.deps.local.markAuditEventsDelivered([event], Date.now());
36801
37681
  }
36802
37682
  // Attached `llm_call` is written locally by the inner gateway, then routed to
36803
37683
  // the control plane through the existing `recordAuditEvent` ingest (no dedicated
@@ -36806,44 +37686,170 @@ var AttachedDataGateway = class {
36806
37686
  // which would write the event to the local store a second time.
36807
37687
  async recordLlmCall(input2) {
36808
37688
  await this.deps.local.recordLlmCall(input2);
36809
- await this.deps.forward.run(
36810
- () => this.deps.client.recordAuditEvent(
36811
- reKeyForForward(llmAuditEvent(input2), this.remoteInventory)
36812
- )
37689
+ const event = llmAuditEvent(input2);
37690
+ const forwarded = await this.deps.forward.run(
37691
+ () => this.deps.client.recordAuditEvent(reKeyForForward(event, this.remoteInventory))
36813
37692
  );
37693
+ if (forwarded.ok) this.deps.local.markAuditEventsDelivered([event], Date.now());
36814
37694
  }
36815
37695
  /**
36816
- * Forward one batch, item by item, under ONE aggregate deadline.
37696
+ * Forward one batch in CHUNKS of AUDIT_EVENT_BATCH_MAX, under ONE aggregate deadline.
37697
+ *
37698
+ * This used to send one HTTP request per event, which is what made the batch
37699
+ * budget bite: at 200ms round-trip a 3s budget admitted ~15 events and threw
37700
+ * away everything after them. The same rows now cross 50 at a time over
37701
+ * `POST /v1/audit-events/batch` — the route the attach-time drain has always
37702
+ * used — so the same budget admits ~750. The wire cap is the server's own
37703
+ * constant, sized against server cost, and the client REFUSES a longer array
37704
+ * client-side, so the chunking here is not a convention.
37705
+ *
37706
+ * Still serial, and still for the original reason: firing N requests at once
37707
+ * would trade a latency problem for a burst the plane's per-key rate limiting
37708
+ * answers with the refusals the breaker then counts. Fewer, fuller requests is
37709
+ * the fix; more concurrent ones is not.
37710
+ *
37711
+ * When the deadline passes the remainder is dropped rather than sent: the
37712
+ * local write has already succeeded, so every caller has a correct result to
37713
+ * return. What is dropped is COUNTED, everywhere it can happen — this path
37714
+ * returns BEFORE `ForwardPolicy.run` is reached, so without the tally in
37715
+ * `forward-drops.ts` a slow-but-answering plane produces no failures, keeps
37716
+ * the breaker closed, renders a healthy block, and discards the tail of every
37717
+ * batch indefinitely. The SAME tally also covers a single that fails inside
37718
+ * the per-item retry below — the breaker opening mid-retry is a failure the
37719
+ * breaker's own state DOES capture, but the events still in this chunk once
37720
+ * that happens are neither delivered nor otherwise counted anywhere, which is
37721
+ * the same invisibility with a different cause.
37722
+ *
37723
+ * `ok` ALONE IS NOT DELIVERY, the same rule `recordCapture` states for the
37724
+ * single-event ack and at fifty times the blast radius here:
37725
+ * `AuditEventBatchAck.accepted` is an aggregate count the wire contract does
37726
+ * not tie to the chunk's own length, so a 2xx answering `{accepted: 30}` for
37727
+ * fifty events is well-formed. Trusting `ok` alone would stamp all fifty as
37728
+ * delivered and never re-offer the twenty the plane did not take. So success
37729
+ * is checked against `chunk.length`; anything short of it falls into the same
37730
+ * per-item pass as a refused chunk, which is the only way to recover the
37731
+ * rows that did not land, since the ack carries no per-row verdict to
37732
+ * resend by.
37733
+ *
37734
+ * That fallback ASSUMES a re-send of an already-landed row is a harmless
37735
+ * no-op rather than a second cost — an assumption this file cannot verify.
37736
+ * `AuditEventBatchAck` carries only `accepted`, unlike its sibling
37737
+ * `IngestAck` (`accepted` + `duplicates`, with `accepted + duplicates ==`
37738
+ * the batch size as the invariant `recordCapture` reads), so whether a
37739
+ * duplicate counts toward THIS route's `accepted` is not expressed
37740
+ * anywhere in this repo. If it follows its sibling's convention and does
37741
+ * NOT, a chunk containing even one already-delivered row — the ordinary
37742
+ * consequence of a lost stamp, which this file already treats as cheap —
37743
+ * answers short forever and enters the per-item pass on every pass it is
37744
+ * offered again. The cost of that is bounded rather than silent: the
37745
+ * pass converges (every row lands and stamps), so it is one wasted round
37746
+ * of singles rather than a stall, and it errs toward an extra resend
37747
+ * rather than toward the lost row the alternative risks.
36817
37748
  *
36818
- * Per-item budgets bound each request and nothing bounded their sum — see
36819
- * BATCH_FORWARD_BUDGET_MS. When the deadline passes the remainder is dropped
36820
- * rather than sent: the local write has already succeeded, so every caller
36821
- * has a correct result to return, and a drop is the outcome this path is
36822
- * built to accept (G8) where a blown hook timeout is not.
37749
+ * BATCH-ATOMIC SETTLEMENT is otherwise the rule: the receiver wraps a chunk in
37750
+ * one transaction, so a full 2xx settles every event in it and a non-2xx
37751
+ * settles none — which is why the whole chunk is stamped together on a FULL
37752
+ * accept and none of it otherwise. THREE reasons do not deserve whole-chunk
37753
+ * treatment, alongside a short accept, and all are re-sent one event at a
37754
+ * time:
36823
37755
  *
36824
- * Serial rather than concurrent on purpose. Firing N requests at once would
36825
- * trade a latency problem for a burst the plane's own per-key rate limiting
36826
- * would answer with the refusals the breaker then counts.
37756
+ * `invalid-request` a chunk the client refused to send at all. One malformed
37757
+ * event would otherwise cost the 49 good ones beside it —
37758
+ * a new way to lose data introduced by the very change
37759
+ * meant to stop losing it.
37760
+ * `route-absent` a deployment that predates the batch route. The
37761
+ * single-event route is the one it serves, and re-sending
37762
+ * here rather than inside the client is what gives each
37763
+ * request its own budget instead of 50 inside one.
37764
+ * `rejected` the deployment's SERVER-side twin of `invalid-request` —
37765
+ * a 4xx body refusal from schema drift on the other side
37766
+ * of the wire. Settlement is batch-atomic on this reason
37767
+ * exactly as on the others, so leaving it out would cost
37768
+ * the whole chunk for one event the DEPLOYMENT considers
37769
+ * malformed, where the per-item form cost only that one.
36827
37770
  *
36828
- * WHAT IS DROPPED IS COUNTED. Every other forward failure ends in
36829
- * `ForwardPolicy.run`'s catch and moves the breaker's file, which is what
36830
- * lets status call the forward unhealthy; this path returns BEFORE `run` is
36831
- * reached, so without the tally in `forward-drops.ts` a slow-but-answering
36832
- * plane produces no failures, keeps the breaker closed, renders a healthy
36833
- * block, and discards the tail of every batch indefinitely.
37771
+ * Every other reason (breaker-open, a refusal, a timeout) applies to the whole
37772
+ * chunk, and re-sending it item by item would just spend the budget failing 50
37773
+ * more times — for those, the blast radius stays exactly what it was before
37774
+ * batching.
36834
37775
  */
36835
37776
  async forwardBatch(inputs, toEvent) {
36836
37777
  const deadline = Date.now() + BATCH_FORWARD_BUDGET_MS;
36837
- for (let i = 0; i < inputs.length; i += 1) {
36838
- const now = Date.now();
36839
- if (now >= deadline) {
36840
- recordForwardDrops(this.deps.dataDir, inputs.length - i, now);
36841
- return;
37778
+ const delivered = [];
37779
+ try {
37780
+ for (let i = 0; i < inputs.length; i += AUDIT_EVENT_BATCH_MAX) {
37781
+ const now = Date.now();
37782
+ if (now >= deadline) {
37783
+ recordForwardDrops(this.deps.dataDir, inputs.length - i, now);
37784
+ return;
37785
+ }
37786
+ const chunk = inputs.slice(i, i + AUDIT_EVENT_BATCH_MAX).map((input2) => toEvent(input2));
37787
+ const forwarded = await this.deps.forward.run(
37788
+ () => this.deps.client.recordAuditEvents(
37789
+ chunk.map((event) => reKeyForForward(event, this.remoteInventory))
37790
+ )
37791
+ );
37792
+ if (forwarded.ok) {
37793
+ if (forwarded.value.accepted === chunk.length) {
37794
+ delivered.push(...chunk);
37795
+ continue;
37796
+ }
37797
+ } else if (
37798
+ // THREE reasons are worth a second pass, one at a time, and they are
37799
+ // the three settled BEFORE the control plane refused anything, or
37800
+ // (for `rejected`) refused the BODY rather than the connection.
37801
+ //
37802
+ // `invalid-request` — the CLIENT refused the body before any request
37803
+ // went out: a defect in one event, not an outage. Re-sending singly
37804
+ // isolates the bad one instead of charging its 49 neighbours for it.
37805
+ //
37806
+ // `route-absent` — the deployment predates the batch route and serves
37807
+ // only the single-event one. The retry IS the compatibility path, and
37808
+ // it has to live HERE rather than inside the client: each single gets
37809
+ // its own FORWARD_BUDGET_MS through `run`, whereas the client's own
37810
+ // fallback would spend 50 sequential round trips inside the ONE
37811
+ // budget wrapping this call — turning a working older deployment into
37812
+ // a timeout, three of those into an open breaker, and every row into
37813
+ // a silent drop while the status surface called an answering
37814
+ // deployment down.
37815
+ //
37816
+ // `rejected` — the deployment's own 4xx refusal of the body, the
37817
+ // server-side twin of `invalid-request`: isolating it the same way
37818
+ // costs one event instead of the whole chunk for a defect the
37819
+ // deployment considers local to one row.
37820
+ //
37821
+ // Every other reason (breaker-open, a refusal, a timeout) applies to
37822
+ // the whole chunk; re-sending it item by item would just spend the
37823
+ // budget failing 50 more times.
37824
+ forwarded.reason !== "invalid-request" && forwarded.reason !== "route-absent" && forwarded.reason !== "rejected"
37825
+ ) {
37826
+ continue;
37827
+ }
37828
+ for (const [j, event] of chunk.entries()) {
37829
+ const at = Date.now();
37830
+ if (at >= deadline) {
37831
+ recordForwardDrops(this.deps.dataDir, inputs.length - i - j, at);
37832
+ return;
37833
+ }
37834
+ const single = await this.deps.forward.run(
37835
+ () => this.deps.client.recordAuditEvent(reKeyForForward(event, this.remoteInventory))
37836
+ );
37837
+ if (single.ok) {
37838
+ delivered.push(event);
37839
+ continue;
37840
+ }
37841
+ if (single.reason === "breaker-open") {
37842
+ recordForwardDrops(this.deps.dataDir, inputs.length - i - j, at);
37843
+ return;
37844
+ }
37845
+ recordForwardDrops(this.deps.dataDir, 1, at);
37846
+ }
37847
+ }
37848
+ } finally {
37849
+ try {
37850
+ this.deps.local.markAuditEventsDelivered(delivered, Date.now());
37851
+ } catch {
36842
37852
  }
36843
- const input2 = inputs[i];
36844
- await this.deps.forward.run(
36845
- () => this.deps.client.recordAuditEvent(reKeyForForward(toEvent(input2), this.remoteInventory))
36846
- );
36847
37853
  }
36848
37854
  }
36849
37855
  // Delegated as a BATCH rather than looped over recordLlmCall: the inner
@@ -36886,9 +37892,10 @@ var AttachedDataGateway = class {
36886
37892
  // local store.
36887
37893
  async recordConfigScan(record2) {
36888
37894
  await this.deps.local.recordConfigScan(record2);
36889
- await this.deps.forward.run(
37895
+ const forwarded = await this.deps.forward.run(
36890
37896
  () => this.deps.client.recordAuditEvent(reKeyForForward(record2.scanEvent, this.remoteInventory))
36891
37897
  );
37898
+ if (forwarded.ok) this.deps.local.markAuditEventsDelivered([record2.scanEvent], Date.now());
36892
37899
  }
36893
37900
  async recordBlockedDetection(entry) {
36894
37901
  return this.deps.local.recordBlockedDetection(entry);
@@ -37022,6 +38029,18 @@ var AttachedDataGateway = class {
37022
38029
  // exactly what it did, leaving the whole control inert on every device
37023
38030
  // while every test around it stayed green.
37024
38031
  prohibitedModels: cached2.prohibitedModels
38032
+ // ALSO HONOURED FROM THE CACHE, and not a bundle field at all: each
38033
+ // merged policy's own `provenance`. `mergeRaiseOnly` spreads the policies
38034
+ // it emits, so an 'authored' policy arriving from the control plane
38035
+ // keeps that marker even where the clamp rebuilds it with a stronger
38036
+ // action. The device reads it in exactly one direction — the rules such a
38037
+ // policy targets are not locally re-assignable — so it sits on the
38038
+ // `prohibitedModels` side of the line for the same reason that field
38039
+ // does: it can only ever ADD a refusal, never relax one, and an unsigned
38040
+ // cache therefore has no relaxation to grant by carrying it. Dropping it
38041
+ // would be the silent failure rather than the safe one — the action would
38042
+ // still be enforced while the local override the organization authored
38043
+ // away quietly came back.
37025
38044
  // `rulesComplete` is a STANDALONE-ONLY signal (the user's local installed
37026
38045
  // snapshot) and is taken from the LOCAL bundle only — never from the wire
37027
38046
  // or the on-disk cache. Honoring a cached one would hand the control plane, or
@@ -37061,10 +38080,10 @@ var AttachedDataGateway = class {
37061
38080
  //
37062
38081
  // Implementing these is what actually closes the skipped-local-maintenance
37063
38082
  // gap: the OSS structural guard `hasLocalStoreMaintenance()` is satisfied by
37064
- // any object carrying all five, so the composite qualifies and SessionStart
38083
+ // any object carrying them all, so the composite qualifies and SessionStart
37065
38084
  // runs maintenance on the device's real store.
37066
38085
  //
37067
- // ⚠ Three of the six are SYNCHRONOUS and must stay that way. `handle-session-start`
38086
+ // ⚠ Several of them are SYNCHRONOUS and must stay that way. `handle-session-start`
37068
38087
  // calls `capWarnEraEnforcement` without `await` and uses `staleBinaryNotice`'s
37069
38088
  // return value directly; declaring them `async` here would hand those call
37070
38089
  // sites a Promise and silently break both.
@@ -37087,9 +38106,15 @@ var AttachedDataGateway = class {
37087
38106
  // Delegated like the rest, and SYNCHRONOUS for the reason the note above
37088
38107
  // gives: `recordCapture` calls it after the forward has already settled, on a
37089
38108
  // path that has nothing left to await.
38109
+ markCaptureOwed(event) {
38110
+ this.deps.local.markCaptureOwed(event);
38111
+ }
37090
38112
  markCaptureDelivered(event, atMs) {
37091
38113
  this.deps.local.markCaptureDelivered(event, atMs);
37092
38114
  }
38115
+ markAuditEventsDelivered(events, atMs) {
38116
+ this.deps.local.markAuditEventsDelivered(events, atMs);
38117
+ }
37093
38118
  };
37094
38119
  function reKeyForForward(event, remote) {
37095
38120
  if (remote === null) {
@@ -37132,281 +38157,17 @@ function toolAuditEvent(input2) {
37132
38157
  }
37133
38158
 
37134
38159
  // ../../packages/plugin-runtime/src/attached/history-state.ts
37135
- import { readFileSync as readFileSync14 } from "fs";
37136
- import { join as join22 } from "path";
38160
+ import { readFileSync as readFileSync15 } from "fs";
38161
+ import { join as join23 } from "path";
37137
38162
 
37138
38163
  // ../../packages/plugin-runtime/src/attached/history-sync.ts
37139
38164
  import { createHash as createHash6 } from "crypto";
37140
38165
  import { hostname as hostname5 } from "os";
37141
38166
 
37142
- // ../../packages/remote/src/http.ts
37143
- import { request as httpRequest } from "http";
37144
- import { request as httpsRequest } from "https";
37145
- var DEFAULT_TIMEOUT_MS = 1e4;
37146
- var MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
37147
- var RemoteRequestError = class extends Error {
37148
- constructor(status) {
37149
- super(`control-plane request failed with status ${String(status)}`);
37150
- this.status = status;
37151
- this.name = "RemoteRequestError";
37152
- }
37153
- status;
37154
- };
37155
- var RemoteRequestInvalid = class extends Error {
37156
- constructor(route, cause) {
37157
- super(`refusing to send a malformed body to ${route}`);
37158
- this.cause = cause;
37159
- this.name = "RemoteRequestInvalid";
37160
- }
37161
- cause;
37162
- };
37163
- var RemoteResponseInvalid = class extends Error {
37164
- constructor(route, detail) {
37165
- super(`control plane answered ${route} with ${detail}`);
37166
- this.name = "RemoteResponseInvalid";
37167
- }
37168
- };
37169
- var RemoteTransportError = class extends Error {
37170
- /**
37171
- * The status the peer sent, when headers arrived and only the BODY was
37172
- * refused.
37173
- *
37174
- * Undefined for the ordinary case this class was written for — no answer at
37175
- * all. It exists because two paths reject after a status has already been
37176
- * delivered: an oversized body and an aborted response. Discarding it there
37177
- * reported a deployment answering 401 with a verbose body as a network
37178
- * outage, which sends the reader to look at their network instead of their
37179
- * credential.
37180
- */
37181
- constructor(reason, status) {
37182
- super(`control-plane request did not complete: ${reason}`);
37183
- this.status = status;
37184
- this.name = "RemoteTransportError";
37185
- }
37186
- status;
37187
- };
37188
- async function send(options) {
37189
- const url2 = new URL(options.url);
37190
- const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
37191
- const send_ = url2.protocol === "http:" ? httpRequest : httpsRequest;
37192
- const requestOptions = {
37193
- method: options.method,
37194
- headers: {
37195
- // CALLER HEADERS FIRST, so this module's own are not overridable. Spread
37196
- // last they win, and two of the values below are ones no caller may
37197
- // replace: `x-api-key` is the credential, and `content-length` is the
37198
- // byte count that stops a multi-byte body being truncated by the
37199
- // receiver. `SendOptions.headers` is a free-form record on an exported
37200
- // function, so "no caller does that today" is not the guarantee to rely
37201
- // on. The one header any caller actually passes — `if-none-match` on the
37202
- // conditional GET — is untouched by this order.
37203
- ...options.headers,
37204
- // The credential. One header, matching what the deployment authenticates
37205
- // on; a second copy in an `Authorization` header would be one more place
37206
- // it can be logged by an intermediary for no gain.
37207
- //
37208
- // Spread conditionally rather than assigned as `undefined`: Node's header
37209
- // handling and `content-length` bookkeeping treat a present-but-undefined
37210
- // key differently from an absent one, and "the header is not there" is
37211
- // the property the attach flow needs.
37212
- ...options.apiKey === void 0 ? {} : { "x-api-key": options.apiKey },
37213
- accept: "application/json",
37214
- ...options.body === void 0 ? {} : {
37215
- "content-type": "application/json",
37216
- // Byte length, not string length: a multi-byte body sent with a
37217
- // character count is truncated by the receiver.
37218
- "content-length": String(Buffer.byteLength(options.body))
37219
- }
37220
- }
37221
- };
37222
- return new Promise((resolve2, reject) => {
37223
- let settled = false;
37224
- const fail = (reason, status) => {
37225
- if (settled) return;
37226
- settled = true;
37227
- reject(new RemoteTransportError(reason, status));
37228
- };
37229
- const req = send_(url2, requestOptions, (res) => {
37230
- const chunks = [];
37231
- let size = 0;
37232
- res.on("data", (chunk) => {
37233
- size += chunk.length;
37234
- if (size > MAX_RESPONSE_BYTES) {
37235
- fail(`response exceeded ${String(MAX_RESPONSE_BYTES)} bytes`, res.statusCode);
37236
- res.destroy();
37237
- req.destroy();
37238
- return;
37239
- }
37240
- chunks.push(chunk);
37241
- });
37242
- res.on("aborted", () => {
37243
- fail("the response was aborted", res.statusCode);
37244
- });
37245
- res.on("end", () => {
37246
- if (settled) return;
37247
- settled = true;
37248
- resolve2({
37249
- status: res.statusCode ?? 0,
37250
- headers: res.headers,
37251
- body: Buffer.concat(chunks).toString("utf8")
37252
- });
37253
- });
37254
- });
37255
- const deadline = setTimeout(() => {
37256
- fail(`no response within ${String(timeoutMs)}ms`);
37257
- req.destroy();
37258
- }, timeoutMs);
37259
- deadline.unref();
37260
- req.on("upgrade", (_res, socket) => {
37261
- fail("the deployment answered with a protocol upgrade");
37262
- socket.destroy();
37263
- });
37264
- req.on("close", () => {
37265
- fail("the connection closed before a response was read");
37266
- clearTimeout(deadline);
37267
- });
37268
- req.on("error", (err) => {
37269
- fail(err.message);
37270
- });
37271
- if (options.body !== void 0) req.write(options.body);
37272
- req.end();
37273
- });
37274
- }
37275
-
37276
- // ../../packages/remote/src/client.ts
37277
- var ROUTES = {
37278
- events: "/v1/events",
37279
- auditEvents: "/v1/audit-events",
37280
- auditEventsBatch: "/v1/audit-events/batch",
37281
- inventory: "/v1/inventory",
37282
- storePosture: "/v1/store-posture",
37283
- policyBundle: "/v1/policy-bundle",
37284
- whoami: "/v1/plugin/whoami",
37285
- shares: "/v1/shares"
37286
- };
37287
- function headerValue(response, name) {
37288
- const raw = response.headers[name];
37289
- if (raw === void 0) return void 0;
37290
- return Array.isArray(raw) ? raw[0] : raw;
37291
- }
37292
- function okBody(response) {
37293
- if (response.status < 200 || response.status >= 300) {
37294
- throw new RemoteRequestError(response.status);
37295
- }
37296
- return response.body;
37297
- }
37298
- function parsed(schema, body, route) {
37299
- let json2;
37300
- try {
37301
- json2 = JSON.parse(body);
37302
- } catch {
37303
- throw new RemoteResponseInvalid(route, "a body that is not JSON");
37304
- }
37305
- const result = schema.safeParse(json2);
37306
- if (!result.success) {
37307
- throw new RemoteResponseInvalid(route, "a body this client cannot read");
37308
- }
37309
- return result.data;
37310
- }
37311
- function withoutTrailingSlashes(endpoint) {
37312
- let end = endpoint.length;
37313
- while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH) end -= 1;
37314
- return endpoint.slice(0, end);
37315
- }
37316
- var SLASH = "/".charCodeAt(0);
37317
- function createRemoteClient(options) {
37318
- const base = withoutTrailingSlashes(options.endpoint);
37319
- const url2 = (route) => `${base}${route}`;
37320
- const common = { apiKey: options.apiKey, timeoutMs: options.timeoutMs };
37321
- const sendOne = async (event) => {
37322
- const validated = RecordAuditEventRequest.safeParse(event);
37323
- if (!validated.success) throw new RemoteRequestInvalid(ROUTES.auditEvents, validated.error);
37324
- const response = await send({
37325
- ...common,
37326
- method: "POST",
37327
- url: url2(ROUTES.auditEvents),
37328
- body: JSON.stringify(validated.data)
37329
- });
37330
- okBody(response);
37331
- };
37332
- return {
37333
- async ingestEvents(batch) {
37334
- const response = await send({
37335
- ...common,
37336
- method: "POST",
37337
- url: url2(ROUTES.events),
37338
- body: JSON.stringify(batch)
37339
- });
37340
- return parsed(IngestAck, okBody(response), ROUTES.events);
37341
- },
37342
- async ingestInventory(context) {
37343
- const response = await send({
37344
- ...common,
37345
- method: "POST",
37346
- url: url2(ROUTES.inventory),
37347
- body: JSON.stringify(context)
37348
- });
37349
- return parsed(ResolvedInventory, okBody(response), ROUTES.inventory);
37350
- },
37351
- async recordAuditEvent(event) {
37352
- await sendOne(event);
37353
- },
37354
- async recordAuditEvents(events) {
37355
- const validated = RecordAuditEventBatch.safeParse({ events });
37356
- if (!validated.success) {
37357
- throw new RemoteRequestInvalid(ROUTES.auditEventsBatch, validated.error);
37358
- }
37359
- const response = await send({
37360
- ...common,
37361
- method: "POST",
37362
- url: url2(ROUTES.auditEventsBatch),
37363
- body: JSON.stringify(validated.data)
37364
- });
37365
- if (response.status === 404) {
37366
- for (const event of validated.data.events) await sendOne(event);
37367
- return { accepted: validated.data.events.length };
37368
- }
37369
- return parsed(AuditEventBatchAck, okBody(response), ROUTES.auditEventsBatch);
37370
- },
37371
- async reportStorePosture(snapshot) {
37372
- const response = await send({
37373
- ...common,
37374
- method: "POST",
37375
- url: url2(ROUTES.storePosture),
37376
- body: JSON.stringify(snapshot)
37377
- });
37378
- okBody(response);
37379
- },
37380
- async getPolicyBundle(etag) {
37381
- const response = await send({
37382
- ...common,
37383
- method: "GET",
37384
- url: url2(ROUTES.policyBundle),
37385
- ...etag === void 0 ? {} : { headers: { "if-none-match": etag } }
37386
- });
37387
- if (response.status === 304) {
37388
- return { changed: false, etag: headerValue(response, "etag") ?? etag };
37389
- }
37390
- const bundle = parsed(PolicyBundle, okBody(response), ROUTES.policyBundle);
37391
- return { changed: true, bundle, etag: headerValue(response, "etag") };
37392
- },
37393
- async whoami() {
37394
- const response = await send({ ...common, method: "GET", url: url2(ROUTES.whoami) });
37395
- return parsed(PluginWhoami, okBody(response), ROUTES.whoami);
37396
- },
37397
- async recordProjectEgress(request) {
37398
- const validated = EgressIngestRequest.safeParse(request);
37399
- if (!validated.success) throw new RemoteRequestInvalid(ROUTES.shares, validated.error);
37400
- const response = await send({
37401
- ...common,
37402
- method: "POST",
37403
- url: url2(ROUTES.shares),
37404
- body: JSON.stringify(validated.data)
37405
- });
37406
- okBody(response);
37407
- }
37408
- };
37409
- }
38167
+ // ../../packages/plugin-runtime/src/attached/capture-rebuild.ts
38168
+ var CORRELATION_ID = EventMetadata.shape.correlationId;
38169
+ var TRACE_ID = EventMetadata.shape.traceId;
38170
+ var EXCEPTION_ID = EventMetadata.shape.exceptionIds.unwrap().element;
37410
38171
 
37411
38172
  // ../../packages/plugin-runtime/src/attached/history-sync-trigger.ts
37412
38173
  import { spawn } from "child_process";
@@ -37414,7 +38175,7 @@ import { fileURLToPath as fileURLToPath2 } from "url";
37414
38175
  var HISTORY_SYNC_THROTTLE_MS = 5 * 60 * 1e3;
37415
38176
 
37416
38177
  // ../../packages/plugin-runtime/src/attached/plugin-block.ts
37417
- import { readFileSync as readFileSync15 } from "fs";
38178
+ import { readFileSync as readFileSync16 } from "fs";
37418
38179
  function createPluginBlock(build, policyStore) {
37419
38180
  return async () => {
37420
38181
  const cached2 = await policyStore.read();
@@ -37433,7 +38194,7 @@ function createPluginBlock(build, policyStore) {
37433
38194
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
37434
38195
  import { randomUUID as randomUUID16 } from "crypto";
37435
38196
  import { readFile as readFile2, rm, writeFile as writeFile2 } from "fs/promises";
37436
- import { join as join23 } from "path";
38197
+ import { join as join24 } from "path";
37437
38198
 
37438
38199
  // ../../packages/plugin-runtime/src/attached/atomic-publish.ts
37439
38200
  import { rename as rename2 } from "fs/promises";
@@ -37457,7 +38218,7 @@ async function publishByRename(tmp, file2, move = rename2) {
37457
38218
 
37458
38219
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
37459
38220
  function createPolicyStore(dir = dataDir()) {
37460
- const file2 = join23(dir, "policy-cache.json");
38221
+ const file2 = join24(dir, "policy-cache.json");
37461
38222
  async function read() {
37462
38223
  try {
37463
38224
  const raw = await readFile2(file2, "utf8");
@@ -37466,22 +38227,32 @@ function createPolicyStore(dir = dataDir()) {
37466
38227
  const record2 = parsed2;
37467
38228
  const bundle = PolicyBundle.parse(record2.bundle);
37468
38229
  const fetchedAtMs = typeof record2.fetchedAtMs === "number" ? record2.fetchedAtMs : 0;
37469
- const etag = typeof record2.etag === "string" ? record2.etag : void 0;
38230
+ const stored = typeof record2.etag === "string" ? record2.etag : void 0;
38231
+ const replayable = record2.shapeId === POLICY_BUNDLE_SHAPE_ID || knowsMoreThanThisBuild(record2.shapeId);
38232
+ const etag = replayable ? stored : void 0;
37470
38233
  return { bundle, fetchedAtMs, ...etag === void 0 ? {} : { etag } };
37471
38234
  } catch {
37472
38235
  return null;
37473
38236
  }
37474
38237
  }
37475
- async function write(bundle, etag) {
37476
- await ensureDataDir(dir);
37477
- const stored = {
37478
- bundle,
37479
- fetchedAtMs: Date.now(),
37480
- ...etag === void 0 ? {} : { etag }
37481
- };
38238
+ function knowsMoreThanThisBuild(shapeId) {
38239
+ if (typeof shapeId !== "string" || shapeId === "") return false;
38240
+ const theirs = new Set(shapeId.split(","));
38241
+ const ours = new Set(POLICY_BUNDLE_SHAPE_ID.split(","));
38242
+ return theirs.size > ours.size && [...ours].every((key) => theirs.has(key));
38243
+ }
38244
+ async function priorRecord() {
38245
+ try {
38246
+ const parsed2 = JSON.parse(await readFile2(file2, "utf8"));
38247
+ return typeof parsed2 === "object" && parsed2 !== null ? parsed2 : null;
38248
+ } catch {
38249
+ return null;
38250
+ }
38251
+ }
38252
+ async function publishRecord(record2) {
37482
38253
  const tmp = `${file2}.${randomUUID16()}.tmp`;
37483
38254
  try {
37484
- await writeFile2(tmp, JSON.stringify(stored), {
38255
+ await writeFile2(tmp, JSON.stringify(record2), {
37485
38256
  encoding: "utf8",
37486
38257
  mode: DATA_FILE_MODE,
37487
38258
  flag: "wx"
@@ -37492,6 +38263,27 @@ function createPolicyStore(dir = dataDir()) {
37492
38263
  throw err;
37493
38264
  }
37494
38265
  }
38266
+ async function write(bundle, etag) {
38267
+ await ensureDataDir(dir);
38268
+ const prior = await priorRecord();
38269
+ const priorVersion = prior?.bundle?.version;
38270
+ if (prior !== null && knowsMoreThanThisBuild(prior.shapeId) && priorVersion === bundle.version) {
38271
+ await publishRecord({
38272
+ ...prior,
38273
+ fetchedAtMs: Date.now()
38274
+ });
38275
+ return;
38276
+ }
38277
+ await publishRecord({
38278
+ bundle,
38279
+ fetchedAtMs: Date.now(),
38280
+ // Stamped on EVERY write, the 304 arm's included: that arm hands back the
38281
+ // bundle it already holds, and the point of the stamp is to describe the
38282
+ // build that last narrowed those bytes, which is this one.
38283
+ shapeId: POLICY_BUNDLE_SHAPE_ID,
38284
+ ...etag === void 0 ? {} : { etag }
38285
+ });
38286
+ }
37495
38287
  return { read, write, file: file2 };
37496
38288
  }
37497
38289
 
@@ -37657,11 +38449,11 @@ function readStorePosture(dbPath2) {
37657
38449
  // ../../packages/plugin-runtime/src/attached/posture-store.ts
37658
38450
  import { randomUUID as randomUUID17 } from "crypto";
37659
38451
  import { readFile as readFile3, rm as rm2, writeFile as writeFile3 } from "fs/promises";
37660
- import { join as join24 } from "path";
38452
+ import { join as join25 } from "path";
37661
38453
  var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
37662
38454
  function createPostureStore(dir = settingsDir(), legacyDir) {
37663
- const file2 = join24(dir, "posture-state.json");
37664
- const legacyFile = legacyDir === void 0 ? null : join24(legacyDir, "posture-state.json");
38455
+ const file2 = join25(dir, "posture-state.json");
38456
+ const legacyFile = legacyDir === void 0 ? null : join25(legacyDir, "posture-state.json");
37665
38457
  async function persist(state) {
37666
38458
  await ensureDataDir(dir);
37667
38459
  const tmp = `${file2}.${randomUUID17()}.tmp`;
@@ -37729,8 +38521,8 @@ function createPostureStore(dir = settingsDir(), legacyDir) {
37729
38521
  }
37730
38522
 
37731
38523
  // ../../packages/plugin-runtime/src/attached/sync-state.ts
37732
- import { readFileSync as readFileSync16 } from "fs";
37733
- import { join as join25 } from "path";
38524
+ import { readFileSync as readFileSync17 } from "fs";
38525
+ import { join as join26 } from "path";
37734
38526
 
37735
38527
  // ../../packages/plugin-runtime/src/attached/status.ts
37736
38528
  var REFUSAL_LINES = {
@@ -38048,9 +38840,21 @@ var StandaloneDataGateway = class {
38048
38840
  // for the whole of it, so a member that threw would make that answer a lie
38049
38841
  // the moment a composite delegated to it. A store-level no-op is the honest
38050
38842
  // shape — a standalone machine has nothing delivered to record.
38843
+ markCaptureOwed(event) {
38844
+ this.db.markCaptureOwed(event);
38845
+ }
38051
38846
  markCaptureDelivered(event, atMs) {
38052
38847
  this.db.markCaptureDelivered(event, atMs);
38053
38848
  }
38849
+ // Implemented, not stubbed, for the same reason its sibling above is: the
38850
+ // attached gateway is a DECORATOR over an instance of this class
38851
+ // (`attached/factory.ts` builds one and passes it as `deps.local`), so every
38852
+ // stamp the live forward makes lands here with a non-empty array. This is the
38853
+ // production write path for that feature, not a shape-satisfying no-op — a
38854
+ // machine that is merely standalone simply never calls it.
38855
+ markAuditEventsDelivered(events, atMs) {
38856
+ this.db.markAuditEventsDelivered(events, atMs);
38857
+ }
38054
38858
  staleBinaryNotice(currentVersion) {
38055
38859
  try {
38056
38860
  const newest = this.db.installedPacks.newestRecordedBinary();
@@ -38209,12 +39013,12 @@ function claimStoreUnavailableWarning(dataDir2, sessionId) {
38209
39013
  return true;
38210
39014
  }
38211
39015
  function markerDirs(dataDir2) {
38212
- return [dataDir2, dirname5(dataDir2)];
39016
+ return [dataDir2, dirname6(dataDir2)];
38213
39017
  }
38214
39018
  function alreadyClaimed(dirs, marker, sessionId) {
38215
39019
  return dirs.some((dir) => {
38216
39020
  try {
38217
- return readFileSync17(join26(dir, marker), "utf8") === sessionId;
39021
+ return readFileSync18(join27(dir, marker), "utf8") === sessionId;
38218
39022
  } catch {
38219
39023
  return false;
38220
39024
  }
@@ -38224,7 +39028,7 @@ function recordClaim(dirs, marker, sessionId) {
38224
39028
  for (const dir of dirs) {
38225
39029
  try {
38226
39030
  mkdirSync5(dir, { recursive: true, mode: DATA_DIR_MODE });
38227
- writeFileSync8(join26(dir, marker), sessionId, { mode: DATA_FILE_MODE });
39031
+ writeFileSync8(join27(dir, marker), sessionId, { mode: DATA_FILE_MODE });
38228
39032
  return;
38229
39033
  } catch {
38230
39034
  }
@@ -38249,7 +39053,7 @@ function formatMode(mode) {
38249
39053
  }
38250
39054
  function warnIfStoreRedirected(config2, sessionId, write = (message) => void process.stderr.write(message)) {
38251
39055
  try {
38252
- const paths = symlinkedStorePaths(dirname5(config2.dataDir));
39056
+ const paths = symlinkedStorePaths(dirname6(config2.dataDir));
38253
39057
  if (paths.length === 0) return;
38254
39058
  if (!sessionId) {
38255
39059
  write(storeRedirectedMessage(paths));