@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.
@@ -496,11 +496,12 @@ import { fileURLToPath as fileURLToPath4 } from "url";
496
496
 
497
497
  // ../../packages/plugin-sdk/src/config.ts
498
498
  import { existsSync as existsSync7 } from "fs";
499
- import { join as join12 } from "path";
499
+ import { join as join13 } from "path";
500
500
 
501
501
  // ../../packages/persistence/src/attached-derived.ts
502
502
  import { rmSync } from "fs";
503
503
  import { join } from "path";
504
+ var POLICY_CACHE_FILENAME = "policy-cache.json";
504
505
  var ATTACHED_FORWARD_STATE_FILENAME = "attached-state.json";
505
506
  var ATTACHED_FORWARD_DROPS_FILENAME = "attached-forward-drops.json";
506
507
 
@@ -601,6 +602,30 @@ var SQLITE_MIGRATIONS = [
601
602
  {
602
603
  tag: "0022_audit_inspection_ms",
603
604
  sql: "ALTER TABLE `audit_events` ADD `inspection_ms` integer GENERATED ALWAYS AS (json_extract(attributes, '$.inspection_ms')) VIRTUAL;"
605
+ },
606
+ {
607
+ tag: "0023_secret_vault_user_authorized",
608
+ sql: "ALTER TABLE `secret_vault` ADD `user_authorized` integer DEFAULT 0 NOT NULL;"
609
+ },
610
+ {
611
+ tag: "0024_finding_resolution_key_created_index",
612
+ 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`);"
613
+ },
614
+ {
615
+ tag: "0025_audit_capture_attribute_columns",
616
+ 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;"
617
+ },
618
+ {
619
+ tag: "0026_audit_llm_call_usage_columns",
620
+ 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;"
621
+ },
622
+ {
623
+ tag: "0027_audit_llm_usage_index",
624
+ 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;"
625
+ },
626
+ {
627
+ tag: "0028_activity_session_probe_indexes",
628
+ 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"
604
629
  }
605
630
  ];
606
631
 
@@ -22143,6 +22168,26 @@ var AttachTokenResponse = external_exports.union([
22143
22168
  AttachTokenExpired,
22144
22169
  external_exports.object({ status: printable(64) })
22145
22170
  ]);
22171
+ var DeviceCommandKind = external_exports.enum(["shares_rescan"]);
22172
+ var DeviceCommand = external_exports.object({
22173
+ id: printable(128).min(1),
22174
+ kind: DeviceCommandKind,
22175
+ issuedAt: printable(64).min(1),
22176
+ expiresAt: printable(64).min(1)
22177
+ }).strict();
22178
+ var DeviceCommandPollResponse = external_exports.object({ command: DeviceCommand.nullable() });
22179
+ var DeviceCommandFailureReason = external_exports.enum(["scan_failed", "no_projects", "expired"]);
22180
+ var DeviceCommandAckBody = external_exports.discriminatedUnion("outcome", [
22181
+ external_exports.object({
22182
+ outcome: external_exports.literal("reported"),
22183
+ projectsScanned: external_exports.number().int().nonnegative()
22184
+ }).strict(),
22185
+ external_exports.object({
22186
+ outcome: external_exports.literal("failed"),
22187
+ reason: DeviceCommandFailureReason,
22188
+ projectsScanned: external_exports.number().int().nonnegative()
22189
+ }).strict()
22190
+ ]);
22146
22191
 
22147
22192
  // ../../packages/schema/src/zod/registry.ts
22148
22193
  var Namespace = external_exports.string().regex(/^[a-z][a-z0-9-]*$/);
@@ -22309,7 +22354,7 @@ var PackManifest = external_exports.object({
22309
22354
  }).meta({ id: "PackManifest" });
22310
22355
 
22311
22356
  // ../../packages/schema/src/zod/detection.ts
22312
- var OriginEnum = external_exports.enum(["library"]).meta({ id: "OriginEnum" });
22357
+ var OriginEnum = external_exports.enum(["library", "custom"]).meta({ id: "OriginEnum" });
22313
22358
  var DetectionFilterEnum = external_exports.enum(["all", "library", "custom", "customized", "updates"]);
22314
22359
  var LibraryStateEnum = external_exports.enum(["new", "imported", "update"]).meta({ id: "LibraryStateEnum" });
22315
22360
  var DetectionCounts = external_exports.object({
@@ -22446,14 +22491,17 @@ function optional2(key, parsed2, raw) {
22446
22491
  function isStringArray(value) {
22447
22492
  return Array.isArray(value) && value.every((entry) => typeof entry === "string");
22448
22493
  }
22494
+ var ORIGIN_VALUES = { library: true, custom: true };
22495
+ function resolveOrigin(origin) {
22496
+ return origin != null && Object.hasOwn(ORIGIN_VALUES, origin) ? origin : "library";
22497
+ }
22449
22498
  function summaryToDetectionListItem(s) {
22450
22499
  return {
22451
22500
  id: `${s.namespace}/${s.packId}`,
22452
22501
  name: s.name,
22453
22502
  version: s.version,
22454
22503
  enabled: s.enabled,
22455
- origin: "library",
22456
- // v1: every installed pack is library origin
22504
+ origin: resolveOrigin(s.origin),
22457
22505
  namespace: s.namespace,
22458
22506
  packId: s.packId,
22459
22507
  ruleCount: s.ruleCount,
@@ -22505,7 +22553,7 @@ function rowToDetectionDetail(row, findingsLast30d, update) {
22505
22553
  name: row.name,
22506
22554
  version: row.version,
22507
22555
  enabled: row.enabled,
22508
- origin: "library",
22556
+ origin: resolveOrigin(row.origin),
22509
22557
  namespace: row.namespace,
22510
22558
  packId: row.packId,
22511
22559
  ruleCount: row.rules.length,
@@ -22525,16 +22573,20 @@ function splitDetectionId(id) {
22525
22573
  }
22526
22574
  function buildDetectionsList(summaries, query) {
22527
22575
  const withUpdate = summaries.filter((s) => s.latestVersion != null);
22576
+ const originOf = (s) => resolveOrigin(s.origin);
22528
22577
  const counts = {
22529
22578
  all: summaries.length,
22530
- library: summaries.length,
22531
- // all origin=library in v1
22532
- custom: 0,
22579
+ library: summaries.filter((s) => originOf(s) === "library").length,
22580
+ custom: summaries.filter((s) => originOf(s) === "custom").length,
22581
+ // No origin member produces this, so it is 0 BY CONSTRUCTION rather than by
22582
+ // omission: `customized` would mean a LIBRARY pack whose rules were edited in
22583
+ // place, and that state does not exist — editing a library pack forks it. See
22584
+ // OriginEnum.
22533
22585
  customized: 0,
22534
22586
  updates: withUpdate.length
22535
22587
  };
22536
22588
  const filter = query.filter;
22537
- let filtered = filter === "custom" || filter === "customized" ? [] : filter === "updates" ? [...withUpdate] : [...summaries];
22589
+ let filtered = filter === "customized" ? [] : filter === "custom" ? summaries.filter((s) => originOf(s) === "custom") : filter === "library" ? summaries.filter((s) => originOf(s) === "library") : filter === "updates" ? [...withUpdate] : [...summaries];
22538
22590
  if (query.q) {
22539
22591
  const q = query.q.toLowerCase();
22540
22592
  filtered = filtered.filter(
@@ -22614,8 +22666,9 @@ var Event = external_exports.object({
22614
22666
  metadata: EventMetadata.optional()
22615
22667
  }).meta({ id: "Event" });
22616
22668
  var IngestEvent = Event.meta({ id: "IngestEvent" });
22669
+ var INGEST_BATCH_MAX = 100;
22617
22670
  var IngestBatch = external_exports.object({
22618
- events: external_exports.array(IngestEvent).min(1).max(100),
22671
+ events: external_exports.array(IngestEvent).min(1).max(INGEST_BATCH_MAX),
22619
22672
  // Dedup policy for this batch. Id-dedup ALWAYS applies. 'content-hash'
22620
22673
  // additionally rejects any event whose contentHash the store has already
22621
22674
  // recorded — for re-runnable bulk ingest (worktree scan, transcript
@@ -23171,375 +23224,11 @@ var PatchInstalledPackRequest = external_exports.object({
23171
23224
  message: "At least one field must be provided"
23172
23225
  }).meta({ id: "PatchInstalledPackRequest" });
23173
23226
 
23174
- // ../../packages/schema/src/zod/vault.ts
23175
- var POINTER_FORMAT_VERSION = 2;
23176
- var CATEGORY_ALTERNATION = DetectionCategory.options.join("|");
23177
- var POINTER_TOKEN_PATTERN = new RegExp(
23178
- `\\[\\[aka:(?:${CATEGORY_ALTERNATION}):[A-Z2-7]{2,7}\\.[A-Z2-7]{26}\\.[A-Z2-7]{16}\\]\\]`
23179
- );
23180
- var POINTER_TOKEN_ANCHORED = new RegExp(`^${POINTER_TOKEN_PATTERN.source}$`);
23181
- function pointerTokenScanner() {
23182
- return new RegExp(POINTER_TOKEN_PATTERN.source, "g");
23183
- }
23184
- var PointerToken = external_exports.string().regex(POINTER_TOKEN_ANCHORED);
23185
- var ParsedPointer = external_exports.object({
23186
- category: DetectionCategory,
23187
- keyVersion: external_exports.number().int().positive(),
23188
- pointerId: external_exports.string(),
23189
- tag: external_exports.string()
23190
- });
23191
- var VaultEntry = external_exports.object({
23192
- pointerId: external_exports.string(),
23193
- // The keyed HMAC of the raw value under `exception.key`, and the epoch it was
23194
- // derived under. This is what a reveal-to-model grant matches on, and it rotates
23195
- // independently of the vault encryption key below.
23196
- valueFingerprint: external_exports.string().regex(/^[0-9a-f]{64}$/),
23197
- fingerprintKeyVersion: external_exports.number().int().positive(),
23198
- // The vault-key epoch this row's ciphertext was sealed under.
23199
- keyVersion: external_exports.number().int().positive(),
23200
- // Fixed at first mint and never updated: the same value detected later under a
23201
- // different rule's category keeps the category it was minted with, so one
23202
- // value always produces exactly one wire token.
23203
- category: DetectionCategory,
23204
- ruleId: external_exports.string(),
23205
- // Partial-reveal preview for badges and listings. Never the raw value.
23206
- maskedMatch: external_exports.string(),
23207
- provider: external_exports.string().optional(),
23208
- ciphertext: external_exports.string(),
23209
- nonce: external_exports.string(),
23210
- authTag: external_exports.string(),
23211
- // How many times this value has been detected on this machine — the reuse
23212
- // signal the vault dashboard reads. Distinct from VaultDeref.pointerCount.
23213
- occurrenceCount: external_exports.number().int().nonnegative(),
23214
- firstSeen: external_exports.string(),
23215
- lastSeen: external_exports.string()
23216
- });
23217
- var PointerDescriptor = external_exports.object({
23218
- category: DetectionCategory,
23219
- provider: external_exports.string().optional(),
23220
- maskedMatch: external_exports.string(),
23221
- occurrences: external_exports.number().int().nonnegative(),
23222
- firstSeen: external_exports.string(),
23223
- lastSeen: external_exports.string()
23224
- });
23225
- var PointerIdentity = external_exports.object({
23226
- ruleId: external_exports.string(),
23227
- valueFingerprint: external_exports.string().regex(/^[0-9a-f]{64}$/),
23228
- fingerprintKeyVersion: external_exports.number().int().positive()
23229
- });
23230
- var DetokenizeTarget = external_exports.enum(["human", "model"]);
23231
- var VaultDerefReason = external_exports.enum([
23232
- "display",
23233
- "explicit-reveal",
23234
- "view-render",
23235
- "model-input",
23236
- "remediation",
23237
- "purge"
23238
- ]);
23239
- var VaultDerefOutcome = external_exports.enum(["revealed", "refused", "unavailable"]);
23240
- var VaultDeref = external_exports.object({
23241
- id: external_exports.guid(),
23242
- pointerId: external_exports.string(),
23243
- at: external_exports.string(),
23244
- target: DetokenizeTarget,
23245
- reason: VaultDerefReason,
23246
- outcome: VaultDerefOutcome,
23247
- // Present only on a model-target crossing that a reveal grant authorized.
23248
- grantId: external_exports.string().optional(),
23249
- // How many pointers ONE batched render resolved. 1 for unbatched rows. Named
23250
- // apart from VaultEntry.occurrenceCount, which counts detections of a value.
23251
- pointerCount: external_exports.number().int().positive().default(1)
23252
- });
23253
- var VaultSightingKind = external_exports.enum([
23254
- "prompt",
23255
- "tool-input",
23256
- "tool-output",
23257
- "file",
23258
- "transcript"
23259
- ]);
23260
- var VaultSighting = external_exports.object({
23261
- location: external_exports.string(),
23262
- kind: VaultSightingKind,
23263
- firstSeen: external_exports.string(),
23264
- lastSeen: external_exports.string()
23265
- });
23266
- var VaultInventoryEntry = external_exports.object({
23267
- pointerId: external_exports.string(),
23268
- category: DetectionCategory,
23269
- provider: external_exports.string().optional(),
23270
- maskedMatch: external_exports.string(),
23271
- occurrences: external_exports.number().int().nonnegative(),
23272
- firstSeen: external_exports.string(),
23273
- lastSeen: external_exports.string(),
23274
- // The active reveal-to-model grant covering this value, when one exists —
23275
- // the inventory badges it, the row links to revocation.
23276
- revealGrantId: external_exports.string().nullable(),
23277
- sightings: external_exports.array(VaultSighting)
23278
- });
23279
- var DEFAULT_VAULT_INVENTORY_LIMIT = 50;
23280
- var DEFAULT_VAULT_DEREFS_LIMIT = 50;
23281
- var MAX_VAULT_PAGE_LIMIT = 200;
23282
- var ListVaultInventoryQuery = external_exports.object({
23283
- limit: external_exports.coerce.number().int().min(1).max(MAX_VAULT_PAGE_LIMIT).optional(),
23284
- // Opaque; names the last row of the page just served.
23285
- cursor: external_exports.string().optional()
23286
- });
23287
- var ListVaultInventoryResponse = external_exports.object({
23288
- // Vaulted values across the whole store, not just this page — cursor-
23289
- // independent, so paging never changes what the count claims.
23290
- totals: external_exports.object({ values: external_exports.number().int().nonnegative() }),
23291
- items: external_exports.array(VaultInventoryEntry),
23292
- // `null` once the last page is reached.
23293
- nextCursor: external_exports.string().nullable()
23294
- });
23295
- var ListVaultReuseQuery = external_exports.object({
23296
- limit: external_exports.coerce.number().int().min(1).max(MAX_VAULT_PAGE_LIMIT).optional(),
23297
- cursor: external_exports.string().optional()
23298
- });
23299
- var ListVaultReuseResponse = external_exports.object({
23300
- // Reused values across the whole store — the number the section's claim
23301
- // ("values detected in more than one place") is about.
23302
- totals: external_exports.object({ reused: external_exports.number().int().nonnegative() }),
23303
- items: external_exports.array(VaultInventoryEntry),
23304
- nextCursor: external_exports.string().nullable()
23305
- });
23306
- var ListVaultDerefsQuery = external_exports.object({
23307
- // Include the batched, high-volume reasons (display, view-render). Omitted
23308
- // hides them and counts them into `hiddenBatched` instead, so the model
23309
- // crossings stay visible. A real boolean, not `z.stringbool()`: this arrives
23310
- // over a Server Action, which preserves the type, never as a URL param.
23311
- includeBatched: external_exports.boolean().optional(),
23312
- limit: external_exports.coerce.number().int().min(1).max(MAX_VAULT_PAGE_LIMIT).optional(),
23313
- cursor: external_exports.string().optional()
23314
- });
23315
- var ListVaultDerefsResponse = external_exports.object({
23316
- items: external_exports.array(VaultDeref),
23317
- nextCursor: external_exports.string().nullable(),
23318
- // Display/view-render rows the query hid, over the WHOLE trail rather than
23319
- // this page — it is the count the "N hidden" line and its toggle speak for.
23320
- // Always 0 when `includeBatched` was set, since nothing was hidden.
23321
- hiddenBatched: external_exports.number().int().nonnegative()
23322
- });
23323
- var VaultKeyCustody = external_exports.string();
23324
- var VaultInlineReveal = external_exports.enum(["masked", "full", "off"]);
23325
- var VAULT_CONSENT_VERSION = 1;
23326
- var VaultConsent = external_exports.object({
23327
- acknowledgedAt: external_exports.iso.datetime(),
23328
- version: external_exports.number().int().positive()
23329
- });
23330
-
23331
- // ../../packages/schema/src/zod/local.ts
23332
- var WORKSPACE_SETTINGS_SPEC_VERSION = 6;
23333
- var MODEL_JUDGE_PAYLOAD_VERSION = 1;
23334
- var RunMode = external_exports.enum(["standalone", "attached"]);
23335
- var ControlPlaneConnection = external_exports.object({
23336
- endpoint: external_exports.string().min(1),
23337
- // Display name for the deployment, shown instead of the raw endpoint.
23338
- label: external_exports.string().min(1).optional(),
23339
- attachedAt: external_exports.iso.datetime()
23340
- }).meta({ id: "ControlPlaneConnection" });
23341
- var SimpleDetectionPolicy = external_exports.enum(["redact", "warn"]);
23342
- var HistoricalAccess = external_exports.enum(["full", "session-only"]);
23343
- var ModelJudgeConsent = external_exports.object({
23344
- acknowledgedAt: external_exports.iso.datetime(),
23345
- payloadVersion: external_exports.number().int().positive()
23346
- });
23347
- var HistorySyncConsent = external_exports.object({
23348
- acknowledgedAt: external_exports.iso.datetime(),
23349
- payloadVersion: external_exports.number().int().positive(),
23350
- endpoint: external_exports.string()
23351
- });
23352
- var WorkspaceSettings = external_exports.object({
23353
- specVersion: external_exports.number().int().positive().default(WORKSPACE_SETTINGS_SPEC_VERSION),
23354
- runMode: RunMode.default("standalone"),
23355
- // Present only while attached; a detach clears it. Its presence is what makes
23356
- // `runMode: 'attached'` mean anything — see isAttached.
23357
- controlPlane: ControlPlaneConnection.optional(),
23358
- policy: SimpleDetectionPolicy.default("redact"),
23359
- // Consent for scanning pre-install surfaces; opt-in (see HistoricalAccess).
23360
- historicalAccess: HistoricalAccess.default("session-only"),
23361
- // In-place egress extraction on the scan paths; disable to stop all Data
23362
- // Shares writes.
23363
- dataSharesInPlace: external_exports.boolean().default(true),
23364
- // Consent to keep a RECOVERABLE encrypted copy of detected values in the local
23365
- // vault, instead of destroying them. Absent by default: this is a custody
23366
- // change from one-way redaction, so it is never an assumed grant on upgrade.
23367
- // Revoking stops future vaulting; it does not erase what is already stored —
23368
- // purging the vault is the eraser.
23369
- vaultConsent: VaultConsent.optional(),
23370
- // Where the vault master key lives.
23371
- vaultKeyCustody: VaultKeyCustody.default("file"),
23372
- // How a pointer renders in assistant prose on screen (see VaultInlineReveal).
23373
- vaultInlineReveal: VaultInlineReveal.default("masked"),
23374
- // Absent until /aka:setup completes; its presence is what "onboarded" means.
23375
- onboardedAt: external_exports.iso.datetime().optional(),
23376
- // Records that the user consented to sending findings to the model API for
23377
- // the /aka:setup judge, along with the payload-shape version they agreed to.
23378
- // Absent until granted; a stale payloadVersion means the consent no longer
23379
- // covers the current payload and must be re-granted.
23380
- modelJudgeConsent: ModelJudgeConsent.optional(),
23381
- // Records that the user consented to sending the activity already recorded on
23382
- // this machine to the deployment it is attached to, along with the payload
23383
- // shape and the endpoint they agreed to. Absent until granted, and a grant for
23384
- // a different endpoint or an older payload no longer counts.
23385
- historySyncConsent: HistorySyncConsent.optional()
23386
- });
23387
- function defaultWorkspaceSettings() {
23388
- return WorkspaceSettings.parse({});
23389
- }
23390
- function isAttached(settings) {
23391
- return settings.runMode === "attached" && settings.controlPlane !== void 0;
23392
- }
23393
- function toInventoryRow(input2, id, now) {
23394
- return {
23395
- id,
23396
- objectType: input2.objectType,
23397
- location: input2.location ?? null,
23398
- title: input2.title ?? null,
23399
- hostId: input2.hostId ?? null,
23400
- attributes: JSON.stringify(input2.attributes),
23401
- firstSeen: now,
23402
- lastSeen: now
23403
- };
23404
- }
23405
- function toSourceProjectRow(input2, id, now) {
23406
- return {
23407
- id,
23408
- url: input2.url,
23409
- name: input2.name ?? null,
23410
- attributes: JSON.stringify(input2.attributes),
23411
- firstSeen: now,
23412
- lastSeen: now
23413
- };
23414
- }
23415
- function toAuditEventRow(input2) {
23416
- return {
23417
- id: input2.id,
23418
- parentId: input2.parentId ?? null,
23419
- rootSessionId: input2.rootSessionId ?? null,
23420
- eventType: input2.eventType,
23421
- hostId: input2.hostId ?? null,
23422
- harnessId: input2.harnessId ?? null,
23423
- sourceProjectId: input2.sourceProjectId ?? null,
23424
- startedAt: isoToEpochMillis(input2.startedAt),
23425
- endedAt: input2.endedAt ? isoToEpochMillis(input2.endedAt) : null,
23426
- severity: input2.severity ?? null,
23427
- priority: input2.priority ?? null,
23428
- content: input2.content ?? null,
23429
- contentHash: input2.contentHash ?? null,
23430
- attributes: input2.attributes ? JSON.stringify(input2.attributes) : null
23431
- };
23432
- }
23433
- function toClassifiedDataRow(input2, id) {
23434
- return {
23435
- id,
23436
- class: input2.class,
23437
- label: input2.label ?? null,
23438
- attributes: input2.attributes ? JSON.stringify(input2.attributes) : null
23439
- };
23440
- }
23441
- function toInspectionDefinitionRow(input2, id) {
23442
- return {
23443
- id,
23444
- ruleId: input2.ruleId,
23445
- name: input2.name,
23446
- category: input2.category,
23447
- severity: input2.severity,
23448
- definition: input2.definition,
23449
- version: input2.version
23450
- };
23451
- }
23452
- function toInspectionFindingRow(input2) {
23453
- return {
23454
- id: input2.id,
23455
- auditEventId: input2.auditEventId,
23456
- inspectionDefinitionId: input2.inspectionDefinitionId,
23457
- classifiedDataId: input2.classifiedDataId ?? null,
23458
- spanStart: input2.span.start,
23459
- spanEnd: input2.span.end,
23460
- maskedMatch: input2.maskedMatch,
23461
- actionTaken: input2.actionTaken,
23462
- confidence: input2.confidence,
23463
- findingKey: input2.findingKey ?? null,
23464
- firstDetectedAt: input2.firstDetectedAt ? isoToEpochMillis(input2.firstDetectedAt) : null
23465
- };
23466
- }
23467
- function toCaptureAttributes(event) {
23468
- const metadata = event.metadata;
23469
- return {
23470
- source_tool: event.sourceTool,
23471
- ...metadata?.repo !== void 0 ? { repo: metadata.repo } : {},
23472
- ...metadata?.filePath !== void 0 ? { file_path: metadata.filePath } : {},
23473
- ...metadata?.toolName !== void 0 ? { tool_name: metadata.toolName } : {},
23474
- ...metadata?.gitignored !== void 0 ? { gitignored: metadata.gitignored } : {},
23475
- ...metadata?.wholeFile !== void 0 ? { whole_file: metadata.wholeFile } : {},
23476
- ...metadata?.correlationId !== void 0 ? { correlation_id: metadata.correlationId } : {},
23477
- ...metadata?.traceId !== void 0 ? { trace_id: metadata.traceId } : {},
23478
- ...metadata?.exceptionIds !== void 0 ? { exception_ids: metadata.exceptionIds } : {},
23479
- ...metadata?.inspectionMs !== void 0 ? { inspection_ms: metadata.inspectionMs } : {},
23480
- // `model`/`turnIndex` have no dedicated CaptureAttributes field (no writer
23481
- // has ever populated either), but every legacy metadata key still rides
23482
- // the bag rather than being silently dropped — CaptureAttributes'
23483
- // `.catchall(z.unknown())` carries the long tail.
23484
- ...metadata?.model !== void 0 ? { model: metadata.model } : {},
23485
- ...metadata?.turnIndex !== void 0 ? { turn_index: metadata.turnIndex } : {}
23486
- };
23487
- }
23488
- function captureDefinitionVersion(finding) {
23489
- return `capture/${finding.category}/${finding.severity}`;
23490
- }
23491
- function toCaptureDefinitionInput(finding) {
23492
- return {
23493
- ruleId: finding.ruleId,
23494
- version: captureDefinitionVersion(finding),
23495
- name: finding.ruleId,
23496
- category: finding.category,
23497
- severity: finding.severity,
23498
- definition: JSON.stringify({ ruleId: finding.ruleId })
23499
- };
23500
- }
23501
-
23502
- // ../../packages/schema/src/zod/managed.ts
23503
- var MANAGED_SETTINGS_FILENAME = "managed-settings.json";
23504
- var MANAGED_SETTINGS_SPEC_VERSION = 1;
23505
- var ManagedSettingKey = external_exports.enum([
23506
- "runMode",
23507
- "historicalAccess",
23508
- "vaultConsent",
23509
- "vaultKeyCustody",
23510
- "vaultInlineReveal",
23511
- "modelJudgeConsent",
23512
- "dataSharesInPlace"
23513
- ]).meta({ id: "ManagedSettingKey" });
23514
- var ManagedSettingsValues = external_exports.object({
23515
- runMode: external_exports.enum(["standalone", "attached"]).optional(),
23516
- controlPlane: external_exports.object({
23517
- endpoint: external_exports.string().min(1),
23518
- label: external_exports.string().min(1).optional()
23519
- }).optional(),
23520
- historicalAccess: external_exports.enum(["full", "session-only"]).optional(),
23521
- vaultConsent: external_exports.boolean().optional(),
23522
- vaultKeyCustody: external_exports.enum(["file", "keychain"]).optional(),
23523
- vaultInlineReveal: external_exports.enum(["masked", "full", "off"]).optional(),
23524
- modelJudgeConsent: external_exports.boolean().optional(),
23525
- dataSharesInPlace: external_exports.boolean().optional()
23526
- }).meta({ id: "ManagedSettingsValues" });
23527
- var ManagedSettings = external_exports.object({
23528
- specVersion: external_exports.number().int().positive().default(MANAGED_SETTINGS_SPEC_VERSION),
23529
- // Shown on every locked control, so the user can tell an administrative
23530
- // decision from a bug. Absent renders as a generic "your organization".
23531
- organization: external_exports.string().min(1).optional(),
23532
- // What the administrator pinned.
23533
- values: ManagedSettingsValues.default({}),
23534
- // Which of those the user may not change. A key here with no matching value
23535
- // freezes whatever the user last chose; a value with no lock is a DEFAULT
23536
- // the user may still override. The two are separable on purpose.
23537
- lockedFields: external_exports.array(ManagedSettingKey).default([])
23538
- }).meta({ id: "ManagedSettings" });
23539
-
23540
23227
  // ../../packages/schema/src/zod/policy.ts
23541
23228
  var PolicyScope = external_exports.enum(["global", "repo", "user"]).meta({ id: "PolicyScope" });
23542
23229
  var PolicyTarget = external_exports.union([external_exports.object({ ruleId: external_exports.string() }), external_exports.object({ category: DetectionCategory })]).meta({ id: "PolicyTarget" });
23230
+ var PolicyKind = external_exports.enum(["builtin", "custom"]).meta({ id: "PolicyKind" });
23231
+ var PolicyProvenance = external_exports.enum(["builtin", "authored"]).meta({ id: "PolicyProvenance" });
23543
23232
  var Policy = external_exports.object({
23544
23233
  id: external_exports.guid(),
23545
23234
  scope: PolicyScope,
@@ -23549,7 +23238,27 @@ var Policy = external_exports.object({
23549
23238
  customKeywords: external_exports.array(external_exports.string()).optional(),
23550
23239
  // Display name — optional so older policy rows without name still parse.
23551
23240
  // Added for the findings API (policy.name column migration).
23552
- name: external_exports.string().optional()
23241
+ name: external_exports.string().optional(),
23242
+ // Whether an AUTHORED policy governs this row's target — not a claim about
23243
+ // which row this is. A producer that collapses several rows onto one target
23244
+ // must carry the marker onto whichever row survives, or the collapse decides
23245
+ // the answer; a survivor may therefore be a built-in expansion still marked
23246
+ // 'authored' because an authored sibling targeted the same thing.
23247
+ // Optional so an older producer — and an older on-disk cache — still parses;
23248
+ // absent reads as 'builtin', which is the behaviour that predates the field.
23249
+ //
23250
+ // Deliberately NOT `kind`/PolicyKind: that name and that enum answer which
23251
+ // built-in archetype catalog entry a policy is, which every catalog surface
23252
+ // reads and which a caller may state. This one is a statement the PRODUCER
23253
+ // of a bundle makes about a row, and only the bundle builder ever stamps it
23254
+ // — the CRUD routes neither accept nor set it.
23255
+ //
23256
+ // A device consumes this in exactly one direction: an 'authored' policy
23257
+ // arriving from a control plane marks the rules it targets as not
23258
+ // locally re-assignable. That can only ever ADD a refusal, never relax one,
23259
+ // which is what makes it safe to honour from an unsigned cache — the same
23260
+ // test `prohibitedModels` passes and `reversibleRuleIds` fails.
23261
+ provenance: PolicyProvenance.optional()
23553
23262
  }).meta({ id: "Policy" });
23554
23263
  var PolicyBundle = external_exports.object({
23555
23264
  version: external_exports.string(),
@@ -23601,6 +23310,12 @@ var PolicyBundle = external_exports.object({
23601
23310
  customKeywords: external_exports.array(external_exports.string()),
23602
23311
  fetchedAt: external_exports.iso.datetime()
23603
23312
  }).meta({ id: "PolicyBundle" });
23313
+ var POLICY_BUNDLE_SHAPE_ID = [
23314
+ ...Object.keys(PolicyBundle.shape),
23315
+ ...Object.keys(Policy.shape).map((key) => `policies.${key}`),
23316
+ ...PolicyTarget.options.flatMap((member) => "shape" in member ? Object.keys(member.shape) : []).map((key) => `policies.target.${key}`),
23317
+ ...Object.keys(ExceptionBundleEntry.shape).map((key) => `exceptions.${key}`)
23318
+ ].sort().join(",");
23604
23319
  var OBSERVE_ONLY_CATEGORIES = ["config"];
23605
23320
  var ENFORCEABLE_CATEGORIES = DetectionCategory.options.filter((c) => !OBSERVE_ONLY_CATEGORIES.includes(c));
23606
23321
  var CATEGORY_PEAK_SEVERITY = {
@@ -23621,9 +23336,11 @@ function severityFloorPolicy(category) {
23621
23336
  const peak = CATEGORY_PEAK_SEVERITY[category];
23622
23337
  return peak === "critical" || peak === "high" ? "warn" : "monitor";
23623
23338
  }
23624
- var PolicyKind = external_exports.enum(["builtin", "custom"]).meta({ id: "PolicyKind" });
23625
23339
  var KNOWN_BUILTIN_IDS = ["monitor", "warn", "redact", "vault", "block"];
23626
23340
  var BuiltinPolicyId = external_exports.enum(KNOWN_BUILTIN_IDS).meta({ id: "BuiltinPolicyId" });
23341
+ var RedactFallback = BuiltinPolicyId.extract(["monitor", "warn", "block"]).meta({
23342
+ id: "RedactFallback"
23343
+ });
23627
23344
  var BUILTIN_ORDER = KNOWN_BUILTIN_IDS;
23628
23345
  var BUILTIN_POLICY_SPECS = {
23629
23346
  monitor: {
@@ -23660,6 +23377,42 @@ var BUILTIN_POLICY_SPECS = {
23660
23377
  function builtinPolicyToAction(id) {
23661
23378
  return BUILTIN_POLICY_SPECS[id].action;
23662
23379
  }
23380
+ var PALETTE_WEAKEST_FIRST = [
23381
+ ...new Set(KNOWN_BUILTIN_IDS.map(builtinPolicyToAction))
23382
+ ];
23383
+ var BELOW_PALETTE = ACTION_TAKEN_KEYS.filter(
23384
+ (action) => !PALETTE_WEAKEST_FIRST.includes(action)
23385
+ );
23386
+ var ACTION_STRENGTH_ORDER = [
23387
+ ...BELOW_PALETTE,
23388
+ ...PALETTE_WEAKEST_FIRST
23389
+ ];
23390
+ function actionRank(action) {
23391
+ return ACTION_STRENGTH_ORDER.indexOf(action);
23392
+ }
23393
+ function isActionAtLeast(action, floor) {
23394
+ return actionRank(action) >= actionRank(floor);
23395
+ }
23396
+ function strongerAction(a, b) {
23397
+ return actionRank(a) >= actionRank(b) ? a : b;
23398
+ }
23399
+ function weakestBuiltinAtLeast(floor) {
23400
+ return KNOWN_BUILTIN_IDS.find((id) => isActionAtLeast(builtinPolicyToAction(id), floor)) ?? "block";
23401
+ }
23402
+ var PackPolicyFloor = external_exports.object({
23403
+ /**
23404
+ * The weakest archetype the device may assign. Stated as a BuiltinPolicyId
23405
+ * rather than a raw ActionTaken because that is the vocabulary the user
23406
+ * picks from — a floor a UI cannot name is one it cannot explain.
23407
+ */
23408
+ floor: BuiltinPolicyId,
23409
+ /**
23410
+ * True when the organization AUTHORED a policy governing this pack rather
23411
+ * than stating a minimum: it gave the answer, so the pack is not
23412
+ * re-assignable locally in either direction.
23413
+ */
23414
+ locked: external_exports.boolean()
23415
+ }).describe("PackPolicyFloor");
23663
23416
  var CATEGORY_EXPRESSIBLE_IDS = KNOWN_BUILTIN_IDS.filter(
23664
23417
  (id) => !BUILTIN_POLICY_SPECS[id].reversible
23665
23418
  );
@@ -23717,6 +23470,397 @@ var PolicyStatsResponse = external_exports.object({
23717
23470
  detectionsGoverned: external_exports.number().int().nonnegative()
23718
23471
  }).meta({ id: "PolicyStatsResponse" });
23719
23472
 
23473
+ // ../../packages/schema/src/zod/vault.ts
23474
+ var POINTER_FORMAT_VERSION = 2;
23475
+ var CATEGORY_ALTERNATION = DetectionCategory.options.join("|");
23476
+ var POINTER_TOKEN_PATTERN = new RegExp(
23477
+ `\\[\\[aka:(?:${CATEGORY_ALTERNATION}):[A-Z2-7]{2,7}\\.[A-Z2-7]{26}\\.[A-Z2-7]{16}\\]\\]`
23478
+ );
23479
+ var POINTER_TOKEN_ANCHORED = new RegExp(`^${POINTER_TOKEN_PATTERN.source}$`);
23480
+ function pointerTokenScanner() {
23481
+ return new RegExp(POINTER_TOKEN_PATTERN.source, "g");
23482
+ }
23483
+ var PointerToken = external_exports.string().regex(POINTER_TOKEN_ANCHORED);
23484
+ var ParsedPointer = external_exports.object({
23485
+ category: DetectionCategory,
23486
+ keyVersion: external_exports.number().int().positive(),
23487
+ pointerId: external_exports.string(),
23488
+ tag: external_exports.string()
23489
+ });
23490
+ var VaultEntry = external_exports.object({
23491
+ pointerId: external_exports.string(),
23492
+ // The keyed HMAC of the raw value under `exception.key`, and the epoch it was
23493
+ // derived under. This is what a reveal-to-model grant matches on, and it rotates
23494
+ // independently of the vault encryption key below.
23495
+ valueFingerprint: external_exports.string().regex(/^[0-9a-f]{64}$/),
23496
+ fingerprintKeyVersion: external_exports.number().int().positive(),
23497
+ // The vault-key epoch this row's ciphertext was sealed under.
23498
+ keyVersion: external_exports.number().int().positive(),
23499
+ // Fixed at first mint and never updated: the same value detected later under a
23500
+ // different rule's category keeps the category it was minted with, so one
23501
+ // value always produces exactly one wire token.
23502
+ category: DetectionCategory,
23503
+ ruleId: external_exports.string(),
23504
+ // Partial-reveal preview for badges and listings. Never the raw value.
23505
+ maskedMatch: external_exports.string(),
23506
+ provider: external_exports.string().optional(),
23507
+ ciphertext: external_exports.string(),
23508
+ nonce: external_exports.string(),
23509
+ authTag: external_exports.string(),
23510
+ // How many times this value has been detected on this machine — the reuse
23511
+ // signal the vault dashboard reads. Distinct from VaultDeref.pointerCount.
23512
+ occurrenceCount: external_exports.number().int().nonnegative(),
23513
+ // True when a PERSON asked for this value to be replaced — the surfaced-
23514
+ // secrets strike — rather than a pack enforcing its assignment. One value is
23515
+ // one row however many paths vault it, so this is what tells a policy sweep
23516
+ // that the row carries somebody's own instruction and not just an assignment
23517
+ // that has since been lowered. STICKY and MONOTONIC: a later automatic
23518
+ // vaulting of the same value must never clear it — what the user said about
23519
+ // the value does not expire.
23520
+ userAuthorized: external_exports.boolean(),
23521
+ firstSeen: external_exports.string(),
23522
+ lastSeen: external_exports.string()
23523
+ });
23524
+ var PointerDescriptor = external_exports.object({
23525
+ category: DetectionCategory,
23526
+ provider: external_exports.string().optional(),
23527
+ maskedMatch: external_exports.string(),
23528
+ occurrences: external_exports.number().int().nonnegative(),
23529
+ firstSeen: external_exports.string(),
23530
+ lastSeen: external_exports.string()
23531
+ });
23532
+ var PointerIdentity = external_exports.object({
23533
+ ruleId: external_exports.string(),
23534
+ valueFingerprint: external_exports.string().regex(/^[0-9a-f]{64}$/),
23535
+ fingerprintKeyVersion: external_exports.number().int().positive()
23536
+ });
23537
+ var DetokenizeTarget = external_exports.enum(["human", "model"]);
23538
+ var VaultDerefReason = external_exports.enum([
23539
+ "display",
23540
+ "explicit-reveal",
23541
+ "view-render",
23542
+ "model-input",
23543
+ "remediation",
23544
+ "purge"
23545
+ ]);
23546
+ var VaultDerefOutcome = external_exports.enum(["revealed", "refused", "unavailable"]);
23547
+ var VaultDeref = external_exports.object({
23548
+ id: external_exports.guid(),
23549
+ pointerId: external_exports.string(),
23550
+ at: external_exports.string(),
23551
+ target: DetokenizeTarget,
23552
+ reason: VaultDerefReason,
23553
+ outcome: VaultDerefOutcome,
23554
+ // Present only on a model-target crossing that a reveal grant authorized.
23555
+ grantId: external_exports.string().optional(),
23556
+ // How many pointers ONE batched render resolved. 1 for unbatched rows. Named
23557
+ // apart from VaultEntry.occurrenceCount, which counts detections of a value.
23558
+ pointerCount: external_exports.number().int().positive().default(1)
23559
+ });
23560
+ var VaultSightingKind = external_exports.enum([
23561
+ "prompt",
23562
+ "tool-input",
23563
+ "tool-output",
23564
+ "file",
23565
+ "transcript"
23566
+ ]);
23567
+ var VaultSighting = external_exports.object({
23568
+ location: external_exports.string(),
23569
+ kind: VaultSightingKind,
23570
+ firstSeen: external_exports.string(),
23571
+ lastSeen: external_exports.string()
23572
+ });
23573
+ var VaultInventoryEntry = external_exports.object({
23574
+ pointerId: external_exports.string(),
23575
+ category: DetectionCategory,
23576
+ provider: external_exports.string().optional(),
23577
+ maskedMatch: external_exports.string(),
23578
+ occurrences: external_exports.number().int().nonnegative(),
23579
+ firstSeen: external_exports.string(),
23580
+ lastSeen: external_exports.string(),
23581
+ // The active reveal-to-model grant covering this value, when one exists —
23582
+ // the inventory badges it, the row links to revocation.
23583
+ revealGrantId: external_exports.string().nullable(),
23584
+ sightings: external_exports.array(VaultSighting)
23585
+ });
23586
+ var DEFAULT_VAULT_INVENTORY_LIMIT = 50;
23587
+ var DEFAULT_VAULT_DEREFS_LIMIT = 50;
23588
+ var MAX_VAULT_PAGE_LIMIT = 200;
23589
+ var ListVaultInventoryQuery = external_exports.object({
23590
+ limit: external_exports.coerce.number().int().min(1).max(MAX_VAULT_PAGE_LIMIT).optional(),
23591
+ // Opaque; names the last row of the page just served.
23592
+ cursor: external_exports.string().optional()
23593
+ });
23594
+ var ListVaultInventoryResponse = external_exports.object({
23595
+ // Vaulted values across the whole store, not just this page — cursor-
23596
+ // independent, so paging never changes what the count claims.
23597
+ totals: external_exports.object({ values: external_exports.number().int().nonnegative() }),
23598
+ items: external_exports.array(VaultInventoryEntry),
23599
+ // `null` once the last page is reached.
23600
+ nextCursor: external_exports.string().nullable()
23601
+ });
23602
+ var ListVaultReuseQuery = external_exports.object({
23603
+ limit: external_exports.coerce.number().int().min(1).max(MAX_VAULT_PAGE_LIMIT).optional(),
23604
+ cursor: external_exports.string().optional()
23605
+ });
23606
+ var ListVaultReuseResponse = external_exports.object({
23607
+ // Reused values across the whole store — the number the section's claim
23608
+ // ("values detected in more than one place") is about.
23609
+ totals: external_exports.object({ reused: external_exports.number().int().nonnegative() }),
23610
+ items: external_exports.array(VaultInventoryEntry),
23611
+ nextCursor: external_exports.string().nullable()
23612
+ });
23613
+ var ListVaultDerefsQuery = external_exports.object({
23614
+ // Include the batched, high-volume reasons (display, view-render). Omitted
23615
+ // hides them and counts them into `hiddenBatched` instead, so the model
23616
+ // crossings stay visible. A real boolean, not `z.stringbool()`: this arrives
23617
+ // over a Server Action, which preserves the type, never as a URL param.
23618
+ includeBatched: external_exports.boolean().optional(),
23619
+ limit: external_exports.coerce.number().int().min(1).max(MAX_VAULT_PAGE_LIMIT).optional(),
23620
+ cursor: external_exports.string().optional()
23621
+ });
23622
+ var ListVaultDerefsResponse = external_exports.object({
23623
+ items: external_exports.array(VaultDeref),
23624
+ nextCursor: external_exports.string().nullable(),
23625
+ // Display/view-render rows the query hid, over the WHOLE trail rather than
23626
+ // this page — it is the count the "N hidden" line and its toggle speak for.
23627
+ // Always 0 when `includeBatched` was set, since nothing was hidden.
23628
+ hiddenBatched: external_exports.number().int().nonnegative()
23629
+ });
23630
+ var VaultKeyCustody = external_exports.string();
23631
+ var VaultInlineReveal = external_exports.enum(["masked", "full", "off"]);
23632
+ var VAULT_CONSENT_VERSION = 1;
23633
+ var VaultConsent = external_exports.object({
23634
+ acknowledgedAt: external_exports.iso.datetime(),
23635
+ version: external_exports.number().int().positive()
23636
+ });
23637
+
23638
+ // ../../packages/schema/src/zod/local.ts
23639
+ var WORKSPACE_SETTINGS_SPEC_VERSION = 7;
23640
+ var MODEL_JUDGE_PAYLOAD_VERSION = 1;
23641
+ var RunMode = external_exports.enum(["standalone", "attached"]);
23642
+ var ControlPlaneConnection = external_exports.object({
23643
+ endpoint: external_exports.string().min(1),
23644
+ // Display name for the deployment, shown instead of the raw endpoint.
23645
+ label: external_exports.string().min(1).optional(),
23646
+ attachedAt: external_exports.iso.datetime()
23647
+ }).meta({ id: "ControlPlaneConnection" });
23648
+ var SimpleDetectionPolicy = external_exports.enum(["redact", "warn"]);
23649
+ var HistoricalAccess = external_exports.enum(["full", "session-only"]);
23650
+ var ModelJudgeConsent = external_exports.object({
23651
+ acknowledgedAt: external_exports.iso.datetime(),
23652
+ payloadVersion: external_exports.number().int().positive()
23653
+ });
23654
+ var HistorySyncConsent = external_exports.object({
23655
+ acknowledgedAt: external_exports.iso.datetime(),
23656
+ payloadVersion: external_exports.number().int().positive(),
23657
+ endpoint: external_exports.string()
23658
+ });
23659
+ var WorkspaceSettings = external_exports.object({
23660
+ specVersion: external_exports.number().int().positive().default(WORKSPACE_SETTINGS_SPEC_VERSION),
23661
+ runMode: RunMode.default("standalone"),
23662
+ // Present only while attached; a detach clears it. Its presence is what makes
23663
+ // `runMode: 'attached'` mean anything — see isAttached.
23664
+ controlPlane: ControlPlaneConnection.optional(),
23665
+ policy: SimpleDetectionPolicy.default("redact"),
23666
+ // Consent for scanning pre-install surfaces; opt-in (see HistoricalAccess).
23667
+ historicalAccess: HistoricalAccess.default("session-only"),
23668
+ // In-place egress extraction on the scan paths; disable to stop all Data
23669
+ // Shares writes.
23670
+ dataSharesInPlace: external_exports.boolean().default(true),
23671
+ // Consent to keep a RECOVERABLE encrypted copy of detected values in the local
23672
+ // vault, instead of destroying them. Absent by default: this is a custody
23673
+ // change from one-way redaction, so it is never an assumed grant on upgrade.
23674
+ // Revoking stops future vaulting; it does not erase what is already stored —
23675
+ // purging the vault is the eraser.
23676
+ vaultConsent: VaultConsent.optional(),
23677
+ // Where the vault master key lives.
23678
+ vaultKeyCustody: VaultKeyCustody.default("file"),
23679
+ // How a pointer renders in assistant prose on screen (see VaultInlineReveal).
23680
+ vaultInlineReveal: VaultInlineReveal.default("masked"),
23681
+ // What a `redact` policy degrades to on a FIELD the host cannot rewrite in
23682
+ // place. Not a handling policy: the policy has already resolved to redact,
23683
+ // and this only says what happens when the host offers no channel to carry it
23684
+ // out — Antigravity's PreToolUse has no updatedInput at all, and Codex and
23685
+ // Claude Code decline to mask a field that EXECUTES because masking would
23686
+ // change what runs. Per FIELD rather than per host, so a host that can
23687
+ // rewrite some inputs keeps true redaction on those.
23688
+ //
23689
+ // Spelled in the built-in policy vocabulary rather than as a fresh enum, so
23690
+ // an attached machine's merge is `strongerAction` over the one action ladder
23691
+ // and no second rank order exists to drift from it. 'deny' is a host wire
23692
+ // word and stays out of the stored value.
23693
+ redactFallback: RedactFallback.default("warn"),
23694
+ // Absent until /aka:setup completes; its presence is what "onboarded" means.
23695
+ onboardedAt: external_exports.iso.datetime().optional(),
23696
+ // Records that the user consented to sending findings to the model API for
23697
+ // the /aka:setup judge, along with the payload-shape version they agreed to.
23698
+ // Absent until granted; a stale payloadVersion means the consent no longer
23699
+ // covers the current payload and must be re-granted.
23700
+ modelJudgeConsent: ModelJudgeConsent.optional(),
23701
+ // Records that the user consented to the DEFERRED send — the outbox — along
23702
+ // with the payload shape and the endpoint they agreed to. Since payload v2
23703
+ // that covers both the pre-attach backlog and undelivered captures (which
23704
+ // carry prompt/reply text in `content`); the key name predates the widening.
23705
+ // Absent until granted, and a grant for a different endpoint or an older
23706
+ // payload no longer counts.
23707
+ historySyncConsent: HistorySyncConsent.optional()
23708
+ });
23709
+ function defaultWorkspaceSettings() {
23710
+ return WorkspaceSettings.parse({});
23711
+ }
23712
+ function isAttached(settings) {
23713
+ return settings.runMode === "attached" && settings.controlPlane !== void 0;
23714
+ }
23715
+ function toInventoryRow(input2, id, now) {
23716
+ return {
23717
+ id,
23718
+ objectType: input2.objectType,
23719
+ location: input2.location ?? null,
23720
+ title: input2.title ?? null,
23721
+ hostId: input2.hostId ?? null,
23722
+ attributes: JSON.stringify(input2.attributes),
23723
+ firstSeen: now,
23724
+ lastSeen: now
23725
+ };
23726
+ }
23727
+ function toSourceProjectRow(input2, id, now) {
23728
+ return {
23729
+ id,
23730
+ url: input2.url,
23731
+ name: input2.name ?? null,
23732
+ attributes: JSON.stringify(input2.attributes),
23733
+ firstSeen: now,
23734
+ lastSeen: now
23735
+ };
23736
+ }
23737
+ function toAuditEventRow(input2) {
23738
+ return {
23739
+ id: input2.id,
23740
+ parentId: input2.parentId ?? null,
23741
+ rootSessionId: input2.rootSessionId ?? null,
23742
+ eventType: input2.eventType,
23743
+ hostId: input2.hostId ?? null,
23744
+ harnessId: input2.harnessId ?? null,
23745
+ sourceProjectId: input2.sourceProjectId ?? null,
23746
+ startedAt: isoToEpochMillis(input2.startedAt),
23747
+ endedAt: input2.endedAt ? isoToEpochMillis(input2.endedAt) : null,
23748
+ severity: input2.severity ?? null,
23749
+ priority: input2.priority ?? null,
23750
+ content: input2.content ?? null,
23751
+ contentHash: input2.contentHash ?? null,
23752
+ attributes: input2.attributes ? JSON.stringify(input2.attributes) : null
23753
+ };
23754
+ }
23755
+ function toClassifiedDataRow(input2, id) {
23756
+ return {
23757
+ id,
23758
+ class: input2.class,
23759
+ label: input2.label ?? null,
23760
+ attributes: input2.attributes ? JSON.stringify(input2.attributes) : null
23761
+ };
23762
+ }
23763
+ function toInspectionDefinitionRow(input2, id) {
23764
+ return {
23765
+ id,
23766
+ ruleId: input2.ruleId,
23767
+ name: input2.name,
23768
+ category: input2.category,
23769
+ severity: input2.severity,
23770
+ definition: input2.definition,
23771
+ version: input2.version
23772
+ };
23773
+ }
23774
+ function toInspectionFindingRow(input2) {
23775
+ return {
23776
+ id: input2.id,
23777
+ auditEventId: input2.auditEventId,
23778
+ inspectionDefinitionId: input2.inspectionDefinitionId,
23779
+ classifiedDataId: input2.classifiedDataId ?? null,
23780
+ spanStart: input2.span.start,
23781
+ spanEnd: input2.span.end,
23782
+ maskedMatch: input2.maskedMatch,
23783
+ actionTaken: input2.actionTaken,
23784
+ confidence: input2.confidence,
23785
+ findingKey: input2.findingKey ?? null,
23786
+ firstDetectedAt: input2.firstDetectedAt ? isoToEpochMillis(input2.firstDetectedAt) : null
23787
+ };
23788
+ }
23789
+ function toCaptureAttributes(event) {
23790
+ const metadata = event.metadata;
23791
+ return {
23792
+ source_tool: event.sourceTool,
23793
+ ...metadata?.repo !== void 0 ? { repo: metadata.repo } : {},
23794
+ ...metadata?.filePath !== void 0 ? { file_path: metadata.filePath } : {},
23795
+ ...metadata?.toolName !== void 0 ? { tool_name: metadata.toolName } : {},
23796
+ ...metadata?.gitignored !== void 0 ? { gitignored: metadata.gitignored } : {},
23797
+ ...metadata?.wholeFile !== void 0 ? { whole_file: metadata.wholeFile } : {},
23798
+ ...metadata?.correlationId !== void 0 ? { correlation_id: metadata.correlationId } : {},
23799
+ ...metadata?.traceId !== void 0 ? { trace_id: metadata.traceId } : {},
23800
+ ...metadata?.exceptionIds !== void 0 ? { exception_ids: metadata.exceptionIds } : {},
23801
+ ...metadata?.inspectionMs !== void 0 ? { inspection_ms: metadata.inspectionMs } : {},
23802
+ // `model`/`turnIndex` have no dedicated CaptureAttributes field (no writer
23803
+ // has ever populated either), but every legacy metadata key still rides
23804
+ // the bag rather than being silently dropped — CaptureAttributes'
23805
+ // `.catchall(z.unknown())` carries the long tail.
23806
+ ...metadata?.model !== void 0 ? { model: metadata.model } : {},
23807
+ ...metadata?.turnIndex !== void 0 ? { turn_index: metadata.turnIndex } : {}
23808
+ };
23809
+ }
23810
+ function captureDefinitionVersion(finding) {
23811
+ return `capture/${finding.category}/${finding.severity}`;
23812
+ }
23813
+ function toCaptureDefinitionInput(finding) {
23814
+ return {
23815
+ ruleId: finding.ruleId,
23816
+ version: captureDefinitionVersion(finding),
23817
+ name: finding.ruleId,
23818
+ category: finding.category,
23819
+ severity: finding.severity,
23820
+ definition: JSON.stringify({ ruleId: finding.ruleId })
23821
+ };
23822
+ }
23823
+
23824
+ // ../../packages/schema/src/zod/managed.ts
23825
+ var MANAGED_SETTINGS_FILENAME = "managed-settings.json";
23826
+ var MANAGED_SETTINGS_SPEC_VERSION = 1;
23827
+ var ManagedSettingKey = external_exports.enum([
23828
+ "runMode",
23829
+ "historicalAccess",
23830
+ "vaultConsent",
23831
+ "vaultKeyCustody",
23832
+ "vaultInlineReveal",
23833
+ "modelJudgeConsent",
23834
+ "dataSharesInPlace",
23835
+ "redactFallback"
23836
+ ]).meta({ id: "ManagedSettingKey" });
23837
+ var ManagedSettingsValues = external_exports.object({
23838
+ runMode: external_exports.enum(["standalone", "attached"]).optional(),
23839
+ controlPlane: external_exports.object({
23840
+ endpoint: external_exports.string().min(1),
23841
+ label: external_exports.string().min(1).optional()
23842
+ }).optional(),
23843
+ historicalAccess: external_exports.enum(["full", "session-only"]).optional(),
23844
+ vaultConsent: external_exports.boolean().optional(),
23845
+ vaultKeyCustody: external_exports.enum(["file", "keychain"]).optional(),
23846
+ vaultInlineReveal: external_exports.enum(["masked", "full", "off"]).optional(),
23847
+ modelJudgeConsent: external_exports.boolean().optional(),
23848
+ dataSharesInPlace: external_exports.boolean().optional(),
23849
+ redactFallback: RedactFallback.optional()
23850
+ }).meta({ id: "ManagedSettingsValues" });
23851
+ var ManagedSettings = external_exports.object({
23852
+ specVersion: external_exports.number().int().positive().default(MANAGED_SETTINGS_SPEC_VERSION),
23853
+ // Shown on every locked control, so the user can tell an administrative
23854
+ // decision from a bug. Absent renders as a generic "your organization".
23855
+ organization: external_exports.string().min(1).optional(),
23856
+ // What the administrator pinned.
23857
+ values: ManagedSettingsValues.default({}),
23858
+ // Which of those the user may not change. A key here with no matching value
23859
+ // freezes whatever the user last chose; a value with no lock is a DEFAULT
23860
+ // the user may still override. The two are separable on purpose.
23861
+ lockedFields: external_exports.array(ManagedSettingKey).default([])
23862
+ }).meta({ id: "ManagedSettings" });
23863
+
23720
23864
  // ../../packages/schema/src/zod/project-files.ts
23721
23865
  var ProjectFileInput = external_exports.object({
23722
23866
  path: external_exports.string().min(1),
@@ -23962,10 +24106,12 @@ var DismissRecommendedActionResponse = external_exports.object({ id: external_ex
23962
24106
  var RecommendedActionIdParam = external_exports.object({ id: external_exports.string() });
23963
24107
 
23964
24108
  // ../../packages/schema/src/zod/settings-action.ts
24109
+ var HistorySyncConsentChoice = external_exports.enum(["granted", "revoked", "unchanged"]).meta({ id: "HistorySyncConsentChoice" });
24110
+ var ModelJudgeConsentChoice = external_exports.enum(["granted", "revoked", "unchanged"]).meta({ id: "ModelJudgeConsentChoice" });
23965
24111
  var SaveSettingsInput = external_exports.object({
23966
24112
  historicalAccess: external_exports.string(),
23967
- modelJudgeConsent: external_exports.boolean(),
23968
- historySyncConsent: external_exports.boolean(),
24113
+ modelJudgeConsent: ModelJudgeConsentChoice,
24114
+ historySyncConsent: HistorySyncConsentChoice,
23969
24115
  vaultConsent: external_exports.string(),
23970
24116
  vaultInlineReveal: external_exports.string()
23971
24117
  });
@@ -24115,9 +24261,9 @@ function deriveReviewReasons(trust, transports) {
24115
24261
  if (transports.includes("http") || transports.includes("ws")) reasons.push("plaintext_transport");
24116
24262
  return reasons;
24117
24263
  }
24118
- function buildReviewInfo(trust, transports) {
24264
+ function buildReviewInfo(trust, transports, decided) {
24119
24265
  const reasons = deriveReviewReasons(trust, transports);
24120
- return { needsReview: reasons.length > 0, reasons };
24266
+ return { needsReview: reasons.length > 0 && !decided, reasons };
24121
24267
  }
24122
24268
  function distinctTransports(transports) {
24123
24269
  return Array.from(new Set(transports));
@@ -24335,8 +24481,8 @@ function readControlPlaneCredential(settingsDir2, connection) {
24335
24481
  }
24336
24482
 
24337
24483
  // ../../packages/persistence/src/database.ts
24338
- import { randomUUID as randomUUID10 } from "crypto";
24339
- import { join as join4, sep } from "path";
24484
+ import { randomUUID as randomUUID11 } from "crypto";
24485
+ import { dirname as dirname2, join as join7, sep } from "path";
24340
24486
  import { DatabaseSync } from "node:sqlite";
24341
24487
 
24342
24488
  // ../../packages/persistence/src/ids.ts
@@ -24601,6 +24747,10 @@ function allRows(stmt, params) {
24601
24747
  if (Array.isArray(params)) return stmt.all(...params);
24602
24748
  return stmt.all(params);
24603
24749
  }
24750
+ function* iterateRows(stmt, params) {
24751
+ const rows = params === void 0 ? stmt.iterate() : Array.isArray(params) ? stmt.iterate(...params) : stmt.iterate(params);
24752
+ for (const row of rows) yield row;
24753
+ }
24604
24754
  function getRow(stmt, params) {
24605
24755
  if (params === void 0) return stmt.get();
24606
24756
  if (Array.isArray(params)) return stmt.get(...params);
@@ -25069,10 +25219,17 @@ function ensureSyncedAtColumn(db, table) {
25069
25219
  if (!columns.includes("sync_claimed_at")) {
25070
25220
  db.exec(`ALTER TABLE ${table} ADD COLUMN sync_claimed_at integer`);
25071
25221
  }
25222
+ if (!columns.includes("outbox_owed")) {
25223
+ db.exec(`ALTER TABLE ${table} ADD COLUMN outbox_owed integer`);
25224
+ }
25072
25225
  db.exec(
25073
25226
  `CREATE INDEX IF NOT EXISTS idx_audit_events_sync
25074
25227
  ON audit_events (event_type, synced_at, sync_claimed_at, started_at)`
25075
25228
  );
25229
+ db.exec(
25230
+ `CREATE INDEX IF NOT EXISTS idx_audit_outbox_owed
25231
+ ON audit_events (event_type, synced_at, sync_claimed_at, started_at) WHERE outbox_owed = 1`
25232
+ );
25076
25233
  db.exec(
25077
25234
  `CREATE INDEX IF NOT EXISTS idx_audit_claimed
25078
25235
  ON audit_events (sync_claimed_at) WHERE sync_claimed_at IS NOT NULL`
@@ -25177,7 +25334,6 @@ function decodeKeysetCursor(cursor) {
25177
25334
  // ../../packages/persistence/src/repositories/activity.ts
25178
25335
  var DAY_MS = 864e5;
25179
25336
  var LIVE_ACTIVITY_WINDOW_MS = 30 * 6e4;
25180
- var LAST_ACTIVITY_EXPR = `max(started_at, coalesce(ended_at, started_at))`;
25181
25337
  function defaultTimeZone() {
25182
25338
  try {
25183
25339
  return Intl.DateTimeFormat().resolvedOptions().timeZone;
@@ -25232,6 +25388,7 @@ var DB_EVENT_TYPE_TO_KIND = {
25232
25388
  error: "error",
25233
25389
  active: "active"
25234
25390
  };
25391
+ var TIMELINE_EVENT_TYPES = Object.keys(DB_EVENT_TYPE_TO_KIND).map((kind) => `'${kind}'`).join(", ");
25235
25392
  function safeParseStringArray(raw) {
25236
25393
  if (!raw) return [];
25237
25394
  const parsed2 = safeJson(raw, null);
@@ -25305,6 +25462,37 @@ var TIMELINE_COLUMNS = `
25305
25462
  json_extract(attributes, '$.targetId') AS target_id,
25306
25463
  json_extract(attributes, '$.internal') AS internal,
25307
25464
  json_extract(attributes, '$.flagged') AS flagged`;
25465
+ var LLM_USAGE_SELECT = `
25466
+ SELECT root_session_id AS sessionId,
25467
+ provider,
25468
+ model,
25469
+ service_tier AS serviceTier,
25470
+ coalesce(sum(input_tokens), 0) AS inputTokens,
25471
+ coalesce(sum(output_tokens), 0) AS outputTokens,
25472
+ coalesce(sum(cache_creation_input_tokens), 0) AS cacheCreationTokens,
25473
+ coalesce(sum(cache_read_input_tokens), 0) AS cacheReadTokens,
25474
+ coalesce(sum(ephemeral_1h_input_tokens), 0) AS ephemeral1hTokens,
25475
+ coalesce(sum(ephemeral_5m_input_tokens), 0) AS ephemeral5mTokens,
25476
+ coalesce(sum(web_search_requests), 0) AS webSearchRequests`;
25477
+ var LLM_USAGE_SCOPE = `event_type = 'llm_call' AND attributes IS NOT NULL AND root_session_id IS NOT NULL`;
25478
+ var LLM_USAGE_GROUP = `GROUP BY root_session_id, provider, model, service_tier`;
25479
+ function usageLeaves(rows) {
25480
+ return rows.map((row) => {
25481
+ const attributes = {
25482
+ input_tokens: row.inputTokens,
25483
+ output_tokens: row.outputTokens,
25484
+ cache_creation_input_tokens: row.cacheCreationTokens,
25485
+ cache_read_input_tokens: row.cacheReadTokens,
25486
+ ephemeral_1h_input_tokens: row.ephemeral1hTokens,
25487
+ ephemeral_5m_input_tokens: row.ephemeral5mTokens,
25488
+ web_search_requests: row.webSearchRequests
25489
+ };
25490
+ if (row.provider !== null) attributes.provider = row.provider;
25491
+ if (row.model !== null) attributes.model = row.model;
25492
+ if (row.serviceTier !== null) attributes.service_tier = row.serviceTier;
25493
+ return { sessionId: row.sessionId, attributes };
25494
+ });
25495
+ }
25308
25496
  var SESSION_ROOT = `event_type = 'session'`;
25309
25497
  var HAS_ACTIVITY = `EXISTS (
25310
25498
  SELECT 1 FROM audit_events c
@@ -25330,16 +25518,17 @@ var SqliteActivityRepository = class {
25330
25518
  const liveThreshold = this.now() - LIVE_ACTIVITY_WINDOW_MS;
25331
25519
  const liveNow = countScalar(
25332
25520
  this.db,
25333
- `SELECT count(*) AS n FROM audit_events s
25521
+ `SELECT count(*) AS n FROM audit_events s INDEXED BY sqlite_autoindex_audit_events_1
25334
25522
  WHERE s.event_type = 'session' AND s.ended_at IS NULL
25335
- AND max(
25336
- s.started_at,
25337
- coalesce(
25338
- (SELECT max(${LAST_ACTIVITY_EXPR}) FROM audit_events e WHERE e.root_session_id = s.id),
25339
- s.started_at
25340
- )
25341
- ) >= ?`,
25342
- [liveThreshold]
25523
+ AND s.id IN (
25524
+ SELECT id FROM audit_events WHERE event_type = 'session' AND started_at >= ?
25525
+ UNION
25526
+ SELECT root_session_id FROM audit_events INDEXED BY idx_audit_started_at
25527
+ WHERE started_at >= ?
25528
+ UNION
25529
+ SELECT root_session_id FROM audit_events INDEXED BY idx_audit_ended_at
25530
+ WHERE ended_at >= ?)`,
25531
+ [liveThreshold, liveThreshold, liveThreshold]
25343
25532
  );
25344
25533
  const toolCallsToday = countScalar(
25345
25534
  this.db,
@@ -25469,7 +25658,7 @@ var SqliteActivityRepository = class {
25469
25658
  this.db.prepare(
25470
25659
  `SELECT ${TIMELINE_COLUMNS}
25471
25660
  FROM audit_events
25472
- WHERE id = ? OR root_session_id = ?
25661
+ WHERE (id = ? OR root_session_id = ?) AND event_type IN (${TIMELINE_EVENT_TYPES})
25473
25662
  ORDER BY started_at ASC, id ASC`
25474
25663
  ),
25475
25664
  [sessionId, sessionId]
@@ -25482,14 +25671,14 @@ var SqliteActivityRepository = class {
25482
25671
  coalesce(sum(output_tokens), 0) AS output,
25483
25672
  coalesce(sum(cache_creation_input_tokens), 0) AS cache_creation,
25484
25673
  coalesce(sum(cache_read_input_tokens), 0) AS cache_read
25485
- FROM audit_events
25674
+ FROM audit_events INDEXED BY idx_audit_session_type
25486
25675
  WHERE root_session_id = ? AND event_type = 'llm_call'`
25487
25676
  ),
25488
25677
  [sessionId]
25489
25678
  ) ?? { input: 0, output: 0, cache_creation: 0, cache_read: 0 };
25490
25679
  const primaryModel = getRow(
25491
25680
  this.db.prepare(
25492
- `SELECT model, provider FROM audit_events
25681
+ `SELECT model, provider FROM audit_events INDEXED BY idx_audit_session_type
25493
25682
  WHERE root_session_id = ? AND event_type = 'llm_call'
25494
25683
  ORDER BY started_at ASC, id ASC
25495
25684
  LIMIT 1`
@@ -25500,7 +25689,7 @@ var SqliteActivityRepository = class {
25500
25689
  this.db.prepare(
25501
25690
  `SELECT coalesce(json_extract(attributes, '$.tool_name'), json_extract(attributes, '$.tool')) AS tool,
25502
25691
  count(*) AS n
25503
- FROM audit_events
25692
+ FROM audit_events INDEXED BY idx_audit_session
25504
25693
  WHERE root_session_id = ? AND event_type = 'tool_call'
25505
25694
  GROUP BY coalesce(json_extract(attributes, '$.tool_name'), json_extract(attributes, '$.tool'))`
25506
25695
  ),
@@ -25508,7 +25697,7 @@ var SqliteActivityRepository = class {
25508
25697
  );
25509
25698
  const modelRows = allRows(
25510
25699
  this.db.prepare(
25511
- `SELECT DISTINCT model FROM audit_events
25700
+ `SELECT DISTINCT model FROM audit_events INDEXED BY idx_audit_session_type
25512
25701
  WHERE root_session_id = ? AND event_type = 'llm_call' AND model IS NOT NULL AND model <> ''
25513
25702
  ORDER BY model`
25514
25703
  ),
@@ -25517,7 +25706,7 @@ var SqliteActivityRepository = class {
25517
25706
  const derivedModels = modelRows.map((r) => r.model);
25518
25707
  const commits = countScalar(
25519
25708
  this.db,
25520
- `SELECT count(*) AS n FROM audit_events
25709
+ `SELECT count(*) AS n FROM audit_events INDEXED BY idx_audit_session
25521
25710
  WHERE root_session_id = ? AND event_type = 'commit'`,
25522
25711
  [sessionId]
25523
25712
  );
@@ -25553,25 +25742,57 @@ var SqliteActivityRepository = class {
25553
25742
  return Promise.resolve(session);
25554
25743
  }
25555
25744
  /**
25556
- * Cross-session token report — every `llm_call` leaf (optionally windowed to
25557
- * `started_at >= fromMs`) grouped into per-session `SessionTokenReport`s, with
25558
- * USD cost DERIVED at read time via the shared `defaultCostModel` (never
25559
- * stored). `fromMs` lets the Activity page scope the usage panel to its
25560
- * selected time range; omit it for all-time (the CLI/TUI overview). The
25561
- * caller collapses these onto per-model rows with `aggregateTokenUsage`.
25745
+ * Cross-session token report — every `llm_call` in the store (or in a
25746
+ * `started_at >= fromMs` window, the Activity page's range) grouped per
25747
+ * session, with USD cost DERIVED at read time via the shared
25748
+ * `defaultCostModel` (never stored). The caller collapses these onto
25749
+ * per-model rows with `aggregateTokenUsage`.
25750
+ *
25751
+ * Grouped in SQL over `idx_audit_llm_usage` — one entry per call carrying
25752
+ * the members the rollup sums — and priced once per group, which is exact
25753
+ * (see LlmUsageRow). Reading the bags and folding them in JS measured 31 ms
25754
+ * for a seven-day window at 50k calls, and naming the VIRTUAL columns
25755
+ * against the table 40 ms, since each is a json_extract recomputed per row;
25756
+ * the index stores the values once, at write, and answers the same window in
25757
+ * 8.5 ms. `INDEXED BY` is deliberate: with or without ANALYZE statistics the
25758
+ * planner prefers the general event-type index and fetches every row to
25759
+ * recompute the columns it could have read. The index is one every open
25760
+ * store carries, since opening runs the migrations, so the hard requirement
25761
+ * `INDEXED BY` introduces is already met; token-rollup-plans.test.ts pins
25762
+ * the plan. All-time is a scan of the whole index — still one narrow entry
25763
+ * per call, no bag parsed.
25562
25764
  */
25563
25765
  tokenReports(fromMs) {
25564
- const leaves = this.readLlmCallLeaves(fromMs === void 0 ? {} : { fromMs });
25565
- return Promise.resolve(buildTokenReports(leaves, defaultCostModel));
25766
+ const rows = allRows(
25767
+ this.db.prepare(
25768
+ `${LLM_USAGE_SELECT}
25769
+ FROM audit_events INDEXED BY idx_audit_llm_usage
25770
+ WHERE ${LLM_USAGE_SCOPE}${fromMs === void 0 ? "" : " AND started_at >= ?"}
25771
+ ${LLM_USAGE_GROUP}`
25772
+ ),
25773
+ fromMs === void 0 ? void 0 : [fromMs]
25774
+ );
25775
+ return Promise.resolve(buildTokenReports(usageLeaves(rows), defaultCostModel));
25566
25776
  }
25567
25777
  /**
25568
- * One session's token report — its `llm_call` leaves grouped per (provider,
25569
- * model) with derived cost, or `null` when the session made no `llm_call`s
25570
- * (an empty/tool-only session). Feeds the session-detail pane's per-model
25571
- * breakdown + estimated cost.
25778
+ * One session's token report — its `llm_call`s grouped per (provider,
25779
+ * model, tier) with derived cost, or `null` when the session made no
25780
+ * `llm_call`s (an empty/tool-only session). Feeds the session-detail pane's
25781
+ * per-model breakdown + estimated cost. The same rollup as `tokenReports`,
25782
+ * seeking one root through a root-led `llm_call` index; the bag-reading fold
25783
+ * it replaces walked every `llm_call` in the store to find one session's.
25572
25784
  */
25573
25785
  tokenReportForSession(sessionId) {
25574
- const reports = buildTokenReports(this.readLlmCallLeaves({ sessionId }), defaultCostModel);
25786
+ const rows = allRows(
25787
+ this.db.prepare(
25788
+ `${LLM_USAGE_SELECT}
25789
+ FROM audit_events
25790
+ WHERE ${LLM_USAGE_SCOPE} AND root_session_id = ?
25791
+ ${LLM_USAGE_GROUP}`
25792
+ ),
25793
+ [sessionId]
25794
+ );
25795
+ const reports = buildTokenReports(usageLeaves(rows), defaultCostModel);
25575
25796
  return Promise.resolve(reports[0] ?? null);
25576
25797
  }
25577
25798
  /**
@@ -25595,42 +25816,6 @@ var SqliteActivityRepository = class {
25595
25816
  for (const row of rows) seen.add(toHarness(row.harness));
25596
25817
  return Promise.resolve([...seen]);
25597
25818
  }
25598
- /**
25599
- * The raw `llm_call` leaves (session id + parsed attribute bag) for the token
25600
- * rollups, optionally narrowed to one session and/or a `started_at >= fromMs`
25601
- * window. A leaf whose attributes blob is NULL or unparseable is skipped
25602
- * (best-effort read — a corrupt bag never breaks the report). `root_session_id`
25603
- * is the leaf's session (the reconciler sets parent_id = root_session_id).
25604
- */
25605
- readLlmCallLeaves(opts = {}) {
25606
- const conditions = ["event_type = 'llm_call'", "attributes IS NOT NULL"];
25607
- const params = [];
25608
- if (opts.sessionId !== void 0) {
25609
- conditions.push("root_session_id = ?");
25610
- params.push(opts.sessionId);
25611
- }
25612
- if (opts.fromMs !== void 0) {
25613
- conditions.push("started_at >= ?");
25614
- params.push(opts.fromMs);
25615
- }
25616
- const rows = allRows(
25617
- this.db.prepare(
25618
- `SELECT root_session_id AS sessionId, attributes
25619
- FROM audit_events
25620
- WHERE ${conditions.join(" AND ")}`
25621
- ),
25622
- params
25623
- );
25624
- return mapRowsTolerant(
25625
- rows.filter(
25626
- (row) => row.sessionId !== null
25627
- ),
25628
- (row) => ({
25629
- sessionId: row.sessionId,
25630
- attributes: JSON.parse(row.attributes)
25631
- })
25632
- );
25633
- }
25634
25819
  /**
25635
25820
  * Per-session turns/findings/shares + last-activity for a page of session ids,
25636
25821
  * in grouped queries (not one per row). An id with no matching rows still
@@ -25645,20 +25830,23 @@ var SqliteActivityRepository = class {
25645
25830
  const inClause = placeholders(sessionIds.length);
25646
25831
  const lastActivityRows = allRows(
25647
25832
  this.db.prepare(
25648
- `SELECT root_session_id AS id, max(${LAST_ACTIVITY_EXPR}) AS m FROM audit_events
25649
- WHERE root_session_id IN (${inClause})
25650
- GROUP BY root_session_id`
25833
+ `SELECT ids.value AS id,
25834
+ (SELECT max(started_at) FROM audit_events e WHERE e.root_session_id = ids.value) AS ms,
25835
+ (SELECT max(ended_at) FROM audit_events e
25836
+ WHERE e.root_session_id = ids.value AND e.ended_at IS NOT NULL) AS me
25837
+ FROM json_each(?) AS ids`
25651
25838
  ),
25652
- sessionIds
25839
+ [JSON.stringify(sessionIds)]
25653
25840
  );
25654
25841
  for (const row of lastActivityRows) {
25655
- if (row.id === null) continue;
25656
25842
  const entry = result.get(row.id);
25657
- if (entry && row.m !== null) entry.lastActivityMs = row.m;
25843
+ const last = Math.max(row.ms ?? 0, row.me ?? 0);
25844
+ if (entry && last > 0) entry.lastActivityMs = last;
25658
25845
  }
25659
25846
  const turnsRows = allRows(
25660
25847
  this.db.prepare(
25661
- `SELECT root_session_id AS id, count(*) AS n FROM audit_events
25848
+ `SELECT root_session_id AS id, count(*) AS n
25849
+ FROM audit_events INDEXED BY idx_audit_session_prompt
25662
25850
  WHERE root_session_id IN (${inClause}) AND event_type = 'prompt'
25663
25851
  GROUP BY root_session_id`
25664
25852
  ),
@@ -25673,7 +25861,7 @@ var SqliteActivityRepository = class {
25673
25861
  this.db.prepare(
25674
25862
  `SELECT root_session_id AS id,
25675
25863
  count(DISTINCT json_extract(attributes, '$.run_key')) AS n
25676
- FROM audit_events
25864
+ FROM audit_events INDEXED BY idx_audit_session_run_key
25677
25865
  WHERE root_session_id IN (${inClause}) AND event_type = 'llm_call'
25678
25866
  AND json_extract(attributes, '$.run_key') IS NOT NULL
25679
25867
  GROUP BY root_session_id`
@@ -25703,7 +25891,7 @@ var SqliteActivityRepository = class {
25703
25891
  this.db.prepare(
25704
25892
  `SELECT root_session_id AS id,
25705
25893
  count(DISTINCT json_extract(attributes, '$.destination')) AS n
25706
- FROM audit_events
25894
+ FROM audit_events INDEXED BY idx_audit_session_share
25707
25895
  WHERE root_session_id IN (${inClause}) AND event_type = 'share'
25708
25896
  GROUP BY root_session_id`
25709
25897
  ),
@@ -26732,7 +26920,6 @@ var LATEST_RESOLUTION_BY_KEY_SQL = `(
26732
26920
 
26733
26921
  // ../../packages/persistence/src/repositories/findings.ts
26734
26922
  var PREVIEW_INSTANCES_PER_GROUP = 200;
26735
- var SCAN_BATCH_ROWS = 1e3;
26736
26923
  var DEFAULT_LOCATIONS_LIMIT = 100;
26737
26924
  var LOCATION_RULE_IDS_CAP = 20;
26738
26925
  function compareLocationOrder(a, b) {
@@ -26761,6 +26948,25 @@ function deriveInstanceStatus(row) {
26761
26948
  latestResolutionStatus: row.latest_status
26762
26949
  });
26763
26950
  }
26951
+ function toFlatFindingRow(r) {
26952
+ return {
26953
+ id: r.id,
26954
+ ruleId: r.rule_id,
26955
+ category: r.category,
26956
+ severity: r.severity,
26957
+ maskedMatch: r.masked_match,
26958
+ actionTaken: r.action_taken,
26959
+ confidence: r.confidence,
26960
+ occurredAt: epochMillisToIso(r.occurred_at),
26961
+ sourceTool: r.source_tool,
26962
+ repo: r.repo ?? "",
26963
+ file: r.file ?? "",
26964
+ ...r.tool_name === null ? {} : { toolName: r.tool_name },
26965
+ eventId: r.event_id,
26966
+ ...r.session_id === null ? {} : { sessionId: r.session_id },
26967
+ status: deriveInstanceStatus(r)
26968
+ };
26969
+ }
26764
26970
  function encodeGroupCursor(group) {
26765
26971
  const payload = {
26766
26972
  sev: group.severity,
@@ -26836,7 +27042,7 @@ var SqliteFindingsRepository = class {
26836
27042
  this.db.prepare(
26837
27043
  `SELECT f.id, f.audit_event_id AS event_id, d.rule_id, d.category, d.severity,
26838
27044
  f.masked_match, f.action_taken, f.confidence, e.started_at AS occurred_at,
26839
- json_extract(e.attributes, '$.source_tool') AS source_tool,
27045
+ e.source_tool AS source_tool,
26840
27046
  e.event_type AS kind
26841
27047
  FROM audit_events e
26842
27048
  CROSS JOIN inspection_findings f ON f.audit_event_id = e.id
@@ -26944,56 +27150,11 @@ var SqliteFindingsRepository = class {
26944
27150
  predicate,
26945
27151
  params: sessionParams
26946
27152
  });
26947
- const rows = allRows(
26948
- this.db.prepare(
26949
- `SELECT id, rule_id, category, severity, masked_match, action_taken, confidence,
26950
- occurred_at, source_tool, repo, file, tool_name, event_id, session_id,
26951
- kind, finding_key, latest_status
26952
- FROM (
26953
- SELECT f.id AS id, d.rule_id AS rule_id, d.category AS category,
26954
- d.severity AS severity, f.masked_match AS masked_match,
26955
- f.action_taken AS action_taken, f.confidence AS confidence,
26956
- e.started_at AS occurred_at,
26957
- json_extract(e.attributes, '$.source_tool') AS source_tool,
26958
- json_extract(e.attributes, '$.repo') AS repo,
26959
- json_extract(e.attributes, '$.file_path') AS file,
26960
- json_extract(e.attributes, '$.tool_name') AS tool_name,
26961
- f.audit_event_id AS event_id, e.root_session_id AS session_id,
26962
- e.event_type AS kind, f.finding_key AS finding_key,
26963
- latest.status AS latest_status,
26964
- ROW_NUMBER() OVER (
26965
- PARTITION BY d.rule_id
26966
- ORDER BY e.started_at DESC, f.id DESC
26967
- ) AS rn
26968
- FROM inspection_findings f
26969
- JOIN audit_events e ON e.id = f.audit_event_id
26970
- JOIN inspection_definitions d ON d.id = f.inspection_definition_id
26971
- LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
26972
- ON latest.finding_key = f.finding_key
26973
- ${predicate}
26974
- )
26975
- WHERE rn <= :cap
26976
- ORDER BY occurred_at DESC, id DESC`
26977
- ),
26978
- { cap: PREVIEW_INSTANCES_PER_GROUP, ...sessionParams }
26979
- );
26980
- const groupable = rows.map((r) => ({
26981
- id: r.id,
26982
- ruleId: r.rule_id,
26983
- category: r.category,
26984
- severity: r.severity,
26985
- maskedMatch: r.masked_match,
26986
- actionTaken: r.action_taken,
26987
- confidence: r.confidence,
26988
- occurredAt: epochMillisToIso(r.occurred_at),
26989
- sourceTool: r.source_tool,
26990
- repo: r.repo ?? "",
26991
- file: r.file ?? "",
26992
- ...r.tool_name === null ? {} : { toolName: r.tool_name },
26993
- eventId: r.event_id,
26994
- ...r.session_id === null ? {} : { sessionId: r.session_id },
26995
- status: deriveInstanceStatus(r)
26996
- }));
27153
+ const rows = this.previewRows(aggregates, {
27154
+ sessionId: query.sessionId,
27155
+ from: query.from
27156
+ });
27157
+ const groupable = rows.map(toFlatFindingRow);
26997
27158
  const allGroups = buildFindingGroups(groupable, { aggregates });
26998
27159
  const filterOpts = {
26999
27160
  severity: query.severity,
@@ -27079,8 +27240,10 @@ var SqliteFindingsRepository = class {
27079
27240
  *
27080
27241
  * The scan runs from the top of the scope on every request, not from the
27081
27242
  * cursor: `totals` and `facets` describe the whole filtered scope and must not
27082
- * move as the caller pages. Rows are pulled in batches so memory stays flat
27083
- * while the counting runs, and only the page itself is retained.
27243
+ * move as the caller pages. Rows come off ONE statement, iterated rather
27244
+ * than materialized (`scanFindingRows`), so memory stays flat while the
27245
+ * counting runs — a generator streaming the index order, not a sequence of
27246
+ * fetched batches; only the page itself is retained.
27084
27247
  */
27085
27248
  listFindingInstances(query) {
27086
27249
  const opts = {
@@ -27096,6 +27259,10 @@ var SqliteFindingsRepository = class {
27096
27259
  };
27097
27260
  const limit = query.limit ?? DEFAULT_FLAT_FINDINGS_LIMIT;
27098
27261
  const cursor = query.cursor === void 0 ? null : decodeKeysetCursor(query.cursor);
27262
+ const isPastCursor = cursor === null ? () => true : (row) => {
27263
+ const rowMs = isoToEpochMillis(row.occurredAt);
27264
+ return rowMs <= cursor.startedAtMs && (rowMs < cursor.startedAtMs || row.id < cursor.id);
27265
+ };
27099
27266
  const accumulator = createInstanceFacetAccumulator(opts);
27100
27267
  const items = [];
27101
27268
  let total = 0;
@@ -27108,6 +27275,7 @@ var SqliteFindingsRepository = class {
27108
27275
  accumulator.add(row);
27109
27276
  if (!matchesInstanceFilters(row, opts)) continue;
27110
27277
  total += 1;
27278
+ if (!isPastCursor(row)) continue;
27111
27279
  if (items.length < limit) {
27112
27280
  items.push(toInstanceDetail(row));
27113
27281
  last = row;
@@ -27116,15 +27284,6 @@ var SqliteFindingsRepository = class {
27116
27284
  }
27117
27285
  }
27118
27286
  const nextCursor = hasMore && last ? encodeKeysetCursor({ startedAtMs: isoToEpochMillis(last.occurredAt), id: last.id }) : null;
27119
- if (cursor !== null) {
27120
- const resumed = this.pageAfter(cursor, opts, limit, query);
27121
- return Promise.resolve({
27122
- totals: { findings: total },
27123
- facets: accumulator.facets(),
27124
- items: resumed.items,
27125
- nextCursor: resumed.nextCursor
27126
- });
27127
- }
27128
27287
  return Promise.resolve({
27129
27288
  totals: { findings: total },
27130
27289
  facets: accumulator.facets(),
@@ -27132,35 +27291,6 @@ var SqliteFindingsRepository = class {
27132
27291
  nextCursor
27133
27292
  });
27134
27293
  }
27135
- /**
27136
- * The page of matching rows strictly after `cursor`. Separate from the
27137
- * counting pass because that one starts at the top of the scope by design;
27138
- * this one narrows the scan with the same keyset predicate the activity list
27139
- * uses, so a later page costs less than the first rather than more.
27140
- */
27141
- pageAfter(cursor, opts, limit, query) {
27142
- const items = [];
27143
- let last;
27144
- let hasMore = false;
27145
- for (const row of this.scanFindingRows({
27146
- sessionId: query.sessionId,
27147
- from: query.from,
27148
- after: cursor
27149
- })) {
27150
- if (!matchesInstanceFilters(row, opts)) continue;
27151
- if (items.length < limit) {
27152
- items.push(toInstanceDetail(row));
27153
- last = row;
27154
- } else {
27155
- hasMore = true;
27156
- break;
27157
- }
27158
- }
27159
- return {
27160
- items,
27161
- nextCursor: hasMore && last ? encodeKeysetCursor({ startedAtMs: isoToEpochMillis(last.occurredAt), id: last.id }) : null
27162
- };
27163
- }
27164
27294
  /**
27165
27295
  * The same findings folded by location: repository, then file within it.
27166
27296
  *
@@ -27243,25 +27373,111 @@ var SqliteFindingsRepository = class {
27243
27373
  });
27244
27374
  }
27245
27375
  /**
27246
- * Every finding in scope as a FlatFindingRow, newest first, pulled in batches.
27376
+ * Each group's newest instances, for the table's expanded rows.
27377
+ *
27378
+ * ONE index-ordered scan with early termination, and the shape is the point.
27379
+ * The natural spelling — `ROW_NUMBER() OVER (PARTITION BY rule_id ORDER BY
27380
+ * started_at DESC)` then `WHERE rn <= cap` — sorts EVERY finding in scope
27381
+ * through a temp B-tree to keep a bounded preview of each group, and then
27382
+ * sorts the survivors again for the page order. Both sorts grow with the
27383
+ * store while the answer does not.
27384
+ *
27385
+ * Instead the scan walks `audit_events` newest-first off `idx_audit_started_at`
27386
+ * (or the session or window index the scope names — see `findingScanSql`),
27387
+ * which is already the order the page wants, and keeps rows per rule until
27388
+ * each rule has as many as it can show. The aggregate the caller already holds
27389
+ * says how many that is: `min(instanceCount, PREVIEW_INSTANCES_PER_GROUP)`
27390
+ * per rule, summed, is the number of rows this scan has to find, and it stops
27391
+ * on the last one. That sum is bounded by `rules * PREVIEW_INSTANCES_PER_GROUP`
27392
+ * (8,000 at this repo's 40-rule bench corpus), not by a fixed row count — a
27393
+ * store with many firing rules widens it. The bound that DOES hold
27394
+ * unconditionally is the sorted form's floor: this scan visits at most as
27395
+ * many rows as `ROW_NUMBER() OVER (PARTITION BY rule_id …)` would have
27396
+ * sorted, and stops the moment every rule has its cap, where the sorted form
27397
+ * sorts the whole scope regardless. The true worst case — the rarest rule's
27398
+ * wanted instances sitting at the tail of the scope — is one pass over
27399
+ * everything in scope with a block sort of the id tie-break only, never a
27400
+ * sort of the scope, which is still that floor.
27401
+ *
27402
+ * A row whose rule the aggregate did not see is skipped: the two statements
27403
+ * run without a shared snapshot, so a capture landing between them can add a
27404
+ * rule here that has no counts there, and the counts are what the group is
27405
+ * built from.
27406
+ */
27407
+ previewRows(aggregates, scope) {
27408
+ const wanted = /* @__PURE__ */ new Map();
27409
+ let remaining = 0;
27410
+ for (const [ruleId, agg] of aggregates) {
27411
+ const n = Math.min(agg.instanceCount, PREVIEW_INSTANCES_PER_GROUP);
27412
+ wanted.set(ruleId, n);
27413
+ remaining += n;
27414
+ }
27415
+ const rows = [];
27416
+ if (remaining === 0) return rows;
27417
+ const { sql, params } = this.findingScanSql(scope);
27418
+ const taken = /* @__PURE__ */ new Map();
27419
+ for (const r of iterateRows(this.db.prepare(sql), params)) {
27420
+ const want = wanted.get(r.rule_id);
27421
+ if (want === void 0) continue;
27422
+ const have = taken.get(r.rule_id) ?? 0;
27423
+ if (have >= want) continue;
27424
+ taken.set(r.rule_id, have + 1);
27425
+ rows.push(r);
27426
+ remaining -= 1;
27427
+ if (remaining === 0) break;
27428
+ }
27429
+ return rows;
27430
+ }
27431
+ /**
27432
+ * Every finding in scope as a FlatFindingRow, newest first, streamed.
27247
27433
  *
27248
27434
  * A generator so a caller streams the scope without it ever being an array:
27249
27435
  * the flat list counts and facets the whole filtered scope, which on a large
27250
- * store is far more rows than any page. Each batch advances the same keyset
27251
- * predicate the page read uses, so the scan is a sequence of bounded reads
27252
- * rather than one unbounded result set.
27253
- *
27254
- * The latest-resolution lookup is the CORRELATED form, not the derived table
27255
- * the grouped path joins: only `status` is needed, idx_finding_resolution_key
27256
- * makes it a point lookup per row, and the derived table would re-materialize
27257
- * a window over the whole resolution table once per batch.
27436
+ * store is far more rows than any page. The rows come off ONE statement,
27437
+ * iterated rather than materialized, in the index order `findingScanSql`
27438
+ * arranges — so the scan is a single pass with a block sort of the id
27439
+ * tie-break only, never a sort of the scope, where a sequence of
27440
+ * keyset-bounded batches re-sorted everything below the cursor on every
27441
+ * batch and cost the square of the scope.
27258
27442
  *
27259
- * `scope` carries ONLY what no facet counts. A filter dimension narrowed here
27260
- * would be missing from its own facet, which is computed by excluding that
27261
- * dimension — see listFindingInstances.
27443
+ * `sessionId` and `from` carry ONLY what no facet counts — a filter
27444
+ * dimension narrowed here would be missing from its own facet, which is
27445
+ * computed by excluding that dimension (see listFindingInstances). There is
27446
+ * no `after`/cursor parameter: a keyset page is collected inline from this
27447
+ * same pass (`listFindingInstances`' `isPastCursor`) rather than by a second,
27448
+ * narrower statement, since the counting pass already visits every row a
27449
+ * page-2+ request would otherwise re-seek for.
27262
27450
  */
27263
27451
  *scanFindingRows(scope) {
27264
- const conditions = [`e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})`];
27452
+ const { sql, params } = this.findingScanSql(scope);
27453
+ for (const r of iterateRows(this.db.prepare(sql), params)) {
27454
+ yield toFlatFindingRow(r);
27455
+ }
27456
+ }
27457
+ /**
27458
+ * The one statement both instance-level scans run: every finding in scope,
27459
+ * joined to its event and definition, newest first.
27460
+ *
27461
+ * THE PLAN IS THE POINT, and two things in the SQL exist only to pin it —
27462
+ * the same two `recentFindings` documents at length, for the same reason:
27463
+ *
27464
+ * - **`+e.event_type`** makes the capture-kind predicate non-indexable, so
27465
+ * the planner cannot pick `idx_audit_type_t` and then sort. That index
27466
+ * yields `started_at` order per event type, not across the four, so
27467
+ * satisfying the ORDER BY from it would need a merge SQLite does not do.
27468
+ * Freed of it, the planner walks `idx_audit_started_at` backwards — or
27469
+ * `idx_audit_session` for a session scope, which is also `started_at`
27470
+ * ordered within the session — and the order falls out of the index.
27471
+ * - **`CROSS JOIN`** pins `audit_events` as the driving table. With plain
27472
+ * JOINs the planner drives from the findings and sorts everything.
27473
+ *
27474
+ * The latest-resolution lookup is the CORRELATED form: only `status` is
27475
+ * needed, `idx_finding_resolution_key_created` answers it with one backward
27476
+ * index probe per keyed row, and a derived table over the whole resolution
27477
+ * table would be materialized before the first row streamed.
27478
+ */
27479
+ findingScanSql(scope) {
27480
+ const conditions = [`+e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})`];
27265
27481
  const params = [];
27266
27482
  if (scope.sessionId !== void 0 && scope.sessionId !== "") {
27267
27483
  conditions.push("e.root_session_id = ?");
@@ -27275,58 +27491,24 @@ var SqliteFindingsRepository = class {
27275
27491
  d.severity AS severity, f.masked_match AS masked_match,
27276
27492
  f.action_taken AS action_taken, f.confidence AS confidence,
27277
27493
  e.started_at AS occurred_at,
27278
- json_extract(e.attributes, '$.source_tool') AS source_tool,
27279
- json_extract(e.attributes, '$.repo') AS repo,
27280
- json_extract(e.attributes, '$.file_path') AS file,
27281
- json_extract(e.attributes, '$.tool_name') AS tool_name,
27494
+ e.source_tool AS source_tool,
27495
+ e.repo AS repo,
27496
+ e.file_path AS file,
27497
+ e.tool_name AS tool_name,
27282
27498
  f.audit_event_id AS event_id, e.root_session_id AS session_id,
27283
27499
  e.event_type AS kind, f.finding_key AS finding_key,
27284
27500
  ${latestResolutionStatusSql("f")} AS latest_status
27285
- FROM inspection_findings f
27286
- JOIN audit_events e ON e.id = f.audit_event_id
27287
- JOIN inspection_definitions d ON d.id = f.inspection_definition_id
27501
+ FROM audit_events e
27502
+ CROSS JOIN inspection_findings f ON f.audit_event_id = e.id
27503
+ CROSS JOIN inspection_definitions d ON d.id = f.inspection_definition_id
27288
27504
  WHERE ${conditions.join(" AND ")}
27289
- AND (e.started_at < ? OR (e.started_at = ? AND f.id < ?))
27290
- ORDER BY e.started_at DESC, f.id DESC
27291
- LIMIT ?`;
27292
- let after = scope.after ?? { startedAtMs: Number.MAX_SAFE_INTEGER, id: "\uFFFF" };
27293
- for (; ; ) {
27294
- const rows = allRows(this.db.prepare(sql), [
27295
- ...params,
27296
- after.startedAtMs,
27297
- after.startedAtMs,
27298
- after.id,
27299
- SCAN_BATCH_ROWS
27300
- ]);
27301
- for (const r of rows) {
27302
- yield {
27303
- id: r.id,
27304
- ruleId: r.rule_id,
27305
- category: r.category,
27306
- severity: r.severity,
27307
- maskedMatch: r.masked_match,
27308
- actionTaken: r.action_taken,
27309
- confidence: r.confidence,
27310
- occurredAt: epochMillisToIso(r.occurred_at),
27311
- sourceTool: r.source_tool,
27312
- repo: r.repo ?? "",
27313
- file: r.file ?? "",
27314
- ...r.tool_name === null ? {} : { toolName: r.tool_name },
27315
- eventId: r.event_id,
27316
- ...r.session_id === null ? {} : { sessionId: r.session_id },
27317
- status: deriveInstanceStatus(r)
27318
- };
27319
- }
27320
- if (rows.length < SCAN_BATCH_ROWS) return;
27321
- const lastRow = rows[rows.length - 1];
27322
- if (lastRow === void 0) return;
27323
- after = { startedAtMs: lastRow.occurred_at, id: lastRow.id };
27324
- }
27505
+ ORDER BY e.started_at DESC, f.id DESC`;
27506
+ return { sql, params };
27325
27507
  }
27326
27508
  groupAggregates(withSearchText, scope) {
27327
- const innerSearchColumns = withSearchText ? `, group_concat(DISTINCT json_extract(e.attributes, '$.repo')) AS repos,
27328
- group_concat(DISTINCT json_extract(e.attributes, '$.file_path')) AS files,
27329
- group_concat(DISTINCT 'via ' || json_extract(e.attributes, '$.tool_name')) AS tool_names` : `, NULL AS repos, NULL AS files, NULL AS tool_names`;
27509
+ const innerSearchColumns = withSearchText ? `, group_concat(DISTINCT e.repo) AS repos,
27510
+ group_concat(DISTINCT e.file_path) AS files,
27511
+ group_concat(DISTINCT 'via ' || e.tool_name) AS tool_names` : `, NULL AS repos, NULL AS files, NULL AS tool_names`;
27330
27512
  const rows = this.db.prepare(
27331
27513
  `SELECT rule_id,
27332
27514
  sum(tuple_count) AS instance_count,
@@ -27344,7 +27526,7 @@ var SqliteFindingsRepository = class {
27344
27526
  coalesce(latest.status, '') AS status_tuple,
27345
27527
  count(*) AS tuple_count,
27346
27528
  max(e.started_at) AS latest_at,
27347
- group_concat(DISTINCT json_extract(e.attributes, '$.source_tool')) AS source_tools,
27529
+ group_concat(DISTINCT e.source_tool) AS source_tools,
27348
27530
  group_concat(DISTINCT f.action_taken) AS actions_taken
27349
27531
  ${innerSearchColumns}
27350
27532
  FROM inspection_findings f
@@ -27475,6 +27657,8 @@ function isoDay(ms) {
27475
27657
  // ../../packages/persistence/src/repositories/history-sync.ts
27476
27658
  var STRUCTURAL_EVENT_TYPES = ["session", "llm_call", "tool_call"];
27477
27659
  var TYPE_LIST = STRUCTURAL_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
27660
+ var OUTBOX_CAPTURE_EVENT_TYPES = ["prompt", "response", "tool_use"];
27661
+ var CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
27478
27662
  var SKIPPED = -1;
27479
27663
  var ROW_COLUMNS = `id,
27480
27664
  parent_id AS parentId,
@@ -27514,6 +27698,20 @@ var SqliteHistorySyncRepository = class {
27514
27698
  ORDER BY (event_type = 'session') DESC, started_at
27515
27699
  LIMIT :limit`
27516
27700
  );
27701
+ this.captureRowsStmt = db.prepare(
27702
+ `SELECT ${ROW_COLUMNS}
27703
+ FROM audit_events
27704
+ WHERE synced_at IS NULL
27705
+ AND sync_claimed_at IS NULL
27706
+ AND outbox_owed = 1
27707
+ AND event_type IN (${CAPTURE_TYPE_LIST})
27708
+ AND started_at < :before
27709
+ ORDER BY started_at
27710
+ LIMIT :limit`
27711
+ );
27712
+ this.markOwedStmt = db.prepare(
27713
+ `UPDATE audit_events SET outbox_owed = 1 WHERE id = :id AND synced_at IS NULL`
27714
+ );
27517
27715
  this.stampStmt = db.prepare(
27518
27716
  `UPDATE audit_events SET synced_at = :at, sync_claimed_at = NULL WHERE id = :id`
27519
27717
  );
@@ -27545,6 +27743,12 @@ var SqliteHistorySyncRepository = class {
27545
27743
  FROM audit_events
27546
27744
  WHERE event_type IN (${TYPE_LIST})`
27547
27745
  );
27746
+ this.captureSkipCountStmt = db.prepare(
27747
+ `SELECT COUNT(*) AS skipped
27748
+ FROM audit_events
27749
+ WHERE synced_at = ${String(SKIPPED)}
27750
+ AND event_type IN (${CAPTURE_TYPE_LIST})`
27751
+ );
27548
27752
  this.fingerprintStmt = db.prepare(
27549
27753
  `SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
27550
27754
  FROM history_sync WHERE id = 1`
@@ -27554,6 +27758,10 @@ var SqliteHistorySyncRepository = class {
27554
27758
  SET endpoint_fingerprint = :fingerprint, backlog_before = :backlogBefore
27555
27759
  WHERE id = 1`
27556
27760
  );
27761
+ this.disownCapturesStmt = db.prepare(
27762
+ `UPDATE audit_events SET outbox_owed = NULL
27763
+ WHERE outbox_owed IS NOT NULL AND event_type IN (${CAPTURE_TYPE_LIST})`
27764
+ );
27557
27765
  this.rearmStmt = db.prepare(
27558
27766
  `UPDATE audit_events SET synced_at = NULL
27559
27767
  WHERE synced_at > 0 AND event_type IN (${TYPE_LIST})`
@@ -27626,6 +27834,10 @@ var SqliteHistorySyncRepository = class {
27626
27834
  closeWindowStmt;
27627
27835
  releaseBoundaryStmt;
27628
27836
  freezeBoundaryStmt;
27837
+ captureRowsStmt;
27838
+ markOwedStmt;
27839
+ captureSkipCountStmt;
27840
+ disownCapturesStmt;
27629
27841
  partitionStmt;
27630
27842
  claimRowStmt;
27631
27843
  releaseRowStmt;
@@ -27659,6 +27871,34 @@ var SqliteHistorySyncRepository = class {
27659
27871
  pendingRows(sessionId, limit, before) {
27660
27872
  return allRows(this.rowsStmt, { sessionId, limit, before });
27661
27873
  }
27874
+ /**
27875
+ * Captures this machine still owes the deployment, oldest first.
27876
+ *
27877
+ * Selected by the `outbox_owed` marker the attached forward path writes, not
27878
+ * by a time window — see captureRowsStmt for why a window could not express
27879
+ * this. `before` is the grace window that leaves a just-recorded capture to
27880
+ * the live path.
27881
+ */
27882
+ pendingCaptureRows(limit, before) {
27883
+ return allRows(this.captureRowsStmt, { limit, before });
27884
+ }
27885
+ /**
27886
+ * Record that a capture is OWED to the deployment.
27887
+ *
27888
+ * Written by the attached forward path when a live send did not confirm
27889
+ * delivery, and read by the drain as the whole of its eligibility test. It is
27890
+ * a fact rather than an inference: the machine was attached, the send did not
27891
+ * land, so the row is owed — which no time window can state, because the same
27892
+ * window that holds the rows a past attachment left owed also holds every
27893
+ * capture recorded while the machine was DETACHED, and those were never
27894
+ * offered to anyone.
27895
+ *
27896
+ * Idempotent, and never un-set: `markSynced` settling the row is what takes it
27897
+ * out of the drain's read.
27898
+ */
27899
+ markCaptureOwed(id) {
27900
+ this.markOwedStmt.run({ id });
27901
+ }
27662
27902
  /** Record delivery. Called only AFTER the far side has accepted the rows. */
27663
27903
  markSynced(ids, atMs) {
27664
27904
  this.stampAll(ids, atMs);
@@ -27742,10 +27982,12 @@ var SqliteHistorySyncRepository = class {
27742
27982
  this.countsStmt,
27743
27983
  { before }
27744
27984
  );
27985
+ const captures = getRow(this.captureSkipCountStmt);
27745
27986
  return {
27746
27987
  pending: row?.pending ?? 0,
27747
27988
  sent: row?.sent ?? 0,
27748
- skipped: row?.skipped ?? 0
27989
+ skipped: row?.skipped ?? 0,
27990
+ capturesSkipped: captures?.skipped ?? 0
27749
27991
  };
27750
27992
  }
27751
27993
  /**
@@ -27786,7 +28028,11 @@ var SqliteHistorySyncRepository = class {
27786
28028
  withTransaction(
27787
28029
  this.db,
27788
28030
  () => {
28031
+ const previous = getRow(this.fingerprintStmt)?.fingerprint;
27789
28032
  this.rearmStmt.run();
28033
+ if (previous !== null && previous !== void 0 && previous !== fingerprint) {
28034
+ this.disownCapturesStmt.run();
28035
+ }
27790
28036
  this.setFingerprintStmt.run({ fingerprint, backlogBefore });
27791
28037
  },
27792
28038
  "IMMEDIATE"
@@ -27983,7 +28229,256 @@ var SqliteInspectionFindingsRepository = class {
27983
28229
  };
27984
28230
 
27985
28231
  // ../../packages/persistence/src/repositories/installed-packs.ts
27986
- import { createHash as createHash2, randomUUID as randomUUID3 } from "crypto";
28232
+ import { createHash as createHash2, randomUUID as randomUUID4 } from "crypto";
28233
+
28234
+ // ../../packages/persistence/src/policy-floor.ts
28235
+ import { readFileSync as readFileSync5 } from "fs";
28236
+ import { join as join6 } from "path";
28237
+
28238
+ // ../../packages/persistence/src/local-layout.ts
28239
+ import { renameSync as renameSync3 } from "fs";
28240
+ import { mkdir } from "fs/promises";
28241
+ import { homedir } from "os";
28242
+ import { join as join4 } from "path";
28243
+ function defaultDataDir() {
28244
+ return join4(homedir(), ".aka");
28245
+ }
28246
+ function settingsDir(base = defaultDataDir()) {
28247
+ return join4(base, "settings");
28248
+ }
28249
+ function dataDir(base = defaultDataDir()) {
28250
+ return join4(base, "data");
28251
+ }
28252
+ function dbPath(base = defaultDataDir()) {
28253
+ return join4(dataDir(base), "aka.db");
28254
+ }
28255
+ async function ensureDataDir(dir = defaultDataDir()) {
28256
+ await mkdir(dir, { recursive: true, mode: DATA_DIR_MODE });
28257
+ tightenDir(dir);
28258
+ }
28259
+ function ensureLayoutDirSync(dir = defaultDataDir()) {
28260
+ ensureDataDirSync(dir);
28261
+ }
28262
+ function migrateLegacyLayout(base = defaultDataDir()) {
28263
+ const moves = [
28264
+ { name: "config.json", dest: settingsDir(base) },
28265
+ { name: "policy-cache.json", dest: dataDir(base) }
28266
+ ];
28267
+ for (const { name, dest } of moves) {
28268
+ try {
28269
+ ensureDataDirSync(dest);
28270
+ const moved = join4(dest, name);
28271
+ renameSync3(join4(base, name), moved);
28272
+ tightenFile(moved);
28273
+ } catch {
28274
+ }
28275
+ }
28276
+ }
28277
+
28278
+ // ../../packages/persistence/src/settings.ts
28279
+ import { readFileSync as readFileSync4 } from "fs";
28280
+ import { join as join5 } from "path";
28281
+
28282
+ // ../../packages/persistence/src/file-lock.ts
28283
+ import { randomUUID as randomUUID3 } from "crypto";
28284
+ import {
28285
+ closeSync,
28286
+ existsSync as existsSync2,
28287
+ openSync,
28288
+ readFileSync as readFileSync2,
28289
+ rmSync as rmSync5,
28290
+ statSync as statSync3,
28291
+ writeFileSync as writeFileSync2
28292
+ } from "fs";
28293
+ import { hostname as hostname3 } from "os";
28294
+ var PARK = new Int32Array(new SharedArrayBuffer(4));
28295
+
28296
+ // ../../packages/persistence/src/managed-settings.ts
28297
+ import { readFileSync as readFileSync3 } from "fs";
28298
+ import { posix, win32 } from "path";
28299
+ function managedSettingsPaths(platform2 = process.platform) {
28300
+ if (platform2 === "darwin") {
28301
+ return [
28302
+ posix.join("/Library", "Application Support", "AKASecurity", MANAGED_SETTINGS_FILENAME),
28303
+ posix.join("/Library", "Managed Preferences", MANAGED_SETTINGS_FILENAME)
28304
+ ];
28305
+ }
28306
+ if (platform2 === "win32") {
28307
+ return [win32.join("C:\\", "ProgramData", "AKASecurity", MANAGED_SETTINGS_FILENAME)];
28308
+ }
28309
+ return [posix.join("/etc", "aka", MANAGED_SETTINGS_FILENAME)];
28310
+ }
28311
+ function readManagedSettings(paths = managedSettingsPaths()) {
28312
+ for (const path of paths) {
28313
+ let text;
28314
+ try {
28315
+ text = readFileSync3(path, "utf8");
28316
+ } catch {
28317
+ continue;
28318
+ }
28319
+ const record2 = parseJsonObject(text);
28320
+ if (!record2) continue;
28321
+ const parsed2 = ManagedSettings.safeParse(record2);
28322
+ if (parsed2.success) return parsed2.data;
28323
+ }
28324
+ return null;
28325
+ }
28326
+ function overlayManagedSettings(settings, managed, now = () => /* @__PURE__ */ new Date()) {
28327
+ if (!managed) return settings;
28328
+ const { values } = managed;
28329
+ const merged = { ...settings };
28330
+ if (values.runMode !== void 0) merged.runMode = values.runMode;
28331
+ if (values.controlPlane !== void 0) {
28332
+ merged.controlPlane = {
28333
+ ...values.controlPlane,
28334
+ // The administrator pinned WHICH deployment, not WHEN this machine
28335
+ // joined it. Keep the user's own attach time when the endpoint is
28336
+ // unchanged, so a managed machine does not appear to re-attach on every
28337
+ // read; stamp a fresh one when the administrator moved it.
28338
+ attachedAt: settings.controlPlane?.endpoint === values.controlPlane.endpoint ? settings.controlPlane.attachedAt : now().toISOString()
28339
+ };
28340
+ }
28341
+ if (values.historicalAccess !== void 0) merged.historicalAccess = values.historicalAccess;
28342
+ if (values.vaultKeyCustody !== void 0) merged.vaultKeyCustody = values.vaultKeyCustody;
28343
+ if (values.vaultInlineReveal !== void 0) merged.vaultInlineReveal = values.vaultInlineReveal;
28344
+ if (values.dataSharesInPlace !== void 0) merged.dataSharesInPlace = values.dataSharesInPlace;
28345
+ if (values.redactFallback !== void 0) merged.redactFallback = values.redactFallback;
28346
+ if (values.vaultConsent !== void 0) {
28347
+ merged.vaultConsent = values.vaultConsent ? (
28348
+ // Keep an existing valid grant so its acknowledgedAt survives; mint one
28349
+ // at the current version otherwise.
28350
+ settings.vaultConsent?.version === VAULT_CONSENT_VERSION ? settings.vaultConsent : { acknowledgedAt: now().toISOString(), version: VAULT_CONSENT_VERSION }
28351
+ ) : void 0;
28352
+ }
28353
+ if (values.modelJudgeConsent !== void 0) {
28354
+ merged.modelJudgeConsent = values.modelJudgeConsent ? settings.modelJudgeConsent?.payloadVersion === MODEL_JUDGE_PAYLOAD_VERSION ? settings.modelJudgeConsent : {
28355
+ acknowledgedAt: now().toISOString(),
28356
+ payloadVersion: MODEL_JUDGE_PAYLOAD_VERSION
28357
+ } : void 0;
28358
+ }
28359
+ return merged;
28360
+ }
28361
+
28362
+ // ../../packages/persistence/src/settings.ts
28363
+ var SETTINGS_FILENAME = "settings.json";
28364
+ function readWorkspaceSettings(base = defaultDataDir()) {
28365
+ return overlayManagedSettings(readUserSettings(base), readManagedSettings());
28366
+ }
28367
+ function readUserSettings(base) {
28368
+ const record2 = readJson(join5(settingsDir(base), SETTINGS_FILENAME));
28369
+ if (!record2) return defaultWorkspaceSettings();
28370
+ try {
28371
+ return WorkspaceSettings.parse(record2);
28372
+ } catch {
28373
+ return defaultWorkspaceSettings();
28374
+ }
28375
+ }
28376
+ function readJson(file2) {
28377
+ let text;
28378
+ try {
28379
+ text = readFileSync4(file2, "utf8");
28380
+ } catch {
28381
+ return null;
28382
+ }
28383
+ return parseJsonObject(text) ?? null;
28384
+ }
28385
+
28386
+ // ../../packages/persistence/src/policy-floor.ts
28387
+ function refusalMessage(pack, attempted, floor, refusal) {
28388
+ switch (refusal) {
28389
+ case "lock":
28390
+ return `refusing to re-assign '${pack}': its policy is set by the connected control plane`;
28391
+ case "disable":
28392
+ return `refusing to disable '${pack}': it is governed by the connected control plane`;
28393
+ case "floor":
28394
+ return `refusing to set '${pack}' to '${attempted ?? "unassigned"}': the connected control plane requires at least '${floor}'`;
28395
+ }
28396
+ }
28397
+ var PolicyFloorError = class extends Error {
28398
+ /** `namespace/packId` of the detection whose write was refused. */
28399
+ pack;
28400
+ /**
28401
+ * The archetype the caller asked for, or null when the write named none —
28402
+ * clearing the assignment, or switching the detection off.
28403
+ */
28404
+ attempted;
28405
+ /** The weakest archetype the control plane permits for this pack. */
28406
+ floor;
28407
+ refusal;
28408
+ constructor(pack, attempted, floor, refusal) {
28409
+ super(refusalMessage(pack, attempted, floor, refusal));
28410
+ this.name = "PolicyFloorError";
28411
+ this.pack = pack;
28412
+ this.attempted = attempted;
28413
+ this.floor = floor;
28414
+ this.refusal = refusal;
28415
+ }
28416
+ };
28417
+ function readCachedPolicyBundle(base = defaultDataDir()) {
28418
+ try {
28419
+ const raw = readFileSync5(join6(dataDir(base), POLICY_CACHE_FILENAME), "utf8");
28420
+ const parsed2 = JSON.parse(raw);
28421
+ if (typeof parsed2 !== "object" || parsed2 === null) return null;
28422
+ return PolicyBundle.parse(parsed2.bundle);
28423
+ } catch {
28424
+ return null;
28425
+ }
28426
+ }
28427
+ function indexEnabled(policies) {
28428
+ const byRuleId = /* @__PURE__ */ new Map();
28429
+ const byCategory = /* @__PURE__ */ new Map();
28430
+ for (const policy of policies) {
28431
+ if (!policy.enabled) continue;
28432
+ if ("ruleId" in policy.target) {
28433
+ if (!byRuleId.has(policy.target.ruleId)) byRuleId.set(policy.target.ruleId, policy.action);
28434
+ } else if (!byCategory.has(policy.target.category)) {
28435
+ byCategory.set(policy.target.category, policy.action);
28436
+ }
28437
+ }
28438
+ return { byRuleId, byCategory };
28439
+ }
28440
+ function hasAuthoredPolicy(policies, rules, byRuleId) {
28441
+ const ruleIds = new Set(rules.map((rule) => rule.id));
28442
+ const categories = new Set(rules.map((rule) => rule.category));
28443
+ const bundleNamesPack = rules.some((rule) => byRuleId.has(rule.id));
28444
+ return policies.some((policy) => {
28445
+ if (!policy.enabled || policy.provenance !== "authored") return false;
28446
+ return "ruleId" in policy.target ? ruleIds.has(policy.target.ruleId) : bundleNamesPack && categories.has(policy.target.category);
28447
+ });
28448
+ }
28449
+ function controlPlanePolicyFloor(rules, base = defaultDataDir()) {
28450
+ const floors = openControlPlaneFloors(base);
28451
+ return floors === null ? null : floors.floorFor(rules);
28452
+ }
28453
+ function openControlPlaneFloors(base = defaultDataDir()) {
28454
+ if (!isAttached(readWorkspaceSettings(base))) return null;
28455
+ const bundle = readCachedPolicyBundle(base);
28456
+ if (bundle === null) return null;
28457
+ const indexes = indexEnabled(bundle.policies);
28458
+ return { floorFor: (rules) => resolveFloor(rules, bundle.policies, indexes) };
28459
+ }
28460
+ function resolveFloor(rules, policies, { byRuleId, byCategory }) {
28461
+ let action = null;
28462
+ for (const rule of rules) {
28463
+ const resolved = byRuleId.get(rule.id) ?? byCategory.get(rule.category);
28464
+ if (resolved === void 0) continue;
28465
+ action = action === null ? resolved : strongerAction(action, resolved);
28466
+ }
28467
+ if (action === null) return null;
28468
+ return {
28469
+ floor: weakestBuiltinAtLeast(action),
28470
+ locked: hasAuthoredPolicy(policies, rules, byRuleId)
28471
+ };
28472
+ }
28473
+ function policyAssignmentRefusal(policyId, floor) {
28474
+ if (floor.locked) return "lock";
28475
+ const effective = policyId ?? DEFAULT_PACK_POLICY_ID;
28476
+ return isActionAtLeast(builtinPolicyToAction(effective), builtinPolicyToAction(floor.floor)) ? null : "floor";
28477
+ }
28478
+ function packEnablementRefusal(enabled, floor) {
28479
+ if (floor === null || enabled) return null;
28480
+ return "disable";
28481
+ }
27987
28482
 
27988
28483
  // ../../packages/persistence/src/semver.ts
27989
28484
  function parse3(version2) {
@@ -28077,8 +28572,19 @@ function ruleIdsOf(rulesJson) {
28077
28572
  return ids;
28078
28573
  }
28079
28574
  var SqliteInstalledPacksRepository = class {
28080
- constructor(db) {
28575
+ /**
28576
+ * `baseDir` is the `~/.aka` LAYOUT BASE, not the data dir — the control-plane
28577
+ * floor needs both halves of it (settings/ says whether this machine is
28578
+ * attached, data/ holds the cached bundle). It is optional because a caller
28579
+ * holding only a DatabaseSync — every test construction site, and any embedder
28580
+ * that opens the store itself — has no layout to point at, and such a caller
28581
+ * gets the pre-existing behaviour: no floor, no lock. Production threads it in
28582
+ * from `openLocalDatabase`, which is the single construction site that owns a
28583
+ * real `~/.aka`.
28584
+ */
28585
+ constructor(db, baseDir) {
28081
28586
  this.db = db;
28587
+ this.baseDir = baseDir;
28082
28588
  this.insertMissingStmt = db.prepare(
28083
28589
  `INSERT INTO installed_packs (id, namespace, pack_id, version, name, rules_json, enabled, created_at, updated_at)
28084
28590
  VALUES (:id, :namespace, :packId, :version, :name, :rulesJson, 1, :now, :now)
@@ -28100,11 +28606,17 @@ var SqliteInstalledPacksRepository = class {
28100
28606
  this.signatureStmt = db.prepare(
28101
28607
  `SELECT namespace, pack_id AS packId, version, rules_json AS rulesJson FROM available_packs`
28102
28608
  );
28609
+ this.packRulesStmt = db.prepare(
28610
+ `SELECT rules_json AS rulesJson FROM installed_packs
28611
+ WHERE namespace = ? AND pack_id = ?`
28612
+ );
28103
28613
  }
28104
28614
  db;
28615
+ baseDir;
28105
28616
  insertMissingStmt;
28106
28617
  upsertAvailableStmt;
28107
28618
  signatureStmt;
28619
+ packRulesStmt;
28108
28620
  /**
28109
28621
  * Record the running binary's detection inventory. Refreshes the
28110
28622
  * available_packs mirror (pruning packs the binary no longer ships) and
@@ -28146,7 +28658,7 @@ var SqliteInstalledPacksRepository = class {
28146
28658
  let behind = false;
28147
28659
  for (const row of rows) {
28148
28660
  const params = {
28149
- id: randomUUID3(),
28661
+ id: randomUUID4(),
28150
28662
  namespace: row.namespace,
28151
28663
  packId: row.packId,
28152
28664
  version: row.version,
@@ -28158,7 +28670,7 @@ var SqliteInstalledPacksRepository = class {
28158
28670
  if (stored === void 0 || !isMirrorDowngrade(row, stored)) {
28159
28671
  this.upsertAvailableStmt.run({
28160
28672
  ...params,
28161
- id: randomUUID3(),
28673
+ id: randomUUID4(),
28162
28674
  recordedBy: meta4?.recordedBy ?? null
28163
28675
  });
28164
28676
  } else {
@@ -28404,9 +28916,65 @@ var SqliteInstalledPacksRepository = class {
28404
28916
  // NOT on the hook path — so, unlike recordInventory, these surface errors to the
28405
28917
  // caller rather than swallowing them. Each returns whether a row matched, so the
28406
28918
  // caller can tell an edit from a no-such-detection.
28919
+ /**
28920
+ * The rules one installed pack owns, reduced to what a floor computation
28921
+ * reads. Display-tolerant parsing on purpose: a pack whose snapshot is
28922
+ * unreadable contributes no rules to a scan either, so it is not a detection
28923
+ * the control plane can be governing, and an empty list correctly imposes no
28924
+ * floor. Enabled state is deliberately not filtered — a disabled pack is one
28925
+ * the user can re-enable, and its assignment stays governed meanwhile.
28926
+ */
28927
+ packFloorRules(namespace, packId) {
28928
+ const row = getRow(this.packRulesStmt, [namespace, packId]);
28929
+ if (!row) return [];
28930
+ return parseRules(row.rulesJson).map((rule) => ({ id: rule.id, category: rule.category }));
28931
+ }
28932
+ /**
28933
+ * What the connected control plane imposes on one installed pack, or null on a
28934
+ * machine that is its own authority (standalone, no cached bundle, or a
28935
+ * repository constructed without a layout base).
28936
+ *
28937
+ * Exposed as a READ so a surface can render the constraint — grey out the
28938
+ * choices below the floor, mark a locked detection as locked — rather than
28939
+ * offer the user a picker whose selections it will then be told it may not
28940
+ * make. The refusal in `setPolicy` does not depend on any surface calling this.
28941
+ */
28942
+ policyFloor(namespace, packId) {
28943
+ if (this.baseDir === void 0) return null;
28944
+ return controlPlanePolicyFloor(this.packFloorRules(namespace, packId), this.baseDir);
28945
+ }
28946
+ /**
28947
+ * The same answer for several packs, keyed `namespace/packId` and carrying an
28948
+ * entry only for a pack the control plane actually governs.
28949
+ *
28950
+ * A surface listing every detection asks per pack, and asking through
28951
+ * `policyFloor` re-reads the settings, re-reads and re-parses the whole cached
28952
+ * bundle and rebuilds its indexes once per pack — the entire cost of one
28953
+ * answer, repeated for each row, on every render. This reads all of that once.
28954
+ * Packs whose rules the snapshot cannot produce simply contribute no entry,
28955
+ * exactly as the single-pack read returns null for them.
28956
+ */
28957
+ policyFloors(packs2) {
28958
+ const floors = /* @__PURE__ */ new Map();
28959
+ if (this.baseDir === void 0) return floors;
28960
+ const source = openControlPlaneFloors(this.baseDir);
28961
+ if (source === null) return floors;
28962
+ for (const pack of packs2) {
28963
+ const floor = source.floorFor(this.packFloorRules(pack.namespace, pack.packId));
28964
+ if (floor !== null) floors.set(`${pack.namespace}/${pack.packId}`, floor);
28965
+ }
28966
+ return floors;
28967
+ }
28407
28968
  /**
28408
28969
  * Assign (or clear, with null) the enforcement policy for one installed pack.
28409
- * `policyId` must be a known built-in id (monitor/warn/redact/block).
28970
+ * `policyId` must be a known built-in id (monitor/warn/redact/block/vault).
28971
+ *
28972
+ * On an ATTACHED machine the organization's bundle is a floor this refuses to
28973
+ * write below, and a detection the organization has authored a policy for is
28974
+ * refused outright — see policy-floor.ts for both, and for why the refusal is
28975
+ * a throw rather than a silently substituted value. This is the one device-local
28976
+ * write path for the assignment, so the check belongs here rather than on any
28977
+ * surface that offers the choice.
28410
28978
  */
28411
28979
  setPolicy(namespace, packId, policyId) {
28412
28980
  if (policyId !== null && !BuiltinPolicyId.safeParse(policyId).success) {
@@ -28414,14 +28982,38 @@ var SqliteInstalledPacksRepository = class {
28414
28982
  `Unknown policy '${policyId}'. Must be one of: ${KNOWN_BUILTIN_IDS.join(", ")}.`
28415
28983
  );
28416
28984
  }
28985
+ const requested = policyId;
28986
+ const floor = this.policyFloor(namespace, packId);
28987
+ if (floor !== null) {
28988
+ const refusal = policyAssignmentRefusal(requested, floor);
28989
+ if (refusal !== null) {
28990
+ throw new PolicyFloorError(`${namespace}/${packId}`, requested, floor.floor, refusal);
28991
+ }
28992
+ }
28417
28993
  const res = this.db.prepare(
28418
28994
  `UPDATE installed_packs SET policy_id = :policyId, updated_at = :now
28419
28995
  WHERE namespace = :namespace AND pack_id = :packId`
28420
28996
  ).run({ policyId, now: Date.now(), namespace, packId });
28421
28997
  return Number(res.changes) > 0;
28422
28998
  }
28423
- /** Enable or disable one installed pack. */
28999
+ /**
29000
+ * Enable or disable one installed pack.
29001
+ *
29002
+ * On an ATTACHED machine a detection the organization's bundle governs at all
29003
+ * may not be switched OFF here — see packEnablementRefusal for why that is not
29004
+ * merely another point below the floor, and why re-enabling stays open. Like
29005
+ * the assignment above, the check belongs at this write path rather than on a
29006
+ * surface: this is the one device-local writer of the column, and a refusal
29007
+ * that lived in a page would leave the CLI free.
29008
+ */
28424
29009
  setEnabled(namespace, packId, enabled) {
29010
+ const floor = this.policyFloor(namespace, packId);
29011
+ if (floor !== null) {
29012
+ const refusal = packEnablementRefusal(enabled, floor);
29013
+ if (refusal !== null) {
29014
+ throw new PolicyFloorError(`${namespace}/${packId}`, null, floor.floor, refusal);
29015
+ }
29016
+ }
28425
29017
  const res = this.db.prepare(
28426
29018
  `UPDATE installed_packs SET enabled = :enabled, updated_at = :now
28427
29019
  WHERE namespace = :namespace AND pack_id = :packId`
@@ -28507,7 +29099,7 @@ var SqliteInventoryRepository = class {
28507
29099
  };
28508
29100
 
28509
29101
  // ../../packages/persistence/src/repositories/inventory-assets.ts
28510
- import { randomUUID as randomUUID4 } from "crypto";
29102
+ import { randomUUID as randomUUID5 } from "crypto";
28511
29103
  var CATEGORY_ORDER = ["config", "skill", "mcp", "hook"];
28512
29104
  var VALID_HARNESS_IDS = new Set(HarnessId.options);
28513
29105
  var WORKTREE_CHECKOUT_FILTER = "(url IS NULL OR (url NOT LIKE '%/.claude/worktrees/%' AND url NOT LIKE '%\\.claude\\worktrees\\%'))";
@@ -28996,7 +29588,7 @@ var SqliteInventoryAssetsRepository = class {
28996
29588
  `INSERT INTO file_access_override (id, project_id, path, access, created_at, updated_at)
28997
29589
  VALUES (:id, :projectId, :path, :access, :now, :now)
28998
29590
  ON CONFLICT (project_id, path) DO UPDATE SET access = excluded.access, updated_at = excluded.updated_at`
28999
- ).run({ id: randomUUID4(), projectId, path, access, now: Date.now() });
29591
+ ).run({ id: randomUUID5(), projectId, path, access, now: Date.now() });
29000
29592
  }
29001
29593
  return true;
29002
29594
  }
@@ -29017,7 +29609,7 @@ var SqliteInventoryAssetsRepository = class {
29017
29609
  `INSERT INTO mcp_trust_override (id, asset_id, trust, created_at, updated_at)
29018
29610
  VALUES (:id, :assetId, :trust, :now, :now)
29019
29611
  ON CONFLICT (asset_id) DO UPDATE SET trust = excluded.trust, updated_at = excluded.updated_at`
29020
- ).run({ id: randomUUID4(), assetId, trust, now: Date.now() });
29612
+ ).run({ id: randomUUID5(), assetId, trust, now: Date.now() });
29021
29613
  }
29022
29614
  this.configRowsCache = void 0;
29023
29615
  return "ok";
@@ -29314,7 +29906,7 @@ var SqliteInventoryAssetsRepository = class {
29314
29906
  };
29315
29907
 
29316
29908
  // ../../packages/persistence/src/repositories/policies.ts
29317
- import { randomUUID as randomUUID5 } from "crypto";
29909
+ import { randomUUID as randomUUID6 } from "crypto";
29318
29910
  var SqlitePoliciesRepository = class {
29319
29911
  constructor(db) {
29320
29912
  this.db = db;
@@ -29349,7 +29941,7 @@ var SqlitePoliciesRepository = class {
29349
29941
  failOpenTransaction(this.db, () => {
29350
29942
  for (const [category, action] of Object.entries(DEFAULT_ACTIONS)) {
29351
29943
  stmt.run({
29352
- id: randomUUID5(),
29944
+ id: randomUUID6(),
29353
29945
  target: JSON.stringify({ category }),
29354
29946
  action,
29355
29947
  now: Date.now()
@@ -29369,7 +29961,7 @@ var SqlitePoliciesRepository = class {
29369
29961
  `INSERT INTO policies (id, scope, target, action, enabled, created_at, updated_at)
29370
29962
  VALUES (:id, 'global', :target, :action, 1, :now, :now)
29371
29963
  ON CONFLICT(scope, target) DO UPDATE SET action = excluded.action, enabled = 1, updated_at = excluded.updated_at`
29372
- ).run({ id: randomUUID5(), target: JSON.stringify({ category }), action, now });
29964
+ ).run({ id: randomUUID6(), target: JSON.stringify({ category }), action, now });
29373
29965
  }
29374
29966
  // Caps every global per-category policy currently set to block/redact down
29375
29967
  // to warn (see warn-era-cap.ts). Rule-targeted policies are untouched.
@@ -29437,7 +30029,7 @@ var SqlitePolicyCatalogRepository = class {
29437
30029
  };
29438
30030
 
29439
30031
  // ../../packages/persistence/src/repositories/project-files.ts
29440
- import { randomUUID as randomUUID6 } from "crypto";
30032
+ import { randomUUID as randomUUID7 } from "crypto";
29441
30033
  var SqliteProjectFilesRepository = class {
29442
30034
  constructor(db) {
29443
30035
  this.db = db;
@@ -29469,7 +30061,7 @@ var SqliteProjectFilesRepository = class {
29469
30061
  const stamp = Math.max(now, maxStamp + 1);
29470
30062
  for (const file2 of scan2.files) {
29471
30063
  this.upsertStmt.run({
29472
- id: randomUUID6(),
30064
+ id: randomUUID7(),
29473
30065
  projectId,
29474
30066
  path: file2.path,
29475
30067
  name: file2.name,
@@ -29483,9 +30075,9 @@ var SqliteProjectFilesRepository = class {
29483
30075
  };
29484
30076
 
29485
30077
  // ../../packages/persistence/src/repositories/resolutions.ts
29486
- import { randomUUID as randomUUID7 } from "crypto";
30078
+ import { randomUUID as randomUUID8 } from "crypto";
29487
30079
  var SqliteResolutionsRepository = class {
29488
- constructor(db, now = () => Date.now(), newId = () => randomUUID7()) {
30080
+ constructor(db, now = () => Date.now(), newId = () => randomUUID8()) {
29489
30081
  this.db = db;
29490
30082
  this.now = now;
29491
30083
  this.newId = newId;
@@ -29698,7 +30290,7 @@ var SqliteScanLedgerRepository = class {
29698
30290
  };
29699
30291
 
29700
30292
  // ../../packages/persistence/src/repositories/secret-vault.ts
29701
- import { randomUUID as randomUUID8 } from "crypto";
30293
+ import { randomUUID as randomUUID9 } from "crypto";
29702
30294
  function pageLimit(requested, fallback) {
29703
30295
  if (requested === void 0) return fallback;
29704
30296
  return Math.min(Math.max(1, Math.trunc(requested)), MAX_VAULT_PAGE_LIMIT);
@@ -29744,12 +30336,14 @@ var SELECT_COLUMNS = `
29744
30336
  ciphertext,
29745
30337
  nonce,
29746
30338
  auth_tag AS authTag,
30339
+ user_authorized AS userAuthorized,
29747
30340
  occurrence_count AS occurrenceCount,
29748
30341
  first_seen AS firstSeen,
29749
30342
  last_seen AS lastSeen`;
29750
30343
  function toRow(raw) {
29751
- const { provider, ...rest } = raw;
29752
- return provider === null ? rest : { ...rest, provider };
30344
+ const { provider, userAuthorized, ...rest } = raw;
30345
+ const row = { ...rest, userAuthorized: userAuthorized !== 0 };
30346
+ return provider === null ? row : { ...row, provider };
29753
30347
  }
29754
30348
  var SqliteSecretVaultRepository = class {
29755
30349
  constructor(db) {
@@ -29759,17 +30353,18 @@ var SqliteSecretVaultRepository = class {
29759
30353
  pointer_id, value_fingerprint, fingerprint_key_version, key_version,
29760
30354
  format_version, category, rule_id, masked_match, provider,
29761
30355
  ciphertext, nonce, auth_tag,
29762
- occurrence_count, first_seen, last_seen
30356
+ user_authorized, occurrence_count, first_seen, last_seen
29763
30357
  ) VALUES (
29764
30358
  :pointerId, :valueFingerprint, :fingerprintKeyVersion, :keyVersion,
29765
30359
  :formatVersion, :category, :ruleId, :maskedMatch, :provider,
29766
30360
  :ciphertext, :nonce, :authTag,
29767
- 1, :now, :now
30361
+ :userAuthorized, 1, :now, :now
29768
30362
  )`
29769
30363
  );
29770
30364
  this.bumpStmt = db.prepare(
29771
30365
  `UPDATE secret_vault
29772
- SET occurrence_count = occurrence_count + 1, last_seen = :now
30366
+ SET occurrence_count = occurrence_count + 1, last_seen = :now,
30367
+ user_authorized = max(user_authorized, :userAuthorized)
29773
30368
  WHERE value_fingerprint = :valueFingerprint`
29774
30369
  );
29775
30370
  this.byPointerStmt = db.prepare(
@@ -29789,6 +30384,7 @@ var SqliteSecretVaultRepository = class {
29789
30384
  SET value_fingerprint = :valueFingerprint, fingerprint_key_version = :fingerprintKeyVersion
29790
30385
  WHERE pointer_id = :pointerId`
29791
30386
  );
30387
+ this.deleteByPointerStmt = db.prepare(`DELETE FROM secret_vault WHERE pointer_id = :pointerId`);
29792
30388
  this.derefStmt = db.prepare(
29793
30389
  `INSERT INTO secret_vault_deref (id, pointer_id, at, target, reason, outcome, grant_id, pointer_count)
29794
30390
  VALUES (:id, :pointerId, :at, :target, :reason, :outcome, :grantId, :pointerCount)`
@@ -29802,6 +30398,7 @@ var SqliteSecretVaultRepository = class {
29802
30398
  listStmt;
29803
30399
  replaceCiphertextStmt;
29804
30400
  refreshFingerprintStmt;
30401
+ deleteByPointerStmt;
29805
30402
  derefStmt;
29806
30403
  /**
29807
30404
  * Vault a value, or record another sighting of one already vaulted. Keyed on
@@ -29810,6 +30407,11 @@ var SqliteSecretVaultRepository = class {
29810
30407
  * pointer, category and ciphertext, so the same secret always resolves to one
29811
30408
  * wire token. `minted` is true only when this call created the row.
29812
30409
  *
30410
+ * `userAuthorized` is the one field a repeat call may still change, and only
30411
+ * upwards: it records that a PERSON asked for this value to be replaced, and
30412
+ * the row is shared with every automatic path that vaults the same value. See
30413
+ * `bumpStmt` for why clearing it is the defect this shape exists to refuse.
30414
+ *
29813
30415
  * The read-then-write runs in one IMMEDIATE transaction so two concurrent
29814
30416
  * writers cannot both decide they are minting.
29815
30417
  */
@@ -29836,13 +30438,18 @@ var SqliteSecretVaultRepository = class {
29836
30438
  ciphertext: input2.ciphertext,
29837
30439
  nonce: input2.nonce,
29838
30440
  authTag: input2.authTag,
30441
+ userAuthorized: input2.userAuthorized === true ? 1 : 0,
29839
30442
  now
29840
30443
  })
29841
30444
  );
29842
30445
  minted = true;
29843
30446
  return;
29844
30447
  }
29845
- this.bumpStmt.run({ valueFingerprint: input2.valueFingerprint, now });
30448
+ this.bumpStmt.run({
30449
+ valueFingerprint: input2.valueFingerprint,
30450
+ userAuthorized: input2.userAuthorized === true ? 1 : 0,
30451
+ now
30452
+ });
29846
30453
  },
29847
30454
  "IMMEDIATE"
29848
30455
  );
@@ -29902,6 +30509,42 @@ var SqliteSecretVaultRepository = class {
29902
30509
  );
29903
30510
  return destroyed;
29904
30511
  }
30512
+ /**
30513
+ * Destroy the named entries and report WHICH ones went — the scoped
30514
+ * counterpart to `purgeAll`, for a caller that has already put those specific
30515
+ * values back where they came from. Ids the store does not hold are absent
30516
+ * from the answer rather than an error, so a set assembled from a stale read
30517
+ * is not a fault. The deref audit is left alone, exactly as the purge leaves
30518
+ * it.
30519
+ *
30520
+ * The ids come back rather than a count because the caller's next act is to
30521
+ * write a purge row per destroyed entry, and a record of destruction has to
30522
+ * be a record of what was really destroyed: a selection is a claim about a
30523
+ * read that has since gone stale, and auditing from it invents a purge for an
30524
+ * entry still sitting in the vault.
30525
+ *
30526
+ * One transaction over the whole set rather than a statement per id: the
30527
+ * caller hands this the result of a restore pass it has completed, and a
30528
+ * fault partway through must leave the vault as it was found rather than
30529
+ * destroying a prefix of it. The vault holds the only copy of what a pointer
30530
+ * stands for, so half a delete is not a state anything can recover from.
30531
+ */
30532
+ deleteByPointerIds(pointerIds) {
30533
+ if (pointerIds.length === 0) return [];
30534
+ const deleted = [];
30535
+ withTransaction(
30536
+ this.db,
30537
+ () => {
30538
+ for (const pointerId of pointerIds) {
30539
+ if (Number(this.deleteByPointerStmt.run({ pointerId }).changes) > 0) {
30540
+ deleted.push(pointerId);
30541
+ }
30542
+ }
30543
+ },
30544
+ "IMMEDIATE"
30545
+ );
30546
+ return deleted;
30547
+ }
29905
30548
  /**
29906
30549
  * Record (or re-stamp) one place a pointer has been written. One row per
29907
30550
  * (pointer, location); a re-sighting bumps last_seen. Best-effort bookkeeping
@@ -29914,7 +30557,7 @@ var SqliteSecretVaultRepository = class {
29914
30557
  VALUES (:id, :pointerId, :location, :kind, :now, :now)
29915
30558
  ON CONFLICT (pointer_id, location) DO UPDATE SET last_seen = :now`
29916
30559
  ).run({
29917
- id: randomUUID8(),
30560
+ id: randomUUID9(),
29918
30561
  pointerId: entry.pointerId,
29919
30562
  location: entry.location,
29920
30563
  kind: entry.kind,
@@ -30427,15 +31070,15 @@ var SqliteSecurityRepository = class {
30427
31070
  const from = now - RANGE_DAYS[range] * DAY_MS4;
30428
31071
  const rows = allRows(
30429
31072
  this.db.prepare(
30430
- `SELECT json_extract(e.attributes, '$.repo') AS repo, count(*) AS c
31073
+ `SELECT e.repo AS repo, count(*) AS c
30431
31074
  FROM inspection_findings f
30432
31075
  JOIN audit_events e ON e.id = f.audit_event_id
30433
31076
  WHERE e.started_at >= :from AND e.started_at < :to
30434
31077
  AND e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
30435
- AND json_extract(e.attributes, '$.repo') IS NOT NULL
30436
- AND json_extract(e.attributes, '$.repo') != ''
30437
- GROUP BY repo
30438
- ORDER BY c DESC, repo
31078
+ AND e.repo IS NOT NULL
31079
+ AND e.repo != ''
31080
+ GROUP BY e.repo
31081
+ ORDER BY c DESC, e.repo
30439
31082
  LIMIT :limit`
30440
31083
  ),
30441
31084
  { from, to: now, limit }
@@ -30497,7 +31140,7 @@ var SqliteSecurityRepository = class {
30497
31140
  `SELECT f.finding_key AS finding_key,
30498
31141
  d.rule_id AS rule_id,
30499
31142
  d.severity AS severity,
30500
- json_extract(e.attributes, '$.file_path') AS path,
31143
+ e.file_path AS path,
30501
31144
  COALESCE(f.first_detected_at, e.started_at) AS first_detected_at,
30502
31145
  latest.resolved_at AS latest_resolved_at
30503
31146
  FROM ${LATEST_RESOLUTION_BY_KEY_SQL} latest
@@ -30550,7 +31193,7 @@ var SqliteSecurityRepository = class {
30550
31193
  };
30551
31194
 
30552
31195
  // ../../packages/persistence/src/repositories/shares.ts
30553
- import { randomUUID as randomUUID9 } from "crypto";
31196
+ import { randomUUID as randomUUID10 } from "crypto";
30554
31197
  var MAX_EGRESS_CALL_SITES_PER_PROJECT = 5e3;
30555
31198
  var IN_CHUNK = 500;
30556
31199
  var KIND_ORDER = ["provider", "internal", "external", "ip"];
@@ -30638,7 +31281,7 @@ function buildSummary(dest, endpoints) {
30638
31281
  callSiteCount,
30639
31282
  transports: distinctTransports(transports),
30640
31283
  dataClasses: distinctDataClasses(dataClasses),
30641
- review: buildReviewInfo(dest.trust, transports),
31284
+ review: buildReviewInfo(dest.trust, transports, dest.overrideDecision !== null),
30642
31285
  network: dest.kind === "provider" ? null : parseNetwork(dest.networkJson),
30643
31286
  endpoints: endpoints.map(toEndpointSummary)
30644
31287
  };
@@ -30665,7 +31308,7 @@ function buildDetail(dest, endpoints, callSites) {
30665
31308
  lastSeen: new Date(lastSeenMs).toISOString(),
30666
31309
  transports: distinctTransports(transports),
30667
31310
  dataClasses: distinctDataClasses(endpoints.map((e) => e.dataClass)),
30668
- review: buildReviewInfo(dest.trust, transports),
31311
+ review: buildReviewInfo(dest.trust, transports, dest.overrideDecision !== null),
30669
31312
  network: dest.kind === "provider" ? null : parseNetwork(dest.networkJson),
30670
31313
  note: dest.note,
30671
31314
  endpoints: endpoints.map((ep) => ({
@@ -30694,7 +31337,11 @@ var SqliteSharesRepository = class {
30694
31337
  FROM share_destination d
30695
31338
  LEFT JOIN share_endpoint e ON e.destination_id = d.id
30696
31339
  AND e.transport IN ${PLAINTEXT_TRANSPORT_SQL}
30697
- WHERE d.trust IN ('unverified', 'ip') OR e.id IS NOT NULL`
31340
+ WHERE (d.trust IN ('unverified', 'ip') OR e.id IS NOT NULL)
31341
+ AND NOT EXISTS (
31342
+ SELECT 1 FROM egress_decision_override o
31343
+ WHERE o.host = d.host OR (o.destination_id = d.id AND o.host IS NULL)
31344
+ )`
30698
31345
  );
30699
31346
  const kindCounts = countBy(
30700
31347
  this.db,
@@ -30806,7 +31453,7 @@ var SqliteSharesRepository = class {
30806
31453
  (id, destination_id, host, decision, created_at, updated_at)
30807
31454
  VALUES (:id, :destinationId, :host, :decision, :now, :now)`
30808
31455
  ).run({
30809
- id: randomUUID9(),
31456
+ id: randomUUID10(),
30810
31457
  destinationId,
30811
31458
  host: dest.host,
30812
31459
  decision,
@@ -30955,7 +31602,7 @@ var SqliteSharesRepository = class {
30955
31602
  let destinationId = destIds.get(hit.host);
30956
31603
  if (destinationId === void 0) {
30957
31604
  destStmt.run({
30958
- id: randomUUID9(),
31605
+ id: randomUUID10(),
30959
31606
  kind: hit.kind,
30960
31607
  name: hit.name,
30961
31608
  host: hit.host,
@@ -30971,7 +31618,7 @@ var SqliteSharesRepository = class {
30971
31618
  let endpointId = endpointIds.get(endpointKey);
30972
31619
  if (endpointId === void 0) {
30973
31620
  endpointStmt.run({
30974
- id: randomUUID9(),
31621
+ id: randomUUID10(),
30975
31622
  destinationId,
30976
31623
  method: hit.method,
30977
31624
  transport: hit.transport,
@@ -30984,7 +31631,7 @@ var SqliteSharesRepository = class {
30984
31631
  endpointIds.set(endpointKey, endpointId);
30985
31632
  }
30986
31633
  siteStmt.run({
30987
- id: randomUUID9(),
31634
+ id: randomUUID10(),
30988
31635
  endpointId,
30989
31636
  project: input2.project,
30990
31637
  projectKey: input2.projectKey,
@@ -31349,6 +31996,7 @@ function purgeSampleData(db) {
31349
31996
  }
31350
31997
 
31351
31998
  // ../../packages/persistence/src/database.ts
31999
+ var CAPTURE_GRAIN = new Set(EventKind.options);
31352
32000
  var UNSAFE_TEST_ONLY_RAW_HANDLE = /* @__PURE__ */ Symbol(
31353
32001
  "aka.persistence.unsafeTestOnlyRawHandle"
31354
32002
  );
@@ -31396,7 +32044,7 @@ function backupLegacyStore(db, file2) {
31396
32044
  discardStore(file2, backup);
31397
32045
  return backup;
31398
32046
  }
31399
- function openAndInitialize(file2) {
32047
+ function openAndInitialize(file2, base) {
31400
32048
  let db = openWithPragmas(file2);
31401
32049
  try {
31402
32050
  if (isForeignSqliteLineage(db)) {
@@ -31409,7 +32057,7 @@ function openAndInitialize(file2) {
31409
32057
  applyMigrations(db, file2);
31410
32058
  tightenPerms(file2);
31411
32059
  const policies = new SqlitePoliciesRepository(db);
31412
- const installedPacks = new SqliteInstalledPacksRepository(db);
32060
+ const installedPacks = new SqliteInstalledPacksRepository(db, base);
31413
32061
  const repositories = {
31414
32062
  events: new SqliteEventsRepository(db),
31415
32063
  findings: new SqliteFindingsRepository(db),
@@ -31445,7 +32093,7 @@ function openAndInitialize(file2) {
31445
32093
  }
31446
32094
  function openLocalDatabase(dir) {
31447
32095
  ensureDataDirSync(dir);
31448
- const file2 = join4(dir, DB_FILENAME);
32096
+ const file2 = join7(dir, DB_FILENAME);
31449
32097
  reapStalePartials(file2);
31450
32098
  const {
31451
32099
  db,
@@ -31473,7 +32121,13 @@ function openLocalDatabase(dir) {
31473
32121
  inspectionDefinitions,
31474
32122
  inspectionFindings,
31475
32123
  configInventory
31476
- } = openAndInitialize(file2);
32124
+ } = openAndInitialize(
32125
+ file2,
32126
+ // `dir` is always `<base>/data` — every caller resolves it through
32127
+ // `dataDir()` — so its parent is the `~/.aka` base the layout splits into
32128
+ // settings/ and data/, and the pack-policy floor needs both halves.
32129
+ dirname2(dir)
32130
+ );
31477
32131
  function captureRowId(event) {
31478
32132
  return captureId(
31479
32133
  event.metadata?.sessionId ?? null,
@@ -31486,6 +32140,21 @@ function openLocalDatabase(dir) {
31486
32140
  historySync.markSynced([captureRowId(event)], atMs);
31487
32141
  });
31488
32142
  }
32143
+ function markCaptureOwed(event) {
32144
+ failOpenTransaction(db, () => {
32145
+ historySync.markCaptureOwed(captureRowId(event));
32146
+ });
32147
+ }
32148
+ function markAuditEventsDelivered(events2, atMs) {
32149
+ const stampable = events2.filter((event) => !CAPTURE_GRAIN.has(event.eventType));
32150
+ if (stampable.length === 0) return;
32151
+ failOpenTransaction(db, () => {
32152
+ historySync.markSynced(
32153
+ stampable.map((event) => event.id),
32154
+ atMs
32155
+ );
32156
+ });
32157
+ }
31489
32158
  function recordCapture(event, detected) {
31490
32159
  failOpenTransaction(db, () => {
31491
32160
  const sessionId = event.metadata?.sessionId;
@@ -31572,7 +32241,7 @@ function openLocalDatabase(dir) {
31572
32241
  const definitionId = definitionIds.get(`${finding.ruleId}@${finding.version}`);
31573
32242
  if (!definitionId) continue;
31574
32243
  inspectionFindings.insertFinding({
31575
- id: randomUUID10(),
32244
+ id: randomUUID11(),
31576
32245
  auditEventId: record2.scanEvent.id,
31577
32246
  inspectionDefinitionId: definitionId,
31578
32247
  span: finding.span,
@@ -31668,6 +32337,8 @@ function openLocalDatabase(dir) {
31668
32337
  inspectionFindings,
31669
32338
  recordCapture,
31670
32339
  markCaptureDelivered,
32340
+ markCaptureOwed,
32341
+ markAuditEventsDelivered,
31671
32342
  ensureInventory,
31672
32343
  recordConfigScan,
31673
32344
  recordProjectFiles,
@@ -31686,20 +32357,6 @@ function openLocalDatabase(dir) {
31686
32357
  };
31687
32358
  }
31688
32359
 
31689
- // ../../packages/persistence/src/file-lock.ts
31690
- import { randomUUID as randomUUID11 } from "crypto";
31691
- import {
31692
- closeSync,
31693
- existsSync as existsSync2,
31694
- openSync,
31695
- readFileSync as readFileSync2,
31696
- rmSync as rmSync5,
31697
- statSync as statSync3,
31698
- writeFileSync as writeFileSync2
31699
- } from "fs";
31700
- import { hostname as hostname3 } from "os";
31701
- var PARK = new Int32Array(new SharedArrayBuffer(4));
31702
-
31703
32360
  // ../../packages/persistence/src/finding-key.ts
31704
32361
  import { createHash as createHash3 } from "crypto";
31705
32362
  function normalizeFilePath(filePath) {
@@ -31712,13 +32369,13 @@ function computeFindingKey(input2) {
31712
32369
 
31713
32370
  // ../../packages/persistence/src/fingerprint.ts
31714
32371
  import { createHmac, randomBytes } from "crypto";
31715
- import { existsSync as existsSync3, readFileSync as readFileSync3 } from "fs";
31716
- import { join as join5 } from "path";
32372
+ import { existsSync as existsSync3, readFileSync as readFileSync6 } from "fs";
32373
+ import { join as join8 } from "path";
31717
32374
  import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
31718
32375
  var EXCEPTION_KEY_FILENAME = "exception.key";
31719
32376
  var KEY_MATERIAL_BYTES = 32;
31720
32377
  function keyFilePath(dataDir2) {
31721
- return join5(dataDir2, EXCEPTION_KEY_FILENAME);
32378
+ return join8(dataDir2, EXCEPTION_KEY_FILENAME);
31722
32379
  }
31723
32380
  function parseKeyFile(raw) {
31724
32381
  const parsed2 = JSON.parse(raw);
@@ -31756,7 +32413,7 @@ var FloorUnreadableError = class extends Error {
31756
32413
  }
31757
32414
  };
31758
32415
  function storedKeyVersionFloor(dataDir2) {
31759
- const file2 = join5(dataDir2, DB_FILENAME);
32416
+ const file2 = join8(dataDir2, DB_FILENAME);
31760
32417
  if (!existsSync3(file2)) return 0;
31761
32418
  let db;
31762
32419
  try {
@@ -31811,7 +32468,7 @@ function occupantMessage(file2, kind) {
31811
32468
  function readFingerprintKey(dataDir2) {
31812
32469
  let raw;
31813
32470
  try {
31814
- raw = readFileSync3(keyFilePath(dataDir2), "utf8");
32471
+ raw = readFileSync6(keyFilePath(dataDir2), "utf8");
31815
32472
  } catch (err) {
31816
32473
  if (err.code === "ENOENT") return null;
31817
32474
  throw err instanceof Error ? err : new Error(String(err));
@@ -31835,143 +32492,12 @@ function fingerprintValue(key, raw) {
31835
32492
 
31836
32493
  // ../../packages/persistence/src/history-preview.ts
31837
32494
  import { existsSync as existsSync4 } from "fs";
31838
- import { join as join6 } from "path";
32495
+ import { join as join9 } from "path";
31839
32496
  import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
31840
32497
 
31841
- // ../../packages/persistence/src/local-layout.ts
31842
- import { renameSync as renameSync3 } from "fs";
31843
- import { mkdir } from "fs/promises";
31844
- import { homedir } from "os";
31845
- import { join as join7 } from "path";
31846
- function defaultDataDir() {
31847
- return join7(homedir(), ".aka");
31848
- }
31849
- function settingsDir(base = defaultDataDir()) {
31850
- return join7(base, "settings");
31851
- }
31852
- function dataDir(base = defaultDataDir()) {
31853
- return join7(base, "data");
31854
- }
31855
- function dbPath(base = defaultDataDir()) {
31856
- return join7(dataDir(base), "aka.db");
31857
- }
31858
- async function ensureDataDir(dir = defaultDataDir()) {
31859
- await mkdir(dir, { recursive: true, mode: DATA_DIR_MODE });
31860
- tightenDir(dir);
31861
- }
31862
- function ensureLayoutDirSync(dir = defaultDataDir()) {
31863
- ensureDataDirSync(dir);
31864
- }
31865
- function migrateLegacyLayout(base = defaultDataDir()) {
31866
- const moves = [
31867
- { name: "config.json", dest: settingsDir(base) },
31868
- { name: "policy-cache.json", dest: dataDir(base) }
31869
- ];
31870
- for (const { name, dest } of moves) {
31871
- try {
31872
- ensureDataDirSync(dest);
31873
- const moved = join7(dest, name);
31874
- renameSync3(join7(base, name), moved);
31875
- tightenFile(moved);
31876
- } catch {
31877
- }
31878
- }
31879
- }
31880
-
31881
- // ../../packages/persistence/src/managed-settings.ts
31882
- import { readFileSync as readFileSync4 } from "fs";
31883
- import { posix, win32 } from "path";
31884
- function managedSettingsPaths(platform2 = process.platform) {
31885
- if (platform2 === "darwin") {
31886
- return [
31887
- posix.join("/Library", "Application Support", "AKASecurity", MANAGED_SETTINGS_FILENAME),
31888
- posix.join("/Library", "Managed Preferences", MANAGED_SETTINGS_FILENAME)
31889
- ];
31890
- }
31891
- if (platform2 === "win32") {
31892
- return [win32.join("C:\\", "ProgramData", "AKASecurity", MANAGED_SETTINGS_FILENAME)];
31893
- }
31894
- return [posix.join("/etc", "aka", MANAGED_SETTINGS_FILENAME)];
31895
- }
31896
- function readManagedSettings(paths = managedSettingsPaths()) {
31897
- for (const path of paths) {
31898
- let text;
31899
- try {
31900
- text = readFileSync4(path, "utf8");
31901
- } catch {
31902
- continue;
31903
- }
31904
- const record2 = parseJsonObject(text);
31905
- if (!record2) continue;
31906
- const parsed2 = ManagedSettings.safeParse(record2);
31907
- if (parsed2.success) return parsed2.data;
31908
- }
31909
- return null;
31910
- }
31911
- function overlayManagedSettings(settings, managed, now = () => /* @__PURE__ */ new Date()) {
31912
- if (!managed) return settings;
31913
- const { values } = managed;
31914
- const merged = { ...settings };
31915
- if (values.runMode !== void 0) merged.runMode = values.runMode;
31916
- if (values.controlPlane !== void 0) {
31917
- merged.controlPlane = {
31918
- ...values.controlPlane,
31919
- // The administrator pinned WHICH deployment, not WHEN this machine
31920
- // joined it. Keep the user's own attach time when the endpoint is
31921
- // unchanged, so a managed machine does not appear to re-attach on every
31922
- // read; stamp a fresh one when the administrator moved it.
31923
- attachedAt: settings.controlPlane?.endpoint === values.controlPlane.endpoint ? settings.controlPlane.attachedAt : now().toISOString()
31924
- };
31925
- }
31926
- if (values.historicalAccess !== void 0) merged.historicalAccess = values.historicalAccess;
31927
- if (values.vaultKeyCustody !== void 0) merged.vaultKeyCustody = values.vaultKeyCustody;
31928
- if (values.vaultInlineReveal !== void 0) merged.vaultInlineReveal = values.vaultInlineReveal;
31929
- if (values.dataSharesInPlace !== void 0) merged.dataSharesInPlace = values.dataSharesInPlace;
31930
- if (values.vaultConsent !== void 0) {
31931
- merged.vaultConsent = values.vaultConsent ? (
31932
- // Keep an existing valid grant so its acknowledgedAt survives; mint one
31933
- // at the current version otherwise.
31934
- settings.vaultConsent?.version === VAULT_CONSENT_VERSION ? settings.vaultConsent : { acknowledgedAt: now().toISOString(), version: VAULT_CONSENT_VERSION }
31935
- ) : void 0;
31936
- }
31937
- if (values.modelJudgeConsent !== void 0) {
31938
- merged.modelJudgeConsent = values.modelJudgeConsent ? settings.modelJudgeConsent?.payloadVersion === MODEL_JUDGE_PAYLOAD_VERSION ? settings.modelJudgeConsent : {
31939
- acknowledgedAt: now().toISOString(),
31940
- payloadVersion: MODEL_JUDGE_PAYLOAD_VERSION
31941
- } : void 0;
31942
- }
31943
- return merged;
31944
- }
31945
-
31946
- // ../../packages/persistence/src/settings.ts
31947
- import { readFileSync as readFileSync5 } from "fs";
31948
- import { join as join8 } from "path";
31949
- var SETTINGS_FILENAME = "settings.json";
31950
- function readWorkspaceSettings(base = defaultDataDir()) {
31951
- return overlayManagedSettings(readUserSettings(base), readManagedSettings());
31952
- }
31953
- function readUserSettings(base) {
31954
- const record2 = readJson(join8(settingsDir(base), SETTINGS_FILENAME));
31955
- if (!record2) return defaultWorkspaceSettings();
31956
- try {
31957
- return WorkspaceSettings.parse(record2);
31958
- } catch {
31959
- return defaultWorkspaceSettings();
31960
- }
31961
- }
31962
- function readJson(file2) {
31963
- let text;
31964
- try {
31965
- text = readFileSync5(file2, "utf8");
31966
- } catch {
31967
- return null;
31968
- }
31969
- return parseJsonObject(text) ?? null;
31970
- }
31971
-
31972
32498
  // ../../packages/persistence/src/store-symlinks.ts
31973
32499
  import { existsSync as existsSync5, lstatSync as lstatSync3, readlinkSync, realpathSync, statSync as statSync4 } from "fs";
31974
- import { dirname as dirname2, join as join9, resolve } from "path";
32500
+ import { dirname as dirname3, join as join10, resolve } from "path";
31975
32501
 
31976
32502
  // ../../packages/persistence/src/vault/crypto.ts
31977
32503
  import {
@@ -31985,19 +32511,19 @@ import {
31985
32511
  // ../../packages/persistence/src/vault/key-provider.ts
31986
32512
  import { execFileSync } from "child_process";
31987
32513
  import { randomBytes as randomBytes2 } from "crypto";
31988
- import { chmodSync as chmodSync3, readFileSync as readFileSync6, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
31989
- import { join as join10 } from "path";
32514
+ import { chmodSync as chmodSync3, readFileSync as readFileSync7, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
32515
+ import { join as join11 } from "path";
31990
32516
 
31991
32517
  // ../../packages/persistence/src/vault/vault.ts
31992
32518
  import { randomBytes as randomBytes3, randomUUID as randomUUID12 } from "crypto";
31993
32519
 
31994
32520
  // ../../packages/persistence/src/warn-era-cap.ts
31995
32521
  import { existsSync as existsSync6, writeFileSync as writeFileSync4 } from "fs";
31996
- import { join as join11 } from "path";
32522
+ import { join as join12 } from "path";
31997
32523
  var MARKER = "warn-era-capped";
31998
32524
  function capWarnEraEnforcementOnce(db, policyMode, dataDir2) {
31999
32525
  if (policyMode !== "warn") return { capped: 0, skipped: "not-warn" };
32000
- const marker = join11(dataDir2, MARKER);
32526
+ const marker = join12(dataDir2, MARKER);
32001
32527
  if (existsSync6(marker)) return { capped: 0, skipped: "already-run" };
32002
32528
  const capped = db.policies.capCategoryActions();
32003
32529
  writeFileSync4(marker, `${new Date(Date.now()).toISOString()}
@@ -32057,7 +32583,7 @@ function resolveProvider() {
32057
32583
  function loadConfig(base = defaultDataDir(), resolveProviderFn = resolveProvider) {
32058
32584
  try {
32059
32585
  ensureLayoutDirSync(base);
32060
- const settingsFile = join12(settingsDir(base), "settings.json");
32586
+ const settingsFile = join13(settingsDir(base), "settings.json");
32061
32587
  if (existsSync7(settingsFile)) tightenFile(settingsFile);
32062
32588
  } catch {
32063
32589
  }
@@ -32081,9 +32607,9 @@ function resolveProviderSafe(resolveProviderFn) {
32081
32607
  }
32082
32608
 
32083
32609
  // ../../packages/plugin-sdk/src/config-inventory.ts
32084
- import { readdirSync as readdirSync2, readFileSync as readFileSync8, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
32610
+ import { readdirSync as readdirSync2, readFileSync as readFileSync9, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
32085
32611
  import { homedir as homedir2 } from "os";
32086
- import { basename as basename3, join as join14 } from "path";
32612
+ import { basename as basename3, join as join15 } from "path";
32087
32613
 
32088
32614
  // ../../packages/detections/src/egress/registry.ts
32089
32615
  var EXTRACTOR_VERSION = "1";
@@ -35214,8 +35740,8 @@ function scanText(text, ruleVersions) {
35214
35740
  }
35215
35741
 
35216
35742
  // ../../packages/plugin-sdk/src/repo.ts
35217
- import { existsSync as existsSync8, readFileSync as readFileSync7, statSync as statSync6 } from "fs";
35218
- import { basename as basename2, dirname as dirname3, isAbsolute, join as join13, sep as sep2 } from "path";
35743
+ import { existsSync as existsSync8, readFileSync as readFileSync8, statSync as statSync6 } from "fs";
35744
+ import { basename as basename2, dirname as dirname4, isAbsolute, join as join14, sep as sep2 } from "path";
35219
35745
  function resolveRepoIdentity(cwd) {
35220
35746
  try {
35221
35747
  const root = findGitRoot(cwd);
@@ -35237,36 +35763,36 @@ function resolveRepoIdentity(cwd) {
35237
35763
  function findGitRoot(start) {
35238
35764
  let dir = start;
35239
35765
  for (; ; ) {
35240
- if (existsSync8(join13(dir, ".git"))) return dir;
35241
- const parent = dirname3(dir);
35766
+ if (existsSync8(join14(dir, ".git"))) return dir;
35767
+ const parent = dirname4(dir);
35242
35768
  if (parent === dir) return void 0;
35243
35769
  dir = parent;
35244
35770
  }
35245
35771
  }
35246
35772
  function resolveGitContext(root) {
35247
- const dotGit = join13(root, ".git");
35773
+ const dotGit = join14(root, ".git");
35248
35774
  try {
35249
35775
  if (statSync6(dotGit).isDirectory()) {
35250
- return { configPath: join13(dotGit, "config"), headRoot: root };
35776
+ return { configPath: join14(dotGit, "config"), headRoot: root };
35251
35777
  }
35252
35778
  } catch {
35253
35779
  return void 0;
35254
35780
  }
35255
35781
  const target = /^gitdir:\s*(.+?)\s*$/m.exec(safeRead(dotGit) ?? "")?.[1];
35256
35782
  if (!target) return void 0;
35257
- const gitdir = isAbsolute(target) ? target : join13(root, target);
35258
- if (existsSync8(join13(gitdir, "config"))) {
35259
- return { configPath: join13(gitdir, "config"), headRoot: root };
35783
+ const gitdir = isAbsolute(target) ? target : join14(root, target);
35784
+ if (existsSync8(join14(gitdir, "config"))) {
35785
+ return { configPath: join14(gitdir, "config"), headRoot: root };
35260
35786
  }
35261
- const commonRaw = safeRead(join13(gitdir, "commondir"))?.trim();
35787
+ const commonRaw = safeRead(join14(gitdir, "commondir"))?.trim();
35262
35788
  if (!commonRaw) return void 0;
35263
- const commonGitDir = isAbsolute(commonRaw) ? commonRaw : join13(gitdir, commonRaw);
35264
- const headRoot = basename2(commonGitDir) === ".git" ? dirname3(commonGitDir) : root;
35265
- return { configPath: join13(commonGitDir, "config"), headRoot };
35789
+ const commonGitDir = isAbsolute(commonRaw) ? commonRaw : join14(gitdir, commonRaw);
35790
+ const headRoot = basename2(commonGitDir) === ".git" ? dirname4(commonGitDir) : root;
35791
+ return { configPath: join14(commonGitDir, "config"), headRoot };
35266
35792
  }
35267
35793
  function safeRead(path) {
35268
35794
  try {
35269
- return readFileSync7(path, "utf8");
35795
+ return readFileSync8(path, "utf8");
35270
35796
  } catch {
35271
35797
  return void 0;
35272
35798
  }
@@ -35811,8 +36337,8 @@ function createGuardedScanner(partition, gateway, opts) {
35811
36337
 
35812
36338
  // ../../packages/plugin-sdk/src/ignore-layers.ts
35813
36339
  var import_ignore = __toESM(require_ignore(), 1);
35814
- import { readFileSync as readFileSync9 } from "fs";
35815
- import { join as join15 } from "path";
36340
+ import { readFileSync as readFileSync10 } from "fs";
36341
+ import { join as join16 } from "path";
35816
36342
 
35817
36343
  // ../../packages/plugin-sdk/src/inventory-resolver.ts
35818
36344
  import { arch, hostname as hostname4, platform, release } from "os";
@@ -35849,24 +36375,59 @@ import {
35849
36375
  fstatSync,
35850
36376
  mkdirSync as mkdirSync2,
35851
36377
  openSync as openSync2,
35852
- readFileSync as readFileSync10,
36378
+ readFileSync as readFileSync11,
35853
36379
  readSync,
35854
36380
  writeFileSync as writeFileSync5
35855
36381
  } from "fs";
35856
- import { join as join16 } from "path";
36382
+ import { join as join17 } from "path";
35857
36383
  var TAIL_BYTES = 256 * 1024;
35858
36384
 
35859
36385
  // ../../packages/plugin-sdk/src/nudge.ts
35860
- import { mkdirSync as mkdirSync3, readFileSync as readFileSync11, writeFileSync as writeFileSync6 } from "fs";
35861
- import { join as join17 } from "path";
36386
+ import { mkdirSync as mkdirSync3, readFileSync as readFileSync12, writeFileSync as writeFileSync6 } from "fs";
36387
+ import { join as join18 } from "path";
35862
36388
 
35863
36389
  // ../../packages/plugin-sdk/src/paths.ts
35864
36390
  import { readdirSync as readdirSync3, realpathSync as realpathSync3 } from "fs";
35865
- import { basename as basename4, dirname as dirname4, sep as sep3 } from "path";
36391
+ import { basename as basename4, dirname as dirname5, sep as sep3 } from "path";
36392
+
36393
+ // ../../packages/plugin-sdk/src/policy-resolver.ts
36394
+ function createPolicyResolver(bundle) {
36395
+ const byRule = /* @__PURE__ */ new Map();
36396
+ const byCategory = /* @__PURE__ */ new Map();
36397
+ let reversible = /* @__PURE__ */ new Set();
36398
+ try {
36399
+ for (const policy of bundle.policies) {
36400
+ if (!policy.enabled) continue;
36401
+ if ("ruleId" in policy.target) {
36402
+ if (!byRule.has(policy.target.ruleId)) byRule.set(policy.target.ruleId, policy.action);
36403
+ } else if (!byCategory.has(policy.target.category)) {
36404
+ byCategory.set(policy.target.category, policy.action);
36405
+ }
36406
+ }
36407
+ reversible = new Set(bundle.reversibleRuleIds ?? []);
36408
+ } catch {
36409
+ byRule.clear();
36410
+ byCategory.clear();
36411
+ reversible = /* @__PURE__ */ new Set();
36412
+ }
36413
+ return {
36414
+ actionFor(ruleId, category) {
36415
+ const byRuleAction = byRule.get(ruleId);
36416
+ if (byRuleAction !== void 0) return byRuleAction;
36417
+ const byCategoryAction = byCategory.get(category);
36418
+ if (byCategoryAction !== void 0) return byCategoryAction;
36419
+ const fallback = DEFAULT_ACTIONS[category];
36420
+ return fallback ?? "log";
36421
+ },
36422
+ isReversible(ruleId) {
36423
+ return reversible.has(ruleId);
36424
+ }
36425
+ };
36426
+ }
35866
36427
 
35867
36428
  // ../../packages/plugin-sdk/src/project-files.ts
35868
36429
  import { existsSync as existsSync10, readdirSync as readdirSync4 } from "fs";
35869
- import { basename as basename5, join as join18 } from "path";
36430
+ import { basename as basename5, join as join19 } from "path";
35870
36431
 
35871
36432
  // ../../packages/plugin-sdk/src/provider-env-antigravity.ts
35872
36433
  var optionalBaseUrl2 = external_exports.preprocess((v) => {
@@ -35947,7 +36508,6 @@ function safeMaskedMatch(rawMatch) {
35947
36508
  // ../../packages/plugin-sdk/src/runtime.ts
35948
36509
  import { randomUUID as randomUUID14 } from "crypto";
35949
36510
  var ENFORCEMENT_CEILING_ENABLED = false;
35950
- var ACTION_PRIORITY = ["block", "redact", "warn", "log", "allow"];
35951
36511
  function startTiming() {
35952
36512
  try {
35953
36513
  return performance.now();
@@ -35984,28 +36544,22 @@ function createPluginRuntime(gateway, settings, opts) {
35984
36544
  bundlesPacked = true;
35985
36545
  }
35986
36546
  const policyMode = settings.policy;
36547
+ const redactFallback = settings.redactFallback;
35987
36548
  const dataDir2 = opts?.dataDir;
35988
- let policies = [];
35989
36549
  let rules = [];
35990
36550
  let scanner;
35991
36551
  let bundleExceptions = [];
35992
36552
  let initialized = false;
35993
- const ruleActionIndex = /* @__PURE__ */ new Map();
35994
- const categoryActionIndex = /* @__PURE__ */ new Map();
35995
- let reversibleRuleIndex = /* @__PURE__ */ new Set();
36553
+ let resolver = createPolicyResolver({
36554
+ version: "",
36555
+ policies: [],
36556
+ customKeywords: [],
36557
+ fetchedAt: ""
36558
+ });
35996
36559
  async function ensureInitialized() {
35997
36560
  if (initialized) return;
35998
36561
  const bundle = await gateway.getPolicyBundle();
35999
- policies = bundle.policies;
36000
- for (const p of policies) {
36001
- if (!p.enabled) continue;
36002
- if ("ruleId" in p.target) {
36003
- if (!ruleActionIndex.has(p.target.ruleId)) ruleActionIndex.set(p.target.ruleId, p.action);
36004
- } else if (!categoryActionIndex.has(p.target.category)) {
36005
- categoryActionIndex.set(p.target.category, p.action);
36006
- }
36007
- }
36008
- reversibleRuleIndex = new Set(bundle.reversibleRuleIds ?? []);
36562
+ resolver = createPolicyResolver(bundle);
36009
36563
  const bundledProbeKeys = new Set(
36010
36564
  getLoadedRules().map(ruleProbeKey).filter((key) => key !== void 0)
36011
36565
  );
@@ -36058,33 +36612,28 @@ function createPluginRuntime(gateway, settings, opts) {
36058
36612
  return cachedKey;
36059
36613
  }
36060
36614
  function resolveAction(ruleId, category) {
36061
- const byRule = ruleActionIndex.get(ruleId);
36062
- if (byRule !== void 0) return byRule;
36063
- const byCategory = categoryActionIndex.get(category);
36064
- if (byCategory !== void 0) return byCategory;
36065
- const fallback = DEFAULT_ACTIONS[category];
36066
- return fallback ?? "log";
36067
- }
36068
- function actionForFinding(finding, excepted) {
36615
+ return resolver.actionFor(ruleId, category);
36616
+ }
36617
+ function actionForFinding(finding, excepted, rewritable = true) {
36069
36618
  if (excepted?.has(finding)) return "allow";
36070
36619
  const action = resolveAction(finding.ruleId, finding.category);
36620
+ if (!rewritable && action === "redact") return builtinPolicyToAction(redactFallback);
36071
36621
  if (ENFORCEMENT_CEILING_ENABLED && policyMode === "warn" && (action === "block" || action === "redact")) {
36072
36622
  return "warn";
36073
36623
  }
36074
36624
  return action;
36075
36625
  }
36076
- function decide(findings, text, excepted) {
36626
+ function decide(findings, text, excepted, rewritable = true) {
36077
36627
  if (findings.length === 0) return { action: "log", text, findings: [] };
36078
- const actionFor = (finding) => actionForFinding(finding, excepted);
36628
+ const actionFor = (finding) => actionForFinding(finding, excepted, rewritable);
36079
36629
  let worst = "log";
36080
36630
  for (const finding of findings) {
36081
- const action = actionFor(finding);
36082
- if (ACTION_PRIORITY.indexOf(action) < ACTION_PRIORITY.indexOf(worst)) worst = action;
36631
+ worst = strongerAction(worst, actionFor(finding));
36083
36632
  }
36084
36633
  if (worst === "block") return { action: "block", text: null, findings };
36085
36634
  if (worst === "redact") {
36086
36635
  const redactFindings = findings.filter((f) => actionFor(f) === "redact");
36087
- const reversibleFindings = redactFindings.filter((f) => reversibleRuleIndex.has(f.ruleId));
36636
+ const reversibleFindings = redactFindings.filter((f) => resolver.isReversible(f.ruleId));
36088
36637
  return {
36089
36638
  action: "redact",
36090
36639
  text: redact(text, redactFindings),
@@ -36160,7 +36709,7 @@ function createPluginRuntime(gateway, settings, opts) {
36160
36709
  return { excepted: /* @__PURE__ */ new Set(), exceptionIds: [] };
36161
36710
  }
36162
36711
  }
36163
- async function recordBlockedDetections(decision, excepted, ctx, fpCache) {
36712
+ async function recordBlockedDetections(decision, excepted, ctx, fpCache, rewritable = true) {
36164
36713
  const references = [];
36165
36714
  try {
36166
36715
  if (decision.action !== "block" && decision.action !== "redact") return references;
@@ -36168,7 +36717,7 @@ function createPluginRuntime(gateway, settings, opts) {
36168
36717
  if (!key) return references;
36169
36718
  const seen = /* @__PURE__ */ new Set();
36170
36719
  for (const finding of decision.findings) {
36171
- const action = actionForFinding(finding, excepted);
36720
+ const action = actionForFinding(finding, excepted, rewritable);
36172
36721
  if (action !== "block" && action !== "redact") continue;
36173
36722
  const fp = fingerprintOf(key, finding, fpCache);
36174
36723
  const pair = `${finding.ruleId}:${fp}`;
@@ -36195,7 +36744,7 @@ function createPluginRuntime(gateway, settings, opts) {
36195
36744
  }
36196
36745
  return references;
36197
36746
  }
36198
- async function evaluate(text, context, ctx) {
36747
+ async function evaluate(text, context, ctx, rewritable = true) {
36199
36748
  try {
36200
36749
  await ensureInitialized();
36201
36750
  if (!scanner) throw new Error("the runtime initialized without a scanner");
@@ -36204,8 +36753,14 @@ function createPluginRuntime(gateway, settings, opts) {
36204
36753
  const findings = dropShieldedFindings(matched, shielded.spans);
36205
36754
  const fpCache = /* @__PURE__ */ new Map();
36206
36755
  const { excepted, exceptionIds } = await applyExceptions(findings, ctx, fpCache);
36207
- const decision = decide(findings, text, excepted);
36208
- const blockedReferences = await recordBlockedDetections(decision, excepted, ctx, fpCache);
36756
+ const decision = decide(findings, text, excepted, rewritable);
36757
+ const blockedReferences = await recordBlockedDetections(
36758
+ decision,
36759
+ excepted,
36760
+ ctx,
36761
+ fpCache,
36762
+ rewritable
36763
+ );
36209
36764
  if (blockedReferences.length > 0) decision.blockedReferences = blockedReferences;
36210
36765
  return { decision, excepted, exceptionIds };
36211
36766
  } catch {
@@ -36229,12 +36784,16 @@ function createPluginRuntime(gateway, settings, opts) {
36229
36784
  sourceTool: input2.sourceTool,
36230
36785
  metadata: input2.metadata,
36231
36786
  preAuthorizedGrantIds: opts2.preAuthorizedGrantIds
36232
- }
36787
+ },
36788
+ opts2.rewritable
36233
36789
  );
36234
36790
  if (opts2.persist === "with-findings" && decision.findings.length === 0) return decision;
36235
36791
  try {
36236
36792
  const contentHash = contentHashOf(input2.text);
36237
- const storedContent = decision.findings.length > 0 ? redact(input2.text, decision.findings) : input2.text;
36793
+ const maskedFindings = decision.findings.filter(
36794
+ (match) => isActionAtLeast(actionForFinding(match, excepted, opts2.rewritable), "redact")
36795
+ );
36796
+ const storedContent = maskedFindings.length > 0 ? redact(input2.text, maskedFindings) : input2.text;
36238
36797
  const inspectionMs = elapsedMs(timingStartedAt);
36239
36798
  const metadata = exceptionIds.length > 0 || inspectionMs !== void 0 ? {
36240
36799
  ...input2.metadata,
@@ -36271,7 +36830,7 @@ function createPluginRuntime(gateway, settings, opts) {
36271
36830
  severity: match.severity,
36272
36831
  span: match.span,
36273
36832
  maskedMatch,
36274
- actionTaken: actionForFinding(match, excepted),
36833
+ actionTaken: actionForFinding(match, excepted, opts2.rewritable),
36275
36834
  confidence: match.confidence,
36276
36835
  ...findingKey ? { findingKey } : {}
36277
36836
  };
@@ -36311,11 +36870,11 @@ var THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1e3;
36311
36870
 
36312
36871
  // ../../packages/plugin-sdk/src/throttle.ts
36313
36872
  import { mkdirSync as mkdirSync4, statSync as statSync8, writeFileSync as writeFileSync7 } from "fs";
36314
- import { join as join19 } from "path";
36873
+ import { join as join20 } from "path";
36315
36874
 
36316
36875
  // ../../packages/setup-wizard/src/remediation/rotation-checklist.ts
36317
36876
  import { writeFileSync as writeFileSync8 } from "fs";
36318
- import { join as join20 } from "path";
36877
+ import { join as join21 } from "path";
36319
36878
 
36320
36879
  // ../../packages/setup-wizard/src/triage/merge.ts
36321
36880
  var RANK = Object.fromEntries(
@@ -36323,9 +36882,9 @@ var RANK = Object.fromEntries(
36323
36882
  );
36324
36883
 
36325
36884
  // ../../packages/setup-wizard/src/triage/plan-file.ts
36326
- import { mkdtempSync, readFileSync as readFileSync12, rmdirSync, rmSync as rmSync7, writeFileSync as writeFileSync9 } from "fs";
36885
+ import { mkdtempSync, readFileSync as readFileSync13, rmdirSync, rmSync as rmSync7, writeFileSync as writeFileSync9 } from "fs";
36327
36886
  import { tmpdir } from "os";
36328
- import { basename as basename6, dirname as dirname5, join as join21 } from "path";
36887
+ import { basename as basename6, dirname as dirname6, join as join22 } from "path";
36329
36888
  var SuppressionEntrySchema = external_exports.object({
36330
36889
  ruleId: external_exports.string(),
36331
36890
  category: DetectionCategory,
@@ -36406,6 +36965,307 @@ function toEgressIngestRequest(input2) {
36406
36965
  };
36407
36966
  }
36408
36967
 
36968
+ // ../../packages/remote/src/http.ts
36969
+ import { request as httpRequest } from "http";
36970
+ import { request as httpsRequest } from "https";
36971
+ var DEFAULT_TIMEOUT_MS = 1e4;
36972
+ var MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
36973
+ var RemoteRequestError = class extends Error {
36974
+ constructor(status) {
36975
+ super(`control-plane request failed with status ${String(status)}`);
36976
+ this.status = status;
36977
+ this.name = "RemoteRequestError";
36978
+ }
36979
+ status;
36980
+ };
36981
+ var RemoteRouteAbsent = class extends Error {
36982
+ constructor(route) {
36983
+ super(`control plane does not serve ${route}`);
36984
+ this.route = route;
36985
+ this.name = "RemoteRouteAbsent";
36986
+ }
36987
+ route;
36988
+ };
36989
+ var RemoteRequestInvalid = class extends Error {
36990
+ constructor(route, cause) {
36991
+ super(`refusing to send a malformed body to ${route}`);
36992
+ this.cause = cause;
36993
+ this.name = "RemoteRequestInvalid";
36994
+ }
36995
+ cause;
36996
+ };
36997
+ var RemoteResponseInvalid = class extends Error {
36998
+ constructor(route, detail) {
36999
+ super(`control plane answered ${route} with ${detail}`);
37000
+ this.name = "RemoteResponseInvalid";
37001
+ }
37002
+ };
37003
+ var RemoteTransportError = class extends Error {
37004
+ /**
37005
+ * The status the peer sent, when headers arrived and only the BODY was
37006
+ * refused.
37007
+ *
37008
+ * Undefined for the ordinary case this class was written for — no answer at
37009
+ * all. It exists because two paths reject after a status has already been
37010
+ * delivered: an oversized body and an aborted response. Discarding it there
37011
+ * reported a deployment answering 401 with a verbose body as a network
37012
+ * outage, which sends the reader to look at their network instead of their
37013
+ * credential.
37014
+ */
37015
+ constructor(reason, status) {
37016
+ super(`control-plane request did not complete: ${reason}`);
37017
+ this.status = status;
37018
+ this.name = "RemoteTransportError";
37019
+ }
37020
+ status;
37021
+ };
37022
+ async function send(options) {
37023
+ const url2 = new URL(options.url);
37024
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
37025
+ const send_ = url2.protocol === "http:" ? httpRequest : httpsRequest;
37026
+ const requestOptions = {
37027
+ method: options.method,
37028
+ headers: {
37029
+ // CALLER HEADERS FIRST, so this module's own are not overridable. Spread
37030
+ // last they win, and two of the values below are ones no caller may
37031
+ // replace: `x-api-key` is the credential, and `content-length` is the
37032
+ // byte count that stops a multi-byte body being truncated by the
37033
+ // receiver. `SendOptions.headers` is a free-form record on an exported
37034
+ // function, so "no caller does that today" is not the guarantee to rely
37035
+ // on. The one header any caller actually passes — `if-none-match` on the
37036
+ // conditional GET — is untouched by this order.
37037
+ ...options.headers,
37038
+ // The credential. One header, matching what the deployment authenticates
37039
+ // on; a second copy in an `Authorization` header would be one more place
37040
+ // it can be logged by an intermediary for no gain.
37041
+ //
37042
+ // Spread conditionally rather than assigned as `undefined`: Node's header
37043
+ // handling and `content-length` bookkeeping treat a present-but-undefined
37044
+ // key differently from an absent one, and "the header is not there" is
37045
+ // the property the attach flow needs.
37046
+ ...options.apiKey === void 0 ? {} : { "x-api-key": options.apiKey },
37047
+ accept: "application/json",
37048
+ ...options.body === void 0 ? {} : {
37049
+ "content-type": "application/json",
37050
+ // Byte length, not string length: a multi-byte body sent with a
37051
+ // character count is truncated by the receiver.
37052
+ "content-length": String(Buffer.byteLength(options.body))
37053
+ }
37054
+ }
37055
+ };
37056
+ return new Promise((resolve2, reject) => {
37057
+ let settled = false;
37058
+ const fail = (reason, status) => {
37059
+ if (settled) return;
37060
+ settled = true;
37061
+ reject(new RemoteTransportError(reason, status));
37062
+ };
37063
+ const req = send_(url2, requestOptions, (res) => {
37064
+ const chunks = [];
37065
+ let size = 0;
37066
+ res.on("data", (chunk) => {
37067
+ size += chunk.length;
37068
+ if (size > MAX_RESPONSE_BYTES) {
37069
+ fail(`response exceeded ${String(MAX_RESPONSE_BYTES)} bytes`, res.statusCode);
37070
+ res.destroy();
37071
+ req.destroy();
37072
+ return;
37073
+ }
37074
+ chunks.push(chunk);
37075
+ });
37076
+ res.on("aborted", () => {
37077
+ fail("the response was aborted", res.statusCode);
37078
+ });
37079
+ res.on("end", () => {
37080
+ if (settled) return;
37081
+ settled = true;
37082
+ resolve2({
37083
+ status: res.statusCode ?? 0,
37084
+ headers: res.headers,
37085
+ body: Buffer.concat(chunks).toString("utf8")
37086
+ });
37087
+ });
37088
+ });
37089
+ const deadline = setTimeout(() => {
37090
+ fail(`no response within ${String(timeoutMs)}ms`);
37091
+ req.destroy();
37092
+ }, timeoutMs);
37093
+ deadline.unref();
37094
+ req.on("upgrade", (_res, socket) => {
37095
+ fail("the deployment answered with a protocol upgrade");
37096
+ socket.destroy();
37097
+ });
37098
+ req.on("close", () => {
37099
+ fail("the connection closed before a response was read");
37100
+ clearTimeout(deadline);
37101
+ });
37102
+ req.on("error", (err) => {
37103
+ fail(err.message);
37104
+ });
37105
+ if (options.body !== void 0) req.write(options.body);
37106
+ req.end();
37107
+ });
37108
+ }
37109
+
37110
+ // ../../packages/remote/src/client.ts
37111
+ var ROUTES = {
37112
+ events: "/v1/events",
37113
+ auditEvents: "/v1/audit-events",
37114
+ auditEventsBatch: "/v1/audit-events/batch",
37115
+ inventory: "/v1/inventory",
37116
+ storePosture: "/v1/store-posture",
37117
+ policyBundle: "/v1/policy-bundle",
37118
+ whoami: "/v1/plugin/whoami",
37119
+ shares: "/v1/shares",
37120
+ commands: "/v1/plugin/commands"
37121
+ };
37122
+ function ackRoute(id) {
37123
+ return `${ROUTES.commands}/${encodeURIComponent(id)}/ack`;
37124
+ }
37125
+ function headerValue(response, name) {
37126
+ const raw = response.headers[name];
37127
+ if (raw === void 0) return void 0;
37128
+ return Array.isArray(raw) ? raw[0] : raw;
37129
+ }
37130
+ function okBody(response) {
37131
+ if (response.status < 200 || response.status >= 300) {
37132
+ throw new RemoteRequestError(response.status);
37133
+ }
37134
+ return response.body;
37135
+ }
37136
+ function parsed(schema, body, route) {
37137
+ let json2;
37138
+ try {
37139
+ json2 = JSON.parse(body);
37140
+ } catch {
37141
+ throw new RemoteResponseInvalid(route, "a body that is not JSON");
37142
+ }
37143
+ const result = schema.safeParse(json2);
37144
+ if (!result.success) {
37145
+ throw new RemoteResponseInvalid(route, "a body this client cannot read");
37146
+ }
37147
+ return result.data;
37148
+ }
37149
+ function withoutTrailingSlashes(endpoint) {
37150
+ let end = endpoint.length;
37151
+ while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH) end -= 1;
37152
+ return endpoint.slice(0, end);
37153
+ }
37154
+ var SLASH = "/".charCodeAt(0);
37155
+ function createRemoteClient(options) {
37156
+ const base = withoutTrailingSlashes(options.endpoint);
37157
+ const url2 = (route) => `${base}${route}`;
37158
+ const common = { apiKey: options.apiKey, timeoutMs: options.timeoutMs };
37159
+ const sendOne = async (event) => {
37160
+ const validated = RecordAuditEventRequest.safeParse(event);
37161
+ if (!validated.success) throw new RemoteRequestInvalid(ROUTES.auditEvents, validated.error);
37162
+ const response = await send({
37163
+ ...common,
37164
+ method: "POST",
37165
+ url: url2(ROUTES.auditEvents),
37166
+ body: JSON.stringify(validated.data)
37167
+ });
37168
+ okBody(response);
37169
+ };
37170
+ return {
37171
+ async ingestEvents(batch) {
37172
+ const response = await send({
37173
+ ...common,
37174
+ method: "POST",
37175
+ url: url2(ROUTES.events),
37176
+ body: JSON.stringify(batch)
37177
+ });
37178
+ return parsed(IngestAck, okBody(response), ROUTES.events);
37179
+ },
37180
+ async ingestInventory(context) {
37181
+ const response = await send({
37182
+ ...common,
37183
+ method: "POST",
37184
+ url: url2(ROUTES.inventory),
37185
+ body: JSON.stringify(context)
37186
+ });
37187
+ return parsed(ResolvedInventory, okBody(response), ROUTES.inventory);
37188
+ },
37189
+ async recordAuditEvent(event) {
37190
+ await sendOne(event);
37191
+ },
37192
+ async recordAuditEvents(events, opts) {
37193
+ const validated = RecordAuditEventBatch.safeParse({ events });
37194
+ if (!validated.success) {
37195
+ throw new RemoteRequestInvalid(ROUTES.auditEventsBatch, validated.error);
37196
+ }
37197
+ const response = await send({
37198
+ ...common,
37199
+ method: "POST",
37200
+ url: url2(ROUTES.auditEventsBatch),
37201
+ body: JSON.stringify(validated.data)
37202
+ });
37203
+ if (response.status === 404) {
37204
+ if (opts?.fallbackToSingleEvents !== true) {
37205
+ throw new RemoteRouteAbsent(ROUTES.auditEventsBatch);
37206
+ }
37207
+ for (const event of validated.data.events) await sendOne(event);
37208
+ return { accepted: validated.data.events.length };
37209
+ }
37210
+ return parsed(AuditEventBatchAck, okBody(response), ROUTES.auditEventsBatch);
37211
+ },
37212
+ async reportStorePosture(snapshot) {
37213
+ const response = await send({
37214
+ ...common,
37215
+ method: "POST",
37216
+ url: url2(ROUTES.storePosture),
37217
+ body: JSON.stringify(snapshot)
37218
+ });
37219
+ okBody(response);
37220
+ },
37221
+ async getPolicyBundle(etag) {
37222
+ const response = await send({
37223
+ ...common,
37224
+ method: "GET",
37225
+ url: url2(ROUTES.policyBundle),
37226
+ ...etag === void 0 ? {} : { headers: { "if-none-match": etag } }
37227
+ });
37228
+ if (response.status === 304) {
37229
+ return { changed: false, etag: headerValue(response, "etag") ?? etag };
37230
+ }
37231
+ const bundle = parsed(PolicyBundle, okBody(response), ROUTES.policyBundle);
37232
+ return { changed: true, bundle, etag: headerValue(response, "etag") };
37233
+ },
37234
+ async whoami() {
37235
+ const response = await send({ ...common, method: "GET", url: url2(ROUTES.whoami) });
37236
+ return parsed(PluginWhoami, okBody(response), ROUTES.whoami);
37237
+ },
37238
+ async recordProjectEgress(request) {
37239
+ const validated = EgressIngestRequest.safeParse(request);
37240
+ if (!validated.success) throw new RemoteRequestInvalid(ROUTES.shares, validated.error);
37241
+ const response = await send({
37242
+ ...common,
37243
+ method: "POST",
37244
+ url: url2(ROUTES.shares),
37245
+ body: JSON.stringify(validated.data)
37246
+ });
37247
+ okBody(response);
37248
+ },
37249
+ async pollCommand() {
37250
+ const response = await send({ ...common, method: "GET", url: url2(ROUTES.commands) });
37251
+ if (response.status === 404) return null;
37252
+ return parsed(DeviceCommandPollResponse, okBody(response), ROUTES.commands).command;
37253
+ },
37254
+ async ackCommand(id, body) {
37255
+ const validated = DeviceCommandAckBody.safeParse(body);
37256
+ const route = ackRoute(id);
37257
+ if (!validated.success) throw new RemoteRequestInvalid(route, validated.error);
37258
+ const response = await send({
37259
+ ...common,
37260
+ method: "POST",
37261
+ url: url2(route),
37262
+ body: JSON.stringify(validated.data)
37263
+ });
37264
+ okBody(response);
37265
+ }
37266
+ };
37267
+ }
37268
+
36409
37269
  // ../../packages/plugin-runtime/src/attached/failure.ts
36410
37270
  function statusOf(err) {
36411
37271
  if (typeof err !== "object" || err === null || !("status" in err)) return null;
@@ -36424,12 +37284,27 @@ function classifyFailure(err) {
36424
37284
  }
36425
37285
  }
36426
37286
 
37287
+ // ../../packages/plugin-runtime/src/attached/with-timeout.ts
37288
+ var REQUEST_TIMEOUT_MS = 2e3;
37289
+ function withTimeout(promise2, ms) {
37290
+ let timer;
37291
+ const timeout = new Promise((_, reject) => {
37292
+ timer = setTimeout(() => {
37293
+ reject(new Error("attached gateway request timed out"));
37294
+ }, ms);
37295
+ });
37296
+ promise2.catch(() => void 0);
37297
+ return Promise.race([promise2, timeout]).finally(() => {
37298
+ clearTimeout(timer);
37299
+ });
37300
+ }
37301
+
36427
37302
  // ../../packages/plugin-runtime/src/attached/forward-drops.ts
36428
- import { readFileSync as readFileSync13 } from "fs";
36429
- import { join as join22 } from "path";
37303
+ import { readFileSync as readFileSync14 } from "fs";
37304
+ import { join as join23 } from "path";
36430
37305
  var FORWARD_DROPS_FILENAME = ATTACHED_FORWARD_DROPS_FILENAME;
36431
37306
  function forwardDropsPath(dataDir2) {
36432
- return join22(dataDir2, FORWARD_DROPS_FILENAME);
37307
+ return join23(dataDir2, FORWARD_DROPS_FILENAME);
36433
37308
  }
36434
37309
  function recordForwardDrops(dataDir2, count, nowMs) {
36435
37310
  if (count <= 0) return;
@@ -36447,7 +37322,7 @@ function recordForwardDrops(dataDir2, count, nowMs) {
36447
37322
  }
36448
37323
  function readForwardDrops(dataDir2) {
36449
37324
  try {
36450
- const parsed2 = JSON.parse(readFileSync13(forwardDropsPath(dataDir2), "utf8"));
37325
+ const parsed2 = JSON.parse(readFileSync14(forwardDropsPath(dataDir2), "utf8"));
36451
37326
  if (typeof parsed2 !== "object" || parsed2 === null) return null;
36452
37327
  const record2 = parsed2;
36453
37328
  if (typeof record2.droppedForwards !== "number" || !Number.isFinite(record2.droppedForwards)) {
@@ -36465,29 +37340,19 @@ function readForwardDrops(dataDir2) {
36465
37340
 
36466
37341
  // ../../packages/plugin-runtime/src/attached/forward-policy.ts
36467
37342
  import { randomUUID as randomUUID15 } from "crypto";
36468
- import { readFileSync as readFileSync14 } from "fs";
37343
+ import { readFileSync as readFileSync15 } from "fs";
36469
37344
  import { readFile, rename, writeFile } from "fs/promises";
36470
- import { join as join23 } from "path";
36471
-
36472
- // ../../packages/plugin-runtime/src/attached/with-timeout.ts
36473
- var REQUEST_TIMEOUT_MS = 2e3;
36474
- function withTimeout(promise2, ms) {
36475
- let timer;
36476
- const timeout = new Promise((_, reject) => {
36477
- timer = setTimeout(() => {
36478
- reject(new Error("attached gateway request timed out"));
36479
- }, ms);
36480
- });
36481
- promise2.catch(() => void 0);
36482
- return Promise.race([promise2, timeout]).finally(() => {
36483
- clearTimeout(timer);
36484
- });
36485
- }
36486
-
36487
- // ../../packages/plugin-runtime/src/attached/forward-policy.ts
37345
+ import { join as join24 } from "path";
36488
37346
  function isInvalidRequest(err) {
36489
37347
  return typeof err === "object" && err !== null && err.name === "RemoteRequestInvalid";
36490
37348
  }
37349
+ function isRouteAbsent(err) {
37350
+ return typeof err === "object" && err !== null && err.name === "RemoteRouteAbsent";
37351
+ }
37352
+ function isServerRejection(err) {
37353
+ const status = statusOf(err);
37354
+ return status !== null && status >= 400 && status <= 499 && status !== 401 && status !== 403 && status !== 404 && status !== 429;
37355
+ }
36491
37356
  var FORWARD_BUDGET_MS = 1500;
36492
37357
  var DECISION_PATH_BUDGET_MS = 800;
36493
37358
  var BREAKER_FAILURE_THRESHOLD = 3;
@@ -36515,7 +37380,7 @@ function parseBreakerState(raw, nowMs) {
36515
37380
  }
36516
37381
  function createForwardPolicy(deps) {
36517
37382
  const now = deps.now ?? (() => Date.now());
36518
- const file2 = join23(deps.dir, STATE_FILENAME);
37383
+ const file2 = join24(deps.dir, STATE_FILENAME);
36519
37384
  let state = null;
36520
37385
  let loading = null;
36521
37386
  async function readState() {
@@ -36555,6 +37420,20 @@ function createForwardPolicy(deps) {
36555
37420
  } catch {
36556
37421
  current = { ...CLOSED };
36557
37422
  }
37423
+ const restoreOpenedAtMs = (openedAtMs) => persist({
37424
+ consecutiveFailures: current.consecutiveFailures,
37425
+ openedAtMs,
37426
+ lastFailure: current.lastFailure
37427
+ });
37428
+ const recordFailure = (cause) => {
37429
+ const failures = current.consecutiveFailures + 1;
37430
+ const shouldOpen = current.openedAtMs !== null || failures >= BREAKER_FAILURE_THRESHOLD;
37431
+ return persist({
37432
+ consecutiveFailures: failures,
37433
+ openedAtMs: shouldOpen ? now() : null,
37434
+ lastFailure: cause
37435
+ });
37436
+ };
36558
37437
  const at = now();
36559
37438
  if (current.openedAtMs !== null) {
36560
37439
  if (at - current.openedAtMs < BREAKER_COOLDOWN_MS) {
@@ -36573,15 +37452,20 @@ function createForwardPolicy(deps) {
36573
37452
  }
36574
37453
  return { ok: true, value };
36575
37454
  } catch (err) {
36576
- if (isInvalidRequest(err)) return { ok: false, reason: "invalid-request" };
37455
+ if (isInvalidRequest(err)) {
37456
+ if (current.openedAtMs !== null) await restoreOpenedAtMs(current.openedAtMs);
37457
+ return { ok: false, reason: "invalid-request" };
37458
+ }
37459
+ if (isRouteAbsent(err)) {
37460
+ if (current.openedAtMs !== null) await restoreOpenedAtMs(null);
37461
+ return { ok: false, reason: "route-absent" };
37462
+ }
37463
+ if (isServerRejection(err)) {
37464
+ await recordFailure("unreachable");
37465
+ return { ok: false, reason: "rejected" };
37466
+ }
36577
37467
  const reason = classifyFailure(err);
36578
- const failures = current.consecutiveFailures + 1;
36579
- const shouldOpen = current.openedAtMs !== null || failures >= BREAKER_FAILURE_THRESHOLD;
36580
- await persist({
36581
- consecutiveFailures: failures,
36582
- openedAtMs: shouldOpen ? now() : null,
36583
- lastFailure: reason
36584
- });
37468
+ await recordFailure(reason);
36585
37469
  return { ok: false, reason };
36586
37470
  }
36587
37471
  }
@@ -36589,13 +37473,11 @@ function createForwardPolicy(deps) {
36589
37473
  }
36590
37474
 
36591
37475
  // ../../packages/plugin-runtime/src/attached/gateway.ts
36592
- var ACTION_STRENGTH = {
36593
- allow: 0,
36594
- log: 1,
36595
- warn: 2,
36596
- redact: 3,
36597
- block: 4
36598
- };
37476
+ function strongerOf(a, b) {
37477
+ if (a === null) return b;
37478
+ if (b === null) return a;
37479
+ return strongerAction(a, b);
37480
+ }
36599
37481
  function ruleCategoryMap(wireRules, localRules) {
36600
37482
  const map2 = /* @__PURE__ */ new Map();
36601
37483
  for (const rule of wireRules ?? []) map2.set(rule.id, rule.category);
@@ -36605,11 +37487,6 @@ function ruleCategoryMap(wireRules, localRules) {
36605
37487
  }
36606
37488
  return map2;
36607
37489
  }
36608
- function strongerOf(a, b) {
36609
- if (a === null) return b;
36610
- if (b === null) return a;
36611
- return ACTION_STRENGTH[a] >= ACTION_STRENGTH[b] ? a : b;
36612
- }
36613
37490
  function policyKey(policy) {
36614
37491
  return "ruleId" in policy.target ? `rule:${policy.target.ruleId}` : `category:${policy.target.category}`;
36615
37492
  }
@@ -36628,7 +37505,7 @@ function mergeRaiseOnly(localPolicies, remotePolicies, categoryByRuleId) {
36628
37505
  const floor = floorFor(policy, categoryByRuleId);
36629
37506
  remoteCategoryAction.set(
36630
37507
  policy.target.category,
36631
- floor !== null && ACTION_STRENGTH[policy.action] < ACTION_STRENGTH[floor] ? floor : policy.action
37508
+ floor !== null && !isActionAtLeast(policy.action, floor) ? floor : policy.action
36632
37509
  );
36633
37510
  }
36634
37511
  for (const policy of localPolicies) {
@@ -36645,7 +37522,7 @@ function mergeRaiseOnly(localPolicies, remotePolicies, categoryByRuleId) {
36645
37522
  }
36646
37523
  merged.set(
36647
37524
  key,
36648
- remoteFloor !== null && ACTION_STRENGTH[policy.action] < ACTION_STRENGTH[remoteFloor] ? { ...policy, action: remoteFloor } : policy
37525
+ remoteFloor !== null && !isActionAtLeast(policy.action, remoteFloor) ? { ...policy, action: remoteFloor } : policy
36649
37526
  );
36650
37527
  }
36651
37528
  const localCategoryAction = /* @__PURE__ */ new Map();
@@ -36665,13 +37542,13 @@ function mergeRaiseOnly(localPolicies, remotePolicies, categoryByRuleId) {
36665
37542
  if (category !== void 0) localFloor = localCategoryAction.get(category) ?? null;
36666
37543
  }
36667
37544
  const effectiveFloor = strongerOf(floor, localFloor);
36668
- const clamped = effectiveFloor !== null && ACTION_STRENGTH[policy.action] < ACTION_STRENGTH[effectiveFloor] ? { ...policy, action: effectiveFloor } : policy;
37545
+ const clamped = effectiveFloor !== null && !isActionAtLeast(policy.action, effectiveFloor) ? { ...policy, action: effectiveFloor } : policy;
36669
37546
  const existing = merged.get(key);
36670
37547
  if (existing === void 0) {
36671
37548
  merged.set(key, clamped);
36672
37549
  continue;
36673
37550
  }
36674
- if (ACTION_STRENGTH[clamped.action] > ACTION_STRENGTH[existing.action]) {
37551
+ if (actionRank(clamped.action) > actionRank(existing.action)) {
36675
37552
  merged.set(key, clamped);
36676
37553
  }
36677
37554
  }
@@ -36704,6 +37581,8 @@ var AttachedDataGateway = class {
36704
37581
  );
36705
37582
  if (forwarded.ok && forwarded.value.accepted + forwarded.value.duplicates > 0) {
36706
37583
  this.deps.local.markCaptureDelivered(record2.event, Date.now());
37584
+ } else {
37585
+ this.deps.local.markCaptureOwed(record2.event);
36707
37586
  }
36708
37587
  }
36709
37588
  async ensureInventory(ctx) {
@@ -36740,9 +37619,10 @@ var AttachedDataGateway = class {
36740
37619
  // a retried tool_call, exactly this path — can never stomp a populated row.
36741
37620
  async recordAuditEvent(event) {
36742
37621
  await this.deps.local.recordAuditEvent(event);
36743
- await this.deps.forward.run(
37622
+ const forwarded = await this.deps.forward.run(
36744
37623
  () => this.deps.client.recordAuditEvent(reKeyForForward(event, this.remoteInventory))
36745
37624
  );
37625
+ if (forwarded.ok) this.deps.local.markAuditEventsDelivered([event], Date.now());
36746
37626
  }
36747
37627
  // Attached `llm_call` is written locally by the inner gateway, then routed to
36748
37628
  // the control plane through the existing `recordAuditEvent` ingest (no dedicated
@@ -36751,44 +37631,170 @@ var AttachedDataGateway = class {
36751
37631
  // which would write the event to the local store a second time.
36752
37632
  async recordLlmCall(input2) {
36753
37633
  await this.deps.local.recordLlmCall(input2);
36754
- await this.deps.forward.run(
36755
- () => this.deps.client.recordAuditEvent(
36756
- reKeyForForward(llmAuditEvent(input2), this.remoteInventory)
36757
- )
37634
+ const event = llmAuditEvent(input2);
37635
+ const forwarded = await this.deps.forward.run(
37636
+ () => this.deps.client.recordAuditEvent(reKeyForForward(event, this.remoteInventory))
36758
37637
  );
37638
+ if (forwarded.ok) this.deps.local.markAuditEventsDelivered([event], Date.now());
36759
37639
  }
36760
37640
  /**
36761
- * Forward one batch, item by item, under ONE aggregate deadline.
37641
+ * Forward one batch in CHUNKS of AUDIT_EVENT_BATCH_MAX, under ONE aggregate deadline.
37642
+ *
37643
+ * This used to send one HTTP request per event, which is what made the batch
37644
+ * budget bite: at 200ms round-trip a 3s budget admitted ~15 events and threw
37645
+ * away everything after them. The same rows now cross 50 at a time over
37646
+ * `POST /v1/audit-events/batch` — the route the attach-time drain has always
37647
+ * used — so the same budget admits ~750. The wire cap is the server's own
37648
+ * constant, sized against server cost, and the client REFUSES a longer array
37649
+ * client-side, so the chunking here is not a convention.
37650
+ *
37651
+ * Still serial, and still for the original reason: firing N requests at once
37652
+ * would trade a latency problem for a burst the plane's per-key rate limiting
37653
+ * answers with the refusals the breaker then counts. Fewer, fuller requests is
37654
+ * the fix; more concurrent ones is not.
37655
+ *
37656
+ * When the deadline passes the remainder is dropped rather than sent: the
37657
+ * local write has already succeeded, so every caller has a correct result to
37658
+ * return. What is dropped is COUNTED, everywhere it can happen — this path
37659
+ * returns BEFORE `ForwardPolicy.run` is reached, so without the tally in
37660
+ * `forward-drops.ts` a slow-but-answering plane produces no failures, keeps
37661
+ * the breaker closed, renders a healthy block, and discards the tail of every
37662
+ * batch indefinitely. The SAME tally also covers a single that fails inside
37663
+ * the per-item retry below — the breaker opening mid-retry is a failure the
37664
+ * breaker's own state DOES capture, but the events still in this chunk once
37665
+ * that happens are neither delivered nor otherwise counted anywhere, which is
37666
+ * the same invisibility with a different cause.
37667
+ *
37668
+ * `ok` ALONE IS NOT DELIVERY, the same rule `recordCapture` states for the
37669
+ * single-event ack and at fifty times the blast radius here:
37670
+ * `AuditEventBatchAck.accepted` is an aggregate count the wire contract does
37671
+ * not tie to the chunk's own length, so a 2xx answering `{accepted: 30}` for
37672
+ * fifty events is well-formed. Trusting `ok` alone would stamp all fifty as
37673
+ * delivered and never re-offer the twenty the plane did not take. So success
37674
+ * is checked against `chunk.length`; anything short of it falls into the same
37675
+ * per-item pass as a refused chunk, which is the only way to recover the
37676
+ * rows that did not land, since the ack carries no per-row verdict to
37677
+ * resend by.
37678
+ *
37679
+ * That fallback ASSUMES a re-send of an already-landed row is a harmless
37680
+ * no-op rather than a second cost — an assumption this file cannot verify.
37681
+ * `AuditEventBatchAck` carries only `accepted`, unlike its sibling
37682
+ * `IngestAck` (`accepted` + `duplicates`, with `accepted + duplicates ==`
37683
+ * the batch size as the invariant `recordCapture` reads), so whether a
37684
+ * duplicate counts toward THIS route's `accepted` is not expressed
37685
+ * anywhere in this repo. If it follows its sibling's convention and does
37686
+ * NOT, a chunk containing even one already-delivered row — the ordinary
37687
+ * consequence of a lost stamp, which this file already treats as cheap —
37688
+ * answers short forever and enters the per-item pass on every pass it is
37689
+ * offered again. The cost of that is bounded rather than silent: the
37690
+ * pass converges (every row lands and stamps), so it is one wasted round
37691
+ * of singles rather than a stall, and it errs toward an extra resend
37692
+ * rather than toward the lost row the alternative risks.
36762
37693
  *
36763
- * Per-item budgets bound each request and nothing bounded their sum — see
36764
- * BATCH_FORWARD_BUDGET_MS. When the deadline passes the remainder is dropped
36765
- * rather than sent: the local write has already succeeded, so every caller
36766
- * has a correct result to return, and a drop is the outcome this path is
36767
- * built to accept (G8) where a blown hook timeout is not.
37694
+ * BATCH-ATOMIC SETTLEMENT is otherwise the rule: the receiver wraps a chunk in
37695
+ * one transaction, so a full 2xx settles every event in it and a non-2xx
37696
+ * settles none — which is why the whole chunk is stamped together on a FULL
37697
+ * accept and none of it otherwise. THREE reasons do not deserve whole-chunk
37698
+ * treatment, alongside a short accept, and all are re-sent one event at a
37699
+ * time:
36768
37700
  *
36769
- * Serial rather than concurrent on purpose. Firing N requests at once would
36770
- * trade a latency problem for a burst the plane's own per-key rate limiting
36771
- * would answer with the refusals the breaker then counts.
37701
+ * `invalid-request` a chunk the client refused to send at all. One malformed
37702
+ * event would otherwise cost the 49 good ones beside it —
37703
+ * a new way to lose data introduced by the very change
37704
+ * meant to stop losing it.
37705
+ * `route-absent` a deployment that predates the batch route. The
37706
+ * single-event route is the one it serves, and re-sending
37707
+ * here rather than inside the client is what gives each
37708
+ * request its own budget instead of 50 inside one.
37709
+ * `rejected` the deployment's SERVER-side twin of `invalid-request` —
37710
+ * a 4xx body refusal from schema drift on the other side
37711
+ * of the wire. Settlement is batch-atomic on this reason
37712
+ * exactly as on the others, so leaving it out would cost
37713
+ * the whole chunk for one event the DEPLOYMENT considers
37714
+ * malformed, where the per-item form cost only that one.
36772
37715
  *
36773
- * WHAT IS DROPPED IS COUNTED. Every other forward failure ends in
36774
- * `ForwardPolicy.run`'s catch and moves the breaker's file, which is what
36775
- * lets status call the forward unhealthy; this path returns BEFORE `run` is
36776
- * reached, so without the tally in `forward-drops.ts` a slow-but-answering
36777
- * plane produces no failures, keeps the breaker closed, renders a healthy
36778
- * block, and discards the tail of every batch indefinitely.
37716
+ * Every other reason (breaker-open, a refusal, a timeout) applies to the whole
37717
+ * chunk, and re-sending it item by item would just spend the budget failing 50
37718
+ * more times — for those, the blast radius stays exactly what it was before
37719
+ * batching.
36779
37720
  */
36780
37721
  async forwardBatch(inputs, toEvent) {
36781
37722
  const deadline = Date.now() + BATCH_FORWARD_BUDGET_MS;
36782
- for (let i = 0; i < inputs.length; i += 1) {
36783
- const now = Date.now();
36784
- if (now >= deadline) {
36785
- recordForwardDrops(this.deps.dataDir, inputs.length - i, now);
36786
- return;
37723
+ const delivered = [];
37724
+ try {
37725
+ for (let i = 0; i < inputs.length; i += AUDIT_EVENT_BATCH_MAX) {
37726
+ const now = Date.now();
37727
+ if (now >= deadline) {
37728
+ recordForwardDrops(this.deps.dataDir, inputs.length - i, now);
37729
+ return;
37730
+ }
37731
+ const chunk = inputs.slice(i, i + AUDIT_EVENT_BATCH_MAX).map((input2) => toEvent(input2));
37732
+ const forwarded = await this.deps.forward.run(
37733
+ () => this.deps.client.recordAuditEvents(
37734
+ chunk.map((event) => reKeyForForward(event, this.remoteInventory))
37735
+ )
37736
+ );
37737
+ if (forwarded.ok) {
37738
+ if (forwarded.value.accepted === chunk.length) {
37739
+ delivered.push(...chunk);
37740
+ continue;
37741
+ }
37742
+ } else if (
37743
+ // THREE reasons are worth a second pass, one at a time, and they are
37744
+ // the three settled BEFORE the control plane refused anything, or
37745
+ // (for `rejected`) refused the BODY rather than the connection.
37746
+ //
37747
+ // `invalid-request` — the CLIENT refused the body before any request
37748
+ // went out: a defect in one event, not an outage. Re-sending singly
37749
+ // isolates the bad one instead of charging its 49 neighbours for it.
37750
+ //
37751
+ // `route-absent` — the deployment predates the batch route and serves
37752
+ // only the single-event one. The retry IS the compatibility path, and
37753
+ // it has to live HERE rather than inside the client: each single gets
37754
+ // its own FORWARD_BUDGET_MS through `run`, whereas the client's own
37755
+ // fallback would spend 50 sequential round trips inside the ONE
37756
+ // budget wrapping this call — turning a working older deployment into
37757
+ // a timeout, three of those into an open breaker, and every row into
37758
+ // a silent drop while the status surface called an answering
37759
+ // deployment down.
37760
+ //
37761
+ // `rejected` — the deployment's own 4xx refusal of the body, the
37762
+ // server-side twin of `invalid-request`: isolating it the same way
37763
+ // costs one event instead of the whole chunk for a defect the
37764
+ // deployment considers local to one row.
37765
+ //
37766
+ // Every other reason (breaker-open, a refusal, a timeout) applies to
37767
+ // the whole chunk; re-sending it item by item would just spend the
37768
+ // budget failing 50 more times.
37769
+ forwarded.reason !== "invalid-request" && forwarded.reason !== "route-absent" && forwarded.reason !== "rejected"
37770
+ ) {
37771
+ continue;
37772
+ }
37773
+ for (const [j, event] of chunk.entries()) {
37774
+ const at = Date.now();
37775
+ if (at >= deadline) {
37776
+ recordForwardDrops(this.deps.dataDir, inputs.length - i - j, at);
37777
+ return;
37778
+ }
37779
+ const single = await this.deps.forward.run(
37780
+ () => this.deps.client.recordAuditEvent(reKeyForForward(event, this.remoteInventory))
37781
+ );
37782
+ if (single.ok) {
37783
+ delivered.push(event);
37784
+ continue;
37785
+ }
37786
+ if (single.reason === "breaker-open") {
37787
+ recordForwardDrops(this.deps.dataDir, inputs.length - i - j, at);
37788
+ return;
37789
+ }
37790
+ recordForwardDrops(this.deps.dataDir, 1, at);
37791
+ }
37792
+ }
37793
+ } finally {
37794
+ try {
37795
+ this.deps.local.markAuditEventsDelivered(delivered, Date.now());
37796
+ } catch {
36787
37797
  }
36788
- const input2 = inputs[i];
36789
- await this.deps.forward.run(
36790
- () => this.deps.client.recordAuditEvent(reKeyForForward(toEvent(input2), this.remoteInventory))
36791
- );
36792
37798
  }
36793
37799
  }
36794
37800
  // Delegated as a BATCH rather than looped over recordLlmCall: the inner
@@ -36831,9 +37837,10 @@ var AttachedDataGateway = class {
36831
37837
  // local store.
36832
37838
  async recordConfigScan(record2) {
36833
37839
  await this.deps.local.recordConfigScan(record2);
36834
- await this.deps.forward.run(
37840
+ const forwarded = await this.deps.forward.run(
36835
37841
  () => this.deps.client.recordAuditEvent(reKeyForForward(record2.scanEvent, this.remoteInventory))
36836
37842
  );
37843
+ if (forwarded.ok) this.deps.local.markAuditEventsDelivered([record2.scanEvent], Date.now());
36837
37844
  }
36838
37845
  async recordBlockedDetection(entry) {
36839
37846
  return this.deps.local.recordBlockedDetection(entry);
@@ -36967,6 +37974,18 @@ var AttachedDataGateway = class {
36967
37974
  // exactly what it did, leaving the whole control inert on every device
36968
37975
  // while every test around it stayed green.
36969
37976
  prohibitedModels: cached2.prohibitedModels
37977
+ // ALSO HONOURED FROM THE CACHE, and not a bundle field at all: each
37978
+ // merged policy's own `provenance`. `mergeRaiseOnly` spreads the policies
37979
+ // it emits, so an 'authored' policy arriving from the control plane
37980
+ // keeps that marker even where the clamp rebuilds it with a stronger
37981
+ // action. The device reads it in exactly one direction — the rules such a
37982
+ // policy targets are not locally re-assignable — so it sits on the
37983
+ // `prohibitedModels` side of the line for the same reason that field
37984
+ // does: it can only ever ADD a refusal, never relax one, and an unsigned
37985
+ // cache therefore has no relaxation to grant by carrying it. Dropping it
37986
+ // would be the silent failure rather than the safe one — the action would
37987
+ // still be enforced while the local override the organization authored
37988
+ // away quietly came back.
36970
37989
  // `rulesComplete` is a STANDALONE-ONLY signal (the user's local installed
36971
37990
  // snapshot) and is taken from the LOCAL bundle only — never from the wire
36972
37991
  // or the on-disk cache. Honoring a cached one would hand the control plane, or
@@ -37006,10 +38025,10 @@ var AttachedDataGateway = class {
37006
38025
  //
37007
38026
  // Implementing these is what actually closes the skipped-local-maintenance
37008
38027
  // gap: the OSS structural guard `hasLocalStoreMaintenance()` is satisfied by
37009
- // any object carrying all five, so the composite qualifies and SessionStart
38028
+ // any object carrying them all, so the composite qualifies and SessionStart
37010
38029
  // runs maintenance on the device's real store.
37011
38030
  //
37012
- // ⚠ Three of the six are SYNCHRONOUS and must stay that way. `handle-session-start`
38031
+ // ⚠ Several of them are SYNCHRONOUS and must stay that way. `handle-session-start`
37013
38032
  // calls `capWarnEraEnforcement` without `await` and uses `staleBinaryNotice`'s
37014
38033
  // return value directly; declaring them `async` here would hand those call
37015
38034
  // sites a Promise and silently break both.
@@ -37032,9 +38051,15 @@ var AttachedDataGateway = class {
37032
38051
  // Delegated like the rest, and SYNCHRONOUS for the reason the note above
37033
38052
  // gives: `recordCapture` calls it after the forward has already settled, on a
37034
38053
  // path that has nothing left to await.
38054
+ markCaptureOwed(event) {
38055
+ this.deps.local.markCaptureOwed(event);
38056
+ }
37035
38057
  markCaptureDelivered(event, atMs) {
37036
38058
  this.deps.local.markCaptureDelivered(event, atMs);
37037
38059
  }
38060
+ markAuditEventsDelivered(events, atMs) {
38061
+ this.deps.local.markAuditEventsDelivered(events, atMs);
38062
+ }
37038
38063
  };
37039
38064
  function reKeyForForward(event, remote) {
37040
38065
  if (remote === null) {
@@ -37077,281 +38102,17 @@ function toolAuditEvent(input2) {
37077
38102
  }
37078
38103
 
37079
38104
  // ../../packages/plugin-runtime/src/attached/history-state.ts
37080
- import { readFileSync as readFileSync15 } from "fs";
37081
- import { join as join24 } from "path";
38105
+ import { readFileSync as readFileSync16 } from "fs";
38106
+ import { join as join25 } from "path";
37082
38107
 
37083
38108
  // ../../packages/plugin-runtime/src/attached/history-sync.ts
37084
38109
  import { createHash as createHash6 } from "crypto";
37085
38110
  import { hostname as hostname5 } from "os";
37086
38111
 
37087
- // ../../packages/remote/src/http.ts
37088
- import { request as httpRequest } from "http";
37089
- import { request as httpsRequest } from "https";
37090
- var DEFAULT_TIMEOUT_MS = 1e4;
37091
- var MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
37092
- var RemoteRequestError = class extends Error {
37093
- constructor(status) {
37094
- super(`control-plane request failed with status ${String(status)}`);
37095
- this.status = status;
37096
- this.name = "RemoteRequestError";
37097
- }
37098
- status;
37099
- };
37100
- var RemoteRequestInvalid = class extends Error {
37101
- constructor(route, cause) {
37102
- super(`refusing to send a malformed body to ${route}`);
37103
- this.cause = cause;
37104
- this.name = "RemoteRequestInvalid";
37105
- }
37106
- cause;
37107
- };
37108
- var RemoteResponseInvalid = class extends Error {
37109
- constructor(route, detail) {
37110
- super(`control plane answered ${route} with ${detail}`);
37111
- this.name = "RemoteResponseInvalid";
37112
- }
37113
- };
37114
- var RemoteTransportError = class extends Error {
37115
- /**
37116
- * The status the peer sent, when headers arrived and only the BODY was
37117
- * refused.
37118
- *
37119
- * Undefined for the ordinary case this class was written for — no answer at
37120
- * all. It exists because two paths reject after a status has already been
37121
- * delivered: an oversized body and an aborted response. Discarding it there
37122
- * reported a deployment answering 401 with a verbose body as a network
37123
- * outage, which sends the reader to look at their network instead of their
37124
- * credential.
37125
- */
37126
- constructor(reason, status) {
37127
- super(`control-plane request did not complete: ${reason}`);
37128
- this.status = status;
37129
- this.name = "RemoteTransportError";
37130
- }
37131
- status;
37132
- };
37133
- async function send(options) {
37134
- const url2 = new URL(options.url);
37135
- const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
37136
- const send_ = url2.protocol === "http:" ? httpRequest : httpsRequest;
37137
- const requestOptions = {
37138
- method: options.method,
37139
- headers: {
37140
- // CALLER HEADERS FIRST, so this module's own are not overridable. Spread
37141
- // last they win, and two of the values below are ones no caller may
37142
- // replace: `x-api-key` is the credential, and `content-length` is the
37143
- // byte count that stops a multi-byte body being truncated by the
37144
- // receiver. `SendOptions.headers` is a free-form record on an exported
37145
- // function, so "no caller does that today" is not the guarantee to rely
37146
- // on. The one header any caller actually passes — `if-none-match` on the
37147
- // conditional GET — is untouched by this order.
37148
- ...options.headers,
37149
- // The credential. One header, matching what the deployment authenticates
37150
- // on; a second copy in an `Authorization` header would be one more place
37151
- // it can be logged by an intermediary for no gain.
37152
- //
37153
- // Spread conditionally rather than assigned as `undefined`: Node's header
37154
- // handling and `content-length` bookkeeping treat a present-but-undefined
37155
- // key differently from an absent one, and "the header is not there" is
37156
- // the property the attach flow needs.
37157
- ...options.apiKey === void 0 ? {} : { "x-api-key": options.apiKey },
37158
- accept: "application/json",
37159
- ...options.body === void 0 ? {} : {
37160
- "content-type": "application/json",
37161
- // Byte length, not string length: a multi-byte body sent with a
37162
- // character count is truncated by the receiver.
37163
- "content-length": String(Buffer.byteLength(options.body))
37164
- }
37165
- }
37166
- };
37167
- return new Promise((resolve2, reject) => {
37168
- let settled = false;
37169
- const fail = (reason, status) => {
37170
- if (settled) return;
37171
- settled = true;
37172
- reject(new RemoteTransportError(reason, status));
37173
- };
37174
- const req = send_(url2, requestOptions, (res) => {
37175
- const chunks = [];
37176
- let size = 0;
37177
- res.on("data", (chunk) => {
37178
- size += chunk.length;
37179
- if (size > MAX_RESPONSE_BYTES) {
37180
- fail(`response exceeded ${String(MAX_RESPONSE_BYTES)} bytes`, res.statusCode);
37181
- res.destroy();
37182
- req.destroy();
37183
- return;
37184
- }
37185
- chunks.push(chunk);
37186
- });
37187
- res.on("aborted", () => {
37188
- fail("the response was aborted", res.statusCode);
37189
- });
37190
- res.on("end", () => {
37191
- if (settled) return;
37192
- settled = true;
37193
- resolve2({
37194
- status: res.statusCode ?? 0,
37195
- headers: res.headers,
37196
- body: Buffer.concat(chunks).toString("utf8")
37197
- });
37198
- });
37199
- });
37200
- const deadline = setTimeout(() => {
37201
- fail(`no response within ${String(timeoutMs)}ms`);
37202
- req.destroy();
37203
- }, timeoutMs);
37204
- deadline.unref();
37205
- req.on("upgrade", (_res, socket) => {
37206
- fail("the deployment answered with a protocol upgrade");
37207
- socket.destroy();
37208
- });
37209
- req.on("close", () => {
37210
- fail("the connection closed before a response was read");
37211
- clearTimeout(deadline);
37212
- });
37213
- req.on("error", (err) => {
37214
- fail(err.message);
37215
- });
37216
- if (options.body !== void 0) req.write(options.body);
37217
- req.end();
37218
- });
37219
- }
37220
-
37221
- // ../../packages/remote/src/client.ts
37222
- var ROUTES = {
37223
- events: "/v1/events",
37224
- auditEvents: "/v1/audit-events",
37225
- auditEventsBatch: "/v1/audit-events/batch",
37226
- inventory: "/v1/inventory",
37227
- storePosture: "/v1/store-posture",
37228
- policyBundle: "/v1/policy-bundle",
37229
- whoami: "/v1/plugin/whoami",
37230
- shares: "/v1/shares"
37231
- };
37232
- function headerValue(response, name) {
37233
- const raw = response.headers[name];
37234
- if (raw === void 0) return void 0;
37235
- return Array.isArray(raw) ? raw[0] : raw;
37236
- }
37237
- function okBody(response) {
37238
- if (response.status < 200 || response.status >= 300) {
37239
- throw new RemoteRequestError(response.status);
37240
- }
37241
- return response.body;
37242
- }
37243
- function parsed(schema, body, route) {
37244
- let json2;
37245
- try {
37246
- json2 = JSON.parse(body);
37247
- } catch {
37248
- throw new RemoteResponseInvalid(route, "a body that is not JSON");
37249
- }
37250
- const result = schema.safeParse(json2);
37251
- if (!result.success) {
37252
- throw new RemoteResponseInvalid(route, "a body this client cannot read");
37253
- }
37254
- return result.data;
37255
- }
37256
- function withoutTrailingSlashes(endpoint) {
37257
- let end = endpoint.length;
37258
- while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH) end -= 1;
37259
- return endpoint.slice(0, end);
37260
- }
37261
- var SLASH = "/".charCodeAt(0);
37262
- function createRemoteClient(options) {
37263
- const base = withoutTrailingSlashes(options.endpoint);
37264
- const url2 = (route) => `${base}${route}`;
37265
- const common = { apiKey: options.apiKey, timeoutMs: options.timeoutMs };
37266
- const sendOne = async (event) => {
37267
- const validated = RecordAuditEventRequest.safeParse(event);
37268
- if (!validated.success) throw new RemoteRequestInvalid(ROUTES.auditEvents, validated.error);
37269
- const response = await send({
37270
- ...common,
37271
- method: "POST",
37272
- url: url2(ROUTES.auditEvents),
37273
- body: JSON.stringify(validated.data)
37274
- });
37275
- okBody(response);
37276
- };
37277
- return {
37278
- async ingestEvents(batch) {
37279
- const response = await send({
37280
- ...common,
37281
- method: "POST",
37282
- url: url2(ROUTES.events),
37283
- body: JSON.stringify(batch)
37284
- });
37285
- return parsed(IngestAck, okBody(response), ROUTES.events);
37286
- },
37287
- async ingestInventory(context) {
37288
- const response = await send({
37289
- ...common,
37290
- method: "POST",
37291
- url: url2(ROUTES.inventory),
37292
- body: JSON.stringify(context)
37293
- });
37294
- return parsed(ResolvedInventory, okBody(response), ROUTES.inventory);
37295
- },
37296
- async recordAuditEvent(event) {
37297
- await sendOne(event);
37298
- },
37299
- async recordAuditEvents(events) {
37300
- const validated = RecordAuditEventBatch.safeParse({ events });
37301
- if (!validated.success) {
37302
- throw new RemoteRequestInvalid(ROUTES.auditEventsBatch, validated.error);
37303
- }
37304
- const response = await send({
37305
- ...common,
37306
- method: "POST",
37307
- url: url2(ROUTES.auditEventsBatch),
37308
- body: JSON.stringify(validated.data)
37309
- });
37310
- if (response.status === 404) {
37311
- for (const event of validated.data.events) await sendOne(event);
37312
- return { accepted: validated.data.events.length };
37313
- }
37314
- return parsed(AuditEventBatchAck, okBody(response), ROUTES.auditEventsBatch);
37315
- },
37316
- async reportStorePosture(snapshot) {
37317
- const response = await send({
37318
- ...common,
37319
- method: "POST",
37320
- url: url2(ROUTES.storePosture),
37321
- body: JSON.stringify(snapshot)
37322
- });
37323
- okBody(response);
37324
- },
37325
- async getPolicyBundle(etag) {
37326
- const response = await send({
37327
- ...common,
37328
- method: "GET",
37329
- url: url2(ROUTES.policyBundle),
37330
- ...etag === void 0 ? {} : { headers: { "if-none-match": etag } }
37331
- });
37332
- if (response.status === 304) {
37333
- return { changed: false, etag: headerValue(response, "etag") ?? etag };
37334
- }
37335
- const bundle = parsed(PolicyBundle, okBody(response), ROUTES.policyBundle);
37336
- return { changed: true, bundle, etag: headerValue(response, "etag") };
37337
- },
37338
- async whoami() {
37339
- const response = await send({ ...common, method: "GET", url: url2(ROUTES.whoami) });
37340
- return parsed(PluginWhoami, okBody(response), ROUTES.whoami);
37341
- },
37342
- async recordProjectEgress(request) {
37343
- const validated = EgressIngestRequest.safeParse(request);
37344
- if (!validated.success) throw new RemoteRequestInvalid(ROUTES.shares, validated.error);
37345
- const response = await send({
37346
- ...common,
37347
- method: "POST",
37348
- url: url2(ROUTES.shares),
37349
- body: JSON.stringify(validated.data)
37350
- });
37351
- okBody(response);
37352
- }
37353
- };
37354
- }
38112
+ // ../../packages/plugin-runtime/src/attached/capture-rebuild.ts
38113
+ var CORRELATION_ID = EventMetadata.shape.correlationId;
38114
+ var TRACE_ID = EventMetadata.shape.traceId;
38115
+ var EXCEPTION_ID = EventMetadata.shape.exceptionIds.unwrap().element;
37355
38116
 
37356
38117
  // ../../packages/plugin-runtime/src/attached/history-sync-trigger.ts
37357
38118
  import { spawn } from "child_process";
@@ -37359,14 +38120,14 @@ import { fileURLToPath as fileURLToPath2 } from "url";
37359
38120
  var HISTORY_SYNC_THROTTLE_MS = 5 * 60 * 1e3;
37360
38121
 
37361
38122
  // ../../packages/plugin-runtime/src/attached/plugin-block.ts
37362
- import { readFileSync as readFileSync16 } from "fs";
38123
+ import { readFileSync as readFileSync17 } from "fs";
37363
38124
  var manifestBuildCache = /* @__PURE__ */ new Map();
37364
38125
  function readManifestBuild(manifestUrl, packageName) {
37365
38126
  const key = manifestUrl.href;
37366
38127
  if (!manifestBuildCache.has(key)) {
37367
38128
  let build;
37368
38129
  try {
37369
- const manifest = JSON.parse(readFileSync16(manifestUrl, "utf8"));
38130
+ const manifest = JSON.parse(readFileSync17(manifestUrl, "utf8"));
37370
38131
  build = typeof manifest.version === "string" && manifest.version.length > 0 ? { package: packageName, version: manifest.version } : void 0;
37371
38132
  } catch {
37372
38133
  build = void 0;
@@ -37393,7 +38154,7 @@ function createPluginBlock(build, policyStore) {
37393
38154
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
37394
38155
  import { randomUUID as randomUUID16 } from "crypto";
37395
38156
  import { readFile as readFile2, rm, writeFile as writeFile2 } from "fs/promises";
37396
- import { join as join25 } from "path";
38157
+ import { join as join26 } from "path";
37397
38158
 
37398
38159
  // ../../packages/plugin-runtime/src/attached/atomic-publish.ts
37399
38160
  import { rename as rename2 } from "fs/promises";
@@ -37417,7 +38178,7 @@ async function publishByRename(tmp, file2, move = rename2) {
37417
38178
 
37418
38179
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
37419
38180
  function createPolicyStore(dir = dataDir()) {
37420
- const file2 = join25(dir, "policy-cache.json");
38181
+ const file2 = join26(dir, "policy-cache.json");
37421
38182
  async function read() {
37422
38183
  try {
37423
38184
  const raw = await readFile2(file2, "utf8");
@@ -37426,22 +38187,32 @@ function createPolicyStore(dir = dataDir()) {
37426
38187
  const record2 = parsed2;
37427
38188
  const bundle = PolicyBundle.parse(record2.bundle);
37428
38189
  const fetchedAtMs = typeof record2.fetchedAtMs === "number" ? record2.fetchedAtMs : 0;
37429
- const etag = typeof record2.etag === "string" ? record2.etag : void 0;
38190
+ const stored = typeof record2.etag === "string" ? record2.etag : void 0;
38191
+ const replayable = record2.shapeId === POLICY_BUNDLE_SHAPE_ID || knowsMoreThanThisBuild(record2.shapeId);
38192
+ const etag = replayable ? stored : void 0;
37430
38193
  return { bundle, fetchedAtMs, ...etag === void 0 ? {} : { etag } };
37431
38194
  } catch {
37432
38195
  return null;
37433
38196
  }
37434
38197
  }
37435
- async function write(bundle, etag) {
37436
- await ensureDataDir(dir);
37437
- const stored = {
37438
- bundle,
37439
- fetchedAtMs: Date.now(),
37440
- ...etag === void 0 ? {} : { etag }
37441
- };
38198
+ function knowsMoreThanThisBuild(shapeId) {
38199
+ if (typeof shapeId !== "string" || shapeId === "") return false;
38200
+ const theirs = new Set(shapeId.split(","));
38201
+ const ours = new Set(POLICY_BUNDLE_SHAPE_ID.split(","));
38202
+ return theirs.size > ours.size && [...ours].every((key) => theirs.has(key));
38203
+ }
38204
+ async function priorRecord() {
38205
+ try {
38206
+ const parsed2 = JSON.parse(await readFile2(file2, "utf8"));
38207
+ return typeof parsed2 === "object" && parsed2 !== null ? parsed2 : null;
38208
+ } catch {
38209
+ return null;
38210
+ }
38211
+ }
38212
+ async function publishRecord(record2) {
37442
38213
  const tmp = `${file2}.${randomUUID16()}.tmp`;
37443
38214
  try {
37444
- await writeFile2(tmp, JSON.stringify(stored), {
38215
+ await writeFile2(tmp, JSON.stringify(record2), {
37445
38216
  encoding: "utf8",
37446
38217
  mode: DATA_FILE_MODE,
37447
38218
  flag: "wx"
@@ -37452,6 +38223,27 @@ function createPolicyStore(dir = dataDir()) {
37452
38223
  throw err;
37453
38224
  }
37454
38225
  }
38226
+ async function write(bundle, etag) {
38227
+ await ensureDataDir(dir);
38228
+ const prior = await priorRecord();
38229
+ const priorVersion = prior?.bundle?.version;
38230
+ if (prior !== null && knowsMoreThanThisBuild(prior.shapeId) && priorVersion === bundle.version) {
38231
+ await publishRecord({
38232
+ ...prior,
38233
+ fetchedAtMs: Date.now()
38234
+ });
38235
+ return;
38236
+ }
38237
+ await publishRecord({
38238
+ bundle,
38239
+ fetchedAtMs: Date.now(),
38240
+ // Stamped on EVERY write, the 304 arm's included: that arm hands back the
38241
+ // bundle it already holds, and the point of the stamp is to describe the
38242
+ // build that last narrowed those bytes, which is this one.
38243
+ shapeId: POLICY_BUNDLE_SHAPE_ID,
38244
+ ...etag === void 0 ? {} : { etag }
38245
+ });
38246
+ }
37455
38247
  return { read, write, file: file2 };
37456
38248
  }
37457
38249
 
@@ -37617,11 +38409,11 @@ function readStorePosture(dbPath2) {
37617
38409
  // ../../packages/plugin-runtime/src/attached/posture-store.ts
37618
38410
  import { randomUUID as randomUUID17 } from "crypto";
37619
38411
  import { readFile as readFile3, rm as rm2, writeFile as writeFile3 } from "fs/promises";
37620
- import { join as join26 } from "path";
38412
+ import { join as join27 } from "path";
37621
38413
  var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
37622
38414
  function createPostureStore(dir = settingsDir(), legacyDir) {
37623
- const file2 = join26(dir, "posture-state.json");
37624
- const legacyFile = legacyDir === void 0 ? null : join26(legacyDir, "posture-state.json");
38415
+ const file2 = join27(dir, "posture-state.json");
38416
+ const legacyFile = legacyDir === void 0 ? null : join27(legacyDir, "posture-state.json");
37625
38417
  async function persist(state) {
37626
38418
  await ensureDataDir(dir);
37627
38419
  const tmp = `${file2}.${randomUUID17()}.tmp`;
@@ -37689,8 +38481,8 @@ function createPostureStore(dir = settingsDir(), legacyDir) {
37689
38481
  }
37690
38482
 
37691
38483
  // ../../packages/plugin-runtime/src/attached/sync-state.ts
37692
- import { readFileSync as readFileSync17 } from "fs";
37693
- import { join as join27 } from "path";
38484
+ import { readFileSync as readFileSync18 } from "fs";
38485
+ import { join as join28 } from "path";
37694
38486
 
37695
38487
  // ../../packages/plugin-runtime/src/attached/status.ts
37696
38488
  var REFUSAL_LINES = {
@@ -38008,9 +38800,21 @@ var StandaloneDataGateway = class {
38008
38800
  // for the whole of it, so a member that threw would make that answer a lie
38009
38801
  // the moment a composite delegated to it. A store-level no-op is the honest
38010
38802
  // shape — a standalone machine has nothing delivered to record.
38803
+ markCaptureOwed(event) {
38804
+ this.db.markCaptureOwed(event);
38805
+ }
38011
38806
  markCaptureDelivered(event, atMs) {
38012
38807
  this.db.markCaptureDelivered(event, atMs);
38013
38808
  }
38809
+ // Implemented, not stubbed, for the same reason its sibling above is: the
38810
+ // attached gateway is a DECORATOR over an instance of this class
38811
+ // (`attached/factory.ts` builds one and passes it as `deps.local`), so every
38812
+ // stamp the live forward makes lands here with a non-empty array. This is the
38813
+ // production write path for that feature, not a shape-satisfying no-op — a
38814
+ // machine that is merely standalone simply never calls it.
38815
+ markAuditEventsDelivered(events, atMs) {
38816
+ this.db.markAuditEventsDelivered(events, atMs);
38817
+ }
38014
38818
  staleBinaryNotice(currentVersion) {
38015
38819
  try {
38016
38820
  const newest = this.db.installedPacks.newestRecordedBinary();
@@ -38149,11 +38953,11 @@ import { randomUUID as randomUUID19 } from "crypto";
38149
38953
  var EXCEPTION_RETENTION_MS = 90 * 24 * 60 * 60 * 1e3;
38150
38954
 
38151
38955
  // src/history/transcripts.ts
38152
- import { closeSync as closeSync3, openSync as openSync3, readdirSync as readdirSync5, readFileSync as readFileSync18, readSync as readSync2, statSync as statSync10 } from "fs";
38956
+ import { closeSync as closeSync3, openSync as openSync3, readdirSync as readdirSync5, readFileSync as readFileSync19, readSync as readSync2, statSync as statSync10 } from "fs";
38153
38957
  import { homedir as homedir3 } from "os";
38154
- import { join as join28 } from "path";
38958
+ import { join as join29 } from "path";
38155
38959
  function transcriptsDir(home) {
38156
- return join28(home ?? homedir3(), ".codex", "sessions");
38960
+ return join29(home ?? homedir3(), ".codex", "sessions");
38157
38961
  }
38158
38962
  function isRecord(value) {
38159
38963
  return typeof value === "object" && value !== null;
@@ -38392,7 +39196,7 @@ function* walkJsonlFiles(dir, depth = 0) {
38392
39196
  return;
38393
39197
  }
38394
39198
  for (const entry of entries) {
38395
- const full = join28(dir, entry.name);
39199
+ const full = join29(dir, entry.name);
38396
39200
  if (entry.isDirectory()) {
38397
39201
  yield* walkJsonlFiles(full, depth + 1);
38398
39202
  } else if (entry.isFile() && entry.name.endsWith(".jsonl")) {
@@ -38404,7 +39208,7 @@ function* iterateFileContents(dir) {
38404
39208
  for (const filePath of walkJsonlFiles(dir)) {
38405
39209
  try {
38406
39210
  statSync10(filePath);
38407
- yield { content: readFileSync18(filePath, "utf8"), filePath };
39211
+ yield { content: readFileSync19(filePath, "utf8"), filePath };
38408
39212
  } catch {
38409
39213
  }
38410
39214
  }
@@ -38525,11 +39329,11 @@ import {
38525
39329
  fstatSync as fstatSync2,
38526
39330
  mkdirSync as mkdirSync5,
38527
39331
  openSync as openSync4,
38528
- readFileSync as readFileSync19,
39332
+ readFileSync as readFileSync20,
38529
39333
  readSync as readSync3,
38530
39334
  writeFileSync as writeFileSync10
38531
39335
  } from "fs";
38532
- import { join as join29 } from "path";
39336
+ import { join as join30 } from "path";
38533
39337
 
38534
39338
  // src/history/usage.ts
38535
39339
  var NO_PROJECT_CWD = "/nonexistent/aka-reconciler/no-project";