@akasecurity/ai-tc-codex 0.9.9 → 0.9.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -493,11 +493,12 @@ var require_ignore = __commonJS({
493
493
 
494
494
  // ../../packages/plugin-sdk/src/config.ts
495
495
  import { existsSync as existsSync7 } from "fs";
496
- import { join as join12 } from "path";
496
+ import { join as join13 } from "path";
497
497
 
498
498
  // ../../packages/persistence/src/attached-derived.ts
499
499
  import { rmSync } from "fs";
500
500
  import { join } from "path";
501
+ var POLICY_CACHE_FILENAME = "policy-cache.json";
501
502
  var ATTACHED_FORWARD_STATE_FILENAME = "attached-state.json";
502
503
  var ATTACHED_FORWARD_DROPS_FILENAME = "attached-forward-drops.json";
503
504
 
@@ -598,6 +599,30 @@ var SQLITE_MIGRATIONS = [
598
599
  {
599
600
  tag: "0022_audit_inspection_ms",
600
601
  sql: "ALTER TABLE `audit_events` ADD `inspection_ms` integer GENERATED ALWAYS AS (json_extract(attributes, '$.inspection_ms')) VIRTUAL;"
602
+ },
603
+ {
604
+ tag: "0023_secret_vault_user_authorized",
605
+ sql: "ALTER TABLE `secret_vault` ADD `user_authorized` integer DEFAULT 0 NOT NULL;"
606
+ },
607
+ {
608
+ tag: "0024_finding_resolution_key_created_index",
609
+ sql: "DROP INDEX IF EXISTS `idx_finding_resolution_key`;--> statement-breakpoint\nCREATE INDEX `idx_finding_resolution_key_created` ON `finding_resolution` (`finding_key`,`created_at`);"
610
+ },
611
+ {
612
+ tag: "0025_audit_capture_attribute_columns",
613
+ sql: "ALTER TABLE `audit_events` ADD `source_tool` text GENERATED ALWAYS AS (json_extract(attributes, '$.source_tool')) VIRTUAL;--> statement-breakpoint\nALTER TABLE `audit_events` ADD `repo` text GENERATED ALWAYS AS (json_extract(attributes, '$.repo')) VIRTUAL;--> statement-breakpoint\nALTER TABLE `audit_events` ADD `file_path` text GENERATED ALWAYS AS (json_extract(attributes, '$.file_path')) VIRTUAL;--> statement-breakpoint\nALTER TABLE `audit_events` ADD `tool_name` text GENERATED ALWAYS AS (json_extract(attributes, '$.tool_name')) VIRTUAL;"
614
+ },
615
+ {
616
+ tag: "0026_audit_llm_call_usage_columns",
617
+ sql: "ALTER TABLE `audit_events` ADD `service_tier` text GENERATED ALWAYS AS (json_extract(attributes, '$.service_tier')) VIRTUAL;--> statement-breakpoint\nALTER TABLE `audit_events` ADD `ephemeral_1h_input_tokens` integer GENERATED ALWAYS AS (json_extract(attributes, '$.ephemeral_1h_input_tokens')) VIRTUAL;--> statement-breakpoint\nALTER TABLE `audit_events` ADD `ephemeral_5m_input_tokens` integer GENERATED ALWAYS AS (json_extract(attributes, '$.ephemeral_5m_input_tokens')) VIRTUAL;--> statement-breakpoint\nALTER TABLE `audit_events` ADD `web_search_requests` integer GENERATED ALWAYS AS (json_extract(attributes, '$.web_search_requests')) VIRTUAL;"
618
+ },
619
+ {
620
+ tag: "0027_audit_llm_usage_index",
621
+ sql: "CREATE INDEX `idx_audit_llm_usage` ON `audit_events` (`started_at`,`root_session_id`,`provider`,`model`,`service_tier`,`input_tokens`,`output_tokens`,`cache_creation_input_tokens`,`cache_read_input_tokens`,`ephemeral_1h_input_tokens`,`ephemeral_5m_input_tokens`,`web_search_requests`) WHERE event_type = 'llm_call' AND attributes IS NOT NULL;"
622
+ },
623
+ {
624
+ tag: "0028_activity_session_probe_indexes",
625
+ sql: "CREATE INDEX `idx_audit_session_prompt` ON `audit_events` (`root_session_id`) WHERE event_type = 'prompt';--> statement-breakpoint\nCREATE INDEX `idx_audit_session_share` ON `audit_events` (`root_session_id`) WHERE event_type = 'share';--> statement-breakpoint\nCREATE INDEX `idx_audit_ended_at` ON `audit_events` (`ended_at`,`root_session_id`) WHERE ended_at IS NOT NULL;--> statement-breakpoint\nCREATE INDEX `idx_audit_session_ended` ON `audit_events` (`root_session_id`,`ended_at`) WHERE ended_at IS NOT NULL;--> statement-breakpoint\n-- Expression index for the activity list's turns rollup: a live-captured\n-- session's turns are the DISTINCT `run_key` across its `llm_call` leaves, and\n-- carrying the extracted key in the index answers that count from the index\n-- alone instead of parsing every leaf's attribute bag. Written by hand, as\n-- 0013's `idx_audit_code_change_path` was: drizzle-kit cannot emit an\n-- expression containing a comma, so this index is not declared in sqlite.ts.\nCREATE INDEX `idx_audit_session_run_key` ON `audit_events` (`root_session_id`, json_extract(`attributes`, '$.run_key')) WHERE `event_type` = 'llm_call';\n"
601
626
  }
602
627
  ];
603
628
 
@@ -22140,6 +22165,26 @@ var AttachTokenResponse = external_exports.union([
22140
22165
  AttachTokenExpired,
22141
22166
  external_exports.object({ status: printable(64) })
22142
22167
  ]);
22168
+ var DeviceCommandKind = external_exports.enum(["shares_rescan"]);
22169
+ var DeviceCommand = external_exports.object({
22170
+ id: printable(128).min(1),
22171
+ kind: DeviceCommandKind,
22172
+ issuedAt: printable(64).min(1),
22173
+ expiresAt: printable(64).min(1)
22174
+ }).strict();
22175
+ var DeviceCommandPollResponse = external_exports.object({ command: DeviceCommand.nullable() });
22176
+ var DeviceCommandFailureReason = external_exports.enum(["scan_failed", "no_projects", "expired"]);
22177
+ var DeviceCommandAckBody = external_exports.discriminatedUnion("outcome", [
22178
+ external_exports.object({
22179
+ outcome: external_exports.literal("reported"),
22180
+ projectsScanned: external_exports.number().int().nonnegative()
22181
+ }).strict(),
22182
+ external_exports.object({
22183
+ outcome: external_exports.literal("failed"),
22184
+ reason: DeviceCommandFailureReason,
22185
+ projectsScanned: external_exports.number().int().nonnegative()
22186
+ }).strict()
22187
+ ]);
22143
22188
 
22144
22189
  // ../../packages/schema/src/zod/registry.ts
22145
22190
  var Namespace = external_exports.string().regex(/^[a-z][a-z0-9-]*$/);
@@ -22306,7 +22351,7 @@ var PackManifest = external_exports.object({
22306
22351
  }).meta({ id: "PackManifest" });
22307
22352
 
22308
22353
  // ../../packages/schema/src/zod/detection.ts
22309
- var OriginEnum = external_exports.enum(["library"]).meta({ id: "OriginEnum" });
22354
+ var OriginEnum = external_exports.enum(["library", "custom"]).meta({ id: "OriginEnum" });
22310
22355
  var DetectionFilterEnum = external_exports.enum(["all", "library", "custom", "customized", "updates"]);
22311
22356
  var LibraryStateEnum = external_exports.enum(["new", "imported", "update"]).meta({ id: "LibraryStateEnum" });
22312
22357
  var DetectionCounts = external_exports.object({
@@ -22443,14 +22488,17 @@ function optional2(key, parsed2, raw) {
22443
22488
  function isStringArray(value) {
22444
22489
  return Array.isArray(value) && value.every((entry) => typeof entry === "string");
22445
22490
  }
22491
+ var ORIGIN_VALUES = { library: true, custom: true };
22492
+ function resolveOrigin(origin) {
22493
+ return origin != null && Object.hasOwn(ORIGIN_VALUES, origin) ? origin : "library";
22494
+ }
22446
22495
  function summaryToDetectionListItem(s) {
22447
22496
  return {
22448
22497
  id: `${s.namespace}/${s.packId}`,
22449
22498
  name: s.name,
22450
22499
  version: s.version,
22451
22500
  enabled: s.enabled,
22452
- origin: "library",
22453
- // v1: every installed pack is library origin
22501
+ origin: resolveOrigin(s.origin),
22454
22502
  namespace: s.namespace,
22455
22503
  packId: s.packId,
22456
22504
  ruleCount: s.ruleCount,
@@ -22502,7 +22550,7 @@ function rowToDetectionDetail(row, findingsLast30d, update) {
22502
22550
  name: row.name,
22503
22551
  version: row.version,
22504
22552
  enabled: row.enabled,
22505
- origin: "library",
22553
+ origin: resolveOrigin(row.origin),
22506
22554
  namespace: row.namespace,
22507
22555
  packId: row.packId,
22508
22556
  ruleCount: row.rules.length,
@@ -22522,16 +22570,20 @@ function splitDetectionId(id) {
22522
22570
  }
22523
22571
  function buildDetectionsList(summaries, query) {
22524
22572
  const withUpdate = summaries.filter((s) => s.latestVersion != null);
22573
+ const originOf = (s) => resolveOrigin(s.origin);
22525
22574
  const counts = {
22526
22575
  all: summaries.length,
22527
- library: summaries.length,
22528
- // all origin=library in v1
22529
- custom: 0,
22576
+ library: summaries.filter((s) => originOf(s) === "library").length,
22577
+ custom: summaries.filter((s) => originOf(s) === "custom").length,
22578
+ // No origin member produces this, so it is 0 BY CONSTRUCTION rather than by
22579
+ // omission: `customized` would mean a LIBRARY pack whose rules were edited in
22580
+ // place, and that state does not exist — editing a library pack forks it. See
22581
+ // OriginEnum.
22530
22582
  customized: 0,
22531
22583
  updates: withUpdate.length
22532
22584
  };
22533
22585
  const filter = query.filter;
22534
- let filtered = filter === "custom" || filter === "customized" ? [] : filter === "updates" ? [...withUpdate] : [...summaries];
22586
+ let filtered = filter === "customized" ? [] : filter === "custom" ? summaries.filter((s) => originOf(s) === "custom") : filter === "library" ? summaries.filter((s) => originOf(s) === "library") : filter === "updates" ? [...withUpdate] : [...summaries];
22535
22587
  if (query.q) {
22536
22588
  const q = query.q.toLowerCase();
22537
22589
  filtered = filtered.filter(
@@ -22611,8 +22663,9 @@ var Event = external_exports.object({
22611
22663
  metadata: EventMetadata.optional()
22612
22664
  }).meta({ id: "Event" });
22613
22665
  var IngestEvent = Event.meta({ id: "IngestEvent" });
22666
+ var INGEST_BATCH_MAX = 100;
22614
22667
  var IngestBatch = external_exports.object({
22615
- events: external_exports.array(IngestEvent).min(1).max(100),
22668
+ events: external_exports.array(IngestEvent).min(1).max(INGEST_BATCH_MAX),
22616
22669
  // Dedup policy for this batch. Id-dedup ALWAYS applies. 'content-hash'
22617
22670
  // additionally rejects any event whose contentHash the store has already
22618
22671
  // recorded — for re-runnable bulk ingest (worktree scan, transcript
@@ -23168,375 +23221,11 @@ var PatchInstalledPackRequest = external_exports.object({
23168
23221
  message: "At least one field must be provided"
23169
23222
  }).meta({ id: "PatchInstalledPackRequest" });
23170
23223
 
23171
- // ../../packages/schema/src/zod/vault.ts
23172
- var POINTER_FORMAT_VERSION = 2;
23173
- var CATEGORY_ALTERNATION = DetectionCategory.options.join("|");
23174
- var POINTER_TOKEN_PATTERN = new RegExp(
23175
- `\\[\\[aka:(?:${CATEGORY_ALTERNATION}):[A-Z2-7]{2,7}\\.[A-Z2-7]{26}\\.[A-Z2-7]{16}\\]\\]`
23176
- );
23177
- var POINTER_TOKEN_ANCHORED = new RegExp(`^${POINTER_TOKEN_PATTERN.source}$`);
23178
- function pointerTokenScanner() {
23179
- return new RegExp(POINTER_TOKEN_PATTERN.source, "g");
23180
- }
23181
- var PointerToken = external_exports.string().regex(POINTER_TOKEN_ANCHORED);
23182
- var ParsedPointer = external_exports.object({
23183
- category: DetectionCategory,
23184
- keyVersion: external_exports.number().int().positive(),
23185
- pointerId: external_exports.string(),
23186
- tag: external_exports.string()
23187
- });
23188
- var VaultEntry = external_exports.object({
23189
- pointerId: external_exports.string(),
23190
- // The keyed HMAC of the raw value under `exception.key`, and the epoch it was
23191
- // derived under. This is what a reveal-to-model grant matches on, and it rotates
23192
- // independently of the vault encryption key below.
23193
- valueFingerprint: external_exports.string().regex(/^[0-9a-f]{64}$/),
23194
- fingerprintKeyVersion: external_exports.number().int().positive(),
23195
- // The vault-key epoch this row's ciphertext was sealed under.
23196
- keyVersion: external_exports.number().int().positive(),
23197
- // Fixed at first mint and never updated: the same value detected later under a
23198
- // different rule's category keeps the category it was minted with, so one
23199
- // value always produces exactly one wire token.
23200
- category: DetectionCategory,
23201
- ruleId: external_exports.string(),
23202
- // Partial-reveal preview for badges and listings. Never the raw value.
23203
- maskedMatch: external_exports.string(),
23204
- provider: external_exports.string().optional(),
23205
- ciphertext: external_exports.string(),
23206
- nonce: external_exports.string(),
23207
- authTag: external_exports.string(),
23208
- // How many times this value has been detected on this machine — the reuse
23209
- // signal the vault dashboard reads. Distinct from VaultDeref.pointerCount.
23210
- occurrenceCount: external_exports.number().int().nonnegative(),
23211
- firstSeen: external_exports.string(),
23212
- lastSeen: external_exports.string()
23213
- });
23214
- var PointerDescriptor = external_exports.object({
23215
- category: DetectionCategory,
23216
- provider: external_exports.string().optional(),
23217
- maskedMatch: external_exports.string(),
23218
- occurrences: external_exports.number().int().nonnegative(),
23219
- firstSeen: external_exports.string(),
23220
- lastSeen: external_exports.string()
23221
- });
23222
- var PointerIdentity = external_exports.object({
23223
- ruleId: external_exports.string(),
23224
- valueFingerprint: external_exports.string().regex(/^[0-9a-f]{64}$/),
23225
- fingerprintKeyVersion: external_exports.number().int().positive()
23226
- });
23227
- var DetokenizeTarget = external_exports.enum(["human", "model"]);
23228
- var VaultDerefReason = external_exports.enum([
23229
- "display",
23230
- "explicit-reveal",
23231
- "view-render",
23232
- "model-input",
23233
- "remediation",
23234
- "purge"
23235
- ]);
23236
- var VaultDerefOutcome = external_exports.enum(["revealed", "refused", "unavailable"]);
23237
- var VaultDeref = external_exports.object({
23238
- id: external_exports.guid(),
23239
- pointerId: external_exports.string(),
23240
- at: external_exports.string(),
23241
- target: DetokenizeTarget,
23242
- reason: VaultDerefReason,
23243
- outcome: VaultDerefOutcome,
23244
- // Present only on a model-target crossing that a reveal grant authorized.
23245
- grantId: external_exports.string().optional(),
23246
- // How many pointers ONE batched render resolved. 1 for unbatched rows. Named
23247
- // apart from VaultEntry.occurrenceCount, which counts detections of a value.
23248
- pointerCount: external_exports.number().int().positive().default(1)
23249
- });
23250
- var VaultSightingKind = external_exports.enum([
23251
- "prompt",
23252
- "tool-input",
23253
- "tool-output",
23254
- "file",
23255
- "transcript"
23256
- ]);
23257
- var VaultSighting = external_exports.object({
23258
- location: external_exports.string(),
23259
- kind: VaultSightingKind,
23260
- firstSeen: external_exports.string(),
23261
- lastSeen: external_exports.string()
23262
- });
23263
- var VaultInventoryEntry = external_exports.object({
23264
- pointerId: external_exports.string(),
23265
- category: DetectionCategory,
23266
- provider: external_exports.string().optional(),
23267
- maskedMatch: external_exports.string(),
23268
- occurrences: external_exports.number().int().nonnegative(),
23269
- firstSeen: external_exports.string(),
23270
- lastSeen: external_exports.string(),
23271
- // The active reveal-to-model grant covering this value, when one exists —
23272
- // the inventory badges it, the row links to revocation.
23273
- revealGrantId: external_exports.string().nullable(),
23274
- sightings: external_exports.array(VaultSighting)
23275
- });
23276
- var DEFAULT_VAULT_INVENTORY_LIMIT = 50;
23277
- var DEFAULT_VAULT_DEREFS_LIMIT = 50;
23278
- var MAX_VAULT_PAGE_LIMIT = 200;
23279
- var ListVaultInventoryQuery = external_exports.object({
23280
- limit: external_exports.coerce.number().int().min(1).max(MAX_VAULT_PAGE_LIMIT).optional(),
23281
- // Opaque; names the last row of the page just served.
23282
- cursor: external_exports.string().optional()
23283
- });
23284
- var ListVaultInventoryResponse = external_exports.object({
23285
- // Vaulted values across the whole store, not just this page — cursor-
23286
- // independent, so paging never changes what the count claims.
23287
- totals: external_exports.object({ values: external_exports.number().int().nonnegative() }),
23288
- items: external_exports.array(VaultInventoryEntry),
23289
- // `null` once the last page is reached.
23290
- nextCursor: external_exports.string().nullable()
23291
- });
23292
- var ListVaultReuseQuery = external_exports.object({
23293
- limit: external_exports.coerce.number().int().min(1).max(MAX_VAULT_PAGE_LIMIT).optional(),
23294
- cursor: external_exports.string().optional()
23295
- });
23296
- var ListVaultReuseResponse = external_exports.object({
23297
- // Reused values across the whole store — the number the section's claim
23298
- // ("values detected in more than one place") is about.
23299
- totals: external_exports.object({ reused: external_exports.number().int().nonnegative() }),
23300
- items: external_exports.array(VaultInventoryEntry),
23301
- nextCursor: external_exports.string().nullable()
23302
- });
23303
- var ListVaultDerefsQuery = external_exports.object({
23304
- // Include the batched, high-volume reasons (display, view-render). Omitted
23305
- // hides them and counts them into `hiddenBatched` instead, so the model
23306
- // crossings stay visible. A real boolean, not `z.stringbool()`: this arrives
23307
- // over a Server Action, which preserves the type, never as a URL param.
23308
- includeBatched: external_exports.boolean().optional(),
23309
- limit: external_exports.coerce.number().int().min(1).max(MAX_VAULT_PAGE_LIMIT).optional(),
23310
- cursor: external_exports.string().optional()
23311
- });
23312
- var ListVaultDerefsResponse = external_exports.object({
23313
- items: external_exports.array(VaultDeref),
23314
- nextCursor: external_exports.string().nullable(),
23315
- // Display/view-render rows the query hid, over the WHOLE trail rather than
23316
- // this page — it is the count the "N hidden" line and its toggle speak for.
23317
- // Always 0 when `includeBatched` was set, since nothing was hidden.
23318
- hiddenBatched: external_exports.number().int().nonnegative()
23319
- });
23320
- var VaultKeyCustody = external_exports.string();
23321
- var VaultInlineReveal = external_exports.enum(["masked", "full", "off"]);
23322
- var VAULT_CONSENT_VERSION = 1;
23323
- var VaultConsent = external_exports.object({
23324
- acknowledgedAt: external_exports.iso.datetime(),
23325
- version: external_exports.number().int().positive()
23326
- });
23327
-
23328
- // ../../packages/schema/src/zod/local.ts
23329
- var WORKSPACE_SETTINGS_SPEC_VERSION = 6;
23330
- var MODEL_JUDGE_PAYLOAD_VERSION = 1;
23331
- var RunMode = external_exports.enum(["standalone", "attached"]);
23332
- var ControlPlaneConnection = external_exports.object({
23333
- endpoint: external_exports.string().min(1),
23334
- // Display name for the deployment, shown instead of the raw endpoint.
23335
- label: external_exports.string().min(1).optional(),
23336
- attachedAt: external_exports.iso.datetime()
23337
- }).meta({ id: "ControlPlaneConnection" });
23338
- var SimpleDetectionPolicy = external_exports.enum(["redact", "warn"]);
23339
- var HistoricalAccess = external_exports.enum(["full", "session-only"]);
23340
- var ModelJudgeConsent = external_exports.object({
23341
- acknowledgedAt: external_exports.iso.datetime(),
23342
- payloadVersion: external_exports.number().int().positive()
23343
- });
23344
- var HistorySyncConsent = external_exports.object({
23345
- acknowledgedAt: external_exports.iso.datetime(),
23346
- payloadVersion: external_exports.number().int().positive(),
23347
- endpoint: external_exports.string()
23348
- });
23349
- var WorkspaceSettings = external_exports.object({
23350
- specVersion: external_exports.number().int().positive().default(WORKSPACE_SETTINGS_SPEC_VERSION),
23351
- runMode: RunMode.default("standalone"),
23352
- // Present only while attached; a detach clears it. Its presence is what makes
23353
- // `runMode: 'attached'` mean anything — see isAttached.
23354
- controlPlane: ControlPlaneConnection.optional(),
23355
- policy: SimpleDetectionPolicy.default("redact"),
23356
- // Consent for scanning pre-install surfaces; opt-in (see HistoricalAccess).
23357
- historicalAccess: HistoricalAccess.default("session-only"),
23358
- // In-place egress extraction on the scan paths; disable to stop all Data
23359
- // Shares writes.
23360
- dataSharesInPlace: external_exports.boolean().default(true),
23361
- // Consent to keep a RECOVERABLE encrypted copy of detected values in the local
23362
- // vault, instead of destroying them. Absent by default: this is a custody
23363
- // change from one-way redaction, so it is never an assumed grant on upgrade.
23364
- // Revoking stops future vaulting; it does not erase what is already stored —
23365
- // purging the vault is the eraser.
23366
- vaultConsent: VaultConsent.optional(),
23367
- // Where the vault master key lives.
23368
- vaultKeyCustody: VaultKeyCustody.default("file"),
23369
- // How a pointer renders in assistant prose on screen (see VaultInlineReveal).
23370
- vaultInlineReveal: VaultInlineReveal.default("masked"),
23371
- // Absent until /aka:setup completes; its presence is what "onboarded" means.
23372
- onboardedAt: external_exports.iso.datetime().optional(),
23373
- // Records that the user consented to sending findings to the model API for
23374
- // the /aka:setup judge, along with the payload-shape version they agreed to.
23375
- // Absent until granted; a stale payloadVersion means the consent no longer
23376
- // covers the current payload and must be re-granted.
23377
- modelJudgeConsent: ModelJudgeConsent.optional(),
23378
- // Records that the user consented to sending the activity already recorded on
23379
- // this machine to the deployment it is attached to, along with the payload
23380
- // shape and the endpoint they agreed to. Absent until granted, and a grant for
23381
- // a different endpoint or an older payload no longer counts.
23382
- historySyncConsent: HistorySyncConsent.optional()
23383
- });
23384
- function defaultWorkspaceSettings() {
23385
- return WorkspaceSettings.parse({});
23386
- }
23387
- function isAttached(settings) {
23388
- return settings.runMode === "attached" && settings.controlPlane !== void 0;
23389
- }
23390
- function toInventoryRow(input2, id, now) {
23391
- return {
23392
- id,
23393
- objectType: input2.objectType,
23394
- location: input2.location ?? null,
23395
- title: input2.title ?? null,
23396
- hostId: input2.hostId ?? null,
23397
- attributes: JSON.stringify(input2.attributes),
23398
- firstSeen: now,
23399
- lastSeen: now
23400
- };
23401
- }
23402
- function toSourceProjectRow(input2, id, now) {
23403
- return {
23404
- id,
23405
- url: input2.url,
23406
- name: input2.name ?? null,
23407
- attributes: JSON.stringify(input2.attributes),
23408
- firstSeen: now,
23409
- lastSeen: now
23410
- };
23411
- }
23412
- function toAuditEventRow(input2) {
23413
- return {
23414
- id: input2.id,
23415
- parentId: input2.parentId ?? null,
23416
- rootSessionId: input2.rootSessionId ?? null,
23417
- eventType: input2.eventType,
23418
- hostId: input2.hostId ?? null,
23419
- harnessId: input2.harnessId ?? null,
23420
- sourceProjectId: input2.sourceProjectId ?? null,
23421
- startedAt: isoToEpochMillis(input2.startedAt),
23422
- endedAt: input2.endedAt ? isoToEpochMillis(input2.endedAt) : null,
23423
- severity: input2.severity ?? null,
23424
- priority: input2.priority ?? null,
23425
- content: input2.content ?? null,
23426
- contentHash: input2.contentHash ?? null,
23427
- attributes: input2.attributes ? JSON.stringify(input2.attributes) : null
23428
- };
23429
- }
23430
- function toClassifiedDataRow(input2, id) {
23431
- return {
23432
- id,
23433
- class: input2.class,
23434
- label: input2.label ?? null,
23435
- attributes: input2.attributes ? JSON.stringify(input2.attributes) : null
23436
- };
23437
- }
23438
- function toInspectionDefinitionRow(input2, id) {
23439
- return {
23440
- id,
23441
- ruleId: input2.ruleId,
23442
- name: input2.name,
23443
- category: input2.category,
23444
- severity: input2.severity,
23445
- definition: input2.definition,
23446
- version: input2.version
23447
- };
23448
- }
23449
- function toInspectionFindingRow(input2) {
23450
- return {
23451
- id: input2.id,
23452
- auditEventId: input2.auditEventId,
23453
- inspectionDefinitionId: input2.inspectionDefinitionId,
23454
- classifiedDataId: input2.classifiedDataId ?? null,
23455
- spanStart: input2.span.start,
23456
- spanEnd: input2.span.end,
23457
- maskedMatch: input2.maskedMatch,
23458
- actionTaken: input2.actionTaken,
23459
- confidence: input2.confidence,
23460
- findingKey: input2.findingKey ?? null,
23461
- firstDetectedAt: input2.firstDetectedAt ? isoToEpochMillis(input2.firstDetectedAt) : null
23462
- };
23463
- }
23464
- function toCaptureAttributes(event) {
23465
- const metadata = event.metadata;
23466
- return {
23467
- source_tool: event.sourceTool,
23468
- ...metadata?.repo !== void 0 ? { repo: metadata.repo } : {},
23469
- ...metadata?.filePath !== void 0 ? { file_path: metadata.filePath } : {},
23470
- ...metadata?.toolName !== void 0 ? { tool_name: metadata.toolName } : {},
23471
- ...metadata?.gitignored !== void 0 ? { gitignored: metadata.gitignored } : {},
23472
- ...metadata?.wholeFile !== void 0 ? { whole_file: metadata.wholeFile } : {},
23473
- ...metadata?.correlationId !== void 0 ? { correlation_id: metadata.correlationId } : {},
23474
- ...metadata?.traceId !== void 0 ? { trace_id: metadata.traceId } : {},
23475
- ...metadata?.exceptionIds !== void 0 ? { exception_ids: metadata.exceptionIds } : {},
23476
- ...metadata?.inspectionMs !== void 0 ? { inspection_ms: metadata.inspectionMs } : {},
23477
- // `model`/`turnIndex` have no dedicated CaptureAttributes field (no writer
23478
- // has ever populated either), but every legacy metadata key still rides
23479
- // the bag rather than being silently dropped — CaptureAttributes'
23480
- // `.catchall(z.unknown())` carries the long tail.
23481
- ...metadata?.model !== void 0 ? { model: metadata.model } : {},
23482
- ...metadata?.turnIndex !== void 0 ? { turn_index: metadata.turnIndex } : {}
23483
- };
23484
- }
23485
- function captureDefinitionVersion(finding) {
23486
- return `capture/${finding.category}/${finding.severity}`;
23487
- }
23488
- function toCaptureDefinitionInput(finding) {
23489
- return {
23490
- ruleId: finding.ruleId,
23491
- version: captureDefinitionVersion(finding),
23492
- name: finding.ruleId,
23493
- category: finding.category,
23494
- severity: finding.severity,
23495
- definition: JSON.stringify({ ruleId: finding.ruleId })
23496
- };
23497
- }
23498
-
23499
- // ../../packages/schema/src/zod/managed.ts
23500
- var MANAGED_SETTINGS_FILENAME = "managed-settings.json";
23501
- var MANAGED_SETTINGS_SPEC_VERSION = 1;
23502
- var ManagedSettingKey = external_exports.enum([
23503
- "runMode",
23504
- "historicalAccess",
23505
- "vaultConsent",
23506
- "vaultKeyCustody",
23507
- "vaultInlineReveal",
23508
- "modelJudgeConsent",
23509
- "dataSharesInPlace"
23510
- ]).meta({ id: "ManagedSettingKey" });
23511
- var ManagedSettingsValues = external_exports.object({
23512
- runMode: external_exports.enum(["standalone", "attached"]).optional(),
23513
- controlPlane: external_exports.object({
23514
- endpoint: external_exports.string().min(1),
23515
- label: external_exports.string().min(1).optional()
23516
- }).optional(),
23517
- historicalAccess: external_exports.enum(["full", "session-only"]).optional(),
23518
- vaultConsent: external_exports.boolean().optional(),
23519
- vaultKeyCustody: external_exports.enum(["file", "keychain"]).optional(),
23520
- vaultInlineReveal: external_exports.enum(["masked", "full", "off"]).optional(),
23521
- modelJudgeConsent: external_exports.boolean().optional(),
23522
- dataSharesInPlace: external_exports.boolean().optional()
23523
- }).meta({ id: "ManagedSettingsValues" });
23524
- var ManagedSettings = external_exports.object({
23525
- specVersion: external_exports.number().int().positive().default(MANAGED_SETTINGS_SPEC_VERSION),
23526
- // Shown on every locked control, so the user can tell an administrative
23527
- // decision from a bug. Absent renders as a generic "your organization".
23528
- organization: external_exports.string().min(1).optional(),
23529
- // What the administrator pinned.
23530
- values: ManagedSettingsValues.default({}),
23531
- // Which of those the user may not change. A key here with no matching value
23532
- // freezes whatever the user last chose; a value with no lock is a DEFAULT
23533
- // the user may still override. The two are separable on purpose.
23534
- lockedFields: external_exports.array(ManagedSettingKey).default([])
23535
- }).meta({ id: "ManagedSettings" });
23536
-
23537
23224
  // ../../packages/schema/src/zod/policy.ts
23538
23225
  var PolicyScope = external_exports.enum(["global", "repo", "user"]).meta({ id: "PolicyScope" });
23539
23226
  var PolicyTarget = external_exports.union([external_exports.object({ ruleId: external_exports.string() }), external_exports.object({ category: DetectionCategory })]).meta({ id: "PolicyTarget" });
23227
+ var PolicyKind = external_exports.enum(["builtin", "custom"]).meta({ id: "PolicyKind" });
23228
+ var PolicyProvenance = external_exports.enum(["builtin", "authored"]).meta({ id: "PolicyProvenance" });
23540
23229
  var Policy = external_exports.object({
23541
23230
  id: external_exports.guid(),
23542
23231
  scope: PolicyScope,
@@ -23546,7 +23235,27 @@ var Policy = external_exports.object({
23546
23235
  customKeywords: external_exports.array(external_exports.string()).optional(),
23547
23236
  // Display name — optional so older policy rows without name still parse.
23548
23237
  // Added for the findings API (policy.name column migration).
23549
- name: external_exports.string().optional()
23238
+ name: external_exports.string().optional(),
23239
+ // Whether an AUTHORED policy governs this row's target — not a claim about
23240
+ // which row this is. A producer that collapses several rows onto one target
23241
+ // must carry the marker onto whichever row survives, or the collapse decides
23242
+ // the answer; a survivor may therefore be a built-in expansion still marked
23243
+ // 'authored' because an authored sibling targeted the same thing.
23244
+ // Optional so an older producer — and an older on-disk cache — still parses;
23245
+ // absent reads as 'builtin', which is the behaviour that predates the field.
23246
+ //
23247
+ // Deliberately NOT `kind`/PolicyKind: that name and that enum answer which
23248
+ // built-in archetype catalog entry a policy is, which every catalog surface
23249
+ // reads and which a caller may state. This one is a statement the PRODUCER
23250
+ // of a bundle makes about a row, and only the bundle builder ever stamps it
23251
+ // — the CRUD routes neither accept nor set it.
23252
+ //
23253
+ // A device consumes this in exactly one direction: an 'authored' policy
23254
+ // arriving from a control plane marks the rules it targets as not
23255
+ // locally re-assignable. That can only ever ADD a refusal, never relax one,
23256
+ // which is what makes it safe to honour from an unsigned cache — the same
23257
+ // test `prohibitedModels` passes and `reversibleRuleIds` fails.
23258
+ provenance: PolicyProvenance.optional()
23550
23259
  }).meta({ id: "Policy" });
23551
23260
  var PolicyBundle = external_exports.object({
23552
23261
  version: external_exports.string(),
@@ -23598,6 +23307,12 @@ var PolicyBundle = external_exports.object({
23598
23307
  customKeywords: external_exports.array(external_exports.string()),
23599
23308
  fetchedAt: external_exports.iso.datetime()
23600
23309
  }).meta({ id: "PolicyBundle" });
23310
+ var POLICY_BUNDLE_SHAPE_ID = [
23311
+ ...Object.keys(PolicyBundle.shape),
23312
+ ...Object.keys(Policy.shape).map((key) => `policies.${key}`),
23313
+ ...PolicyTarget.options.flatMap((member) => "shape" in member ? Object.keys(member.shape) : []).map((key) => `policies.target.${key}`),
23314
+ ...Object.keys(ExceptionBundleEntry.shape).map((key) => `exceptions.${key}`)
23315
+ ].sort().join(",");
23601
23316
  var OBSERVE_ONLY_CATEGORIES = ["config"];
23602
23317
  var ENFORCEABLE_CATEGORIES = DetectionCategory.options.filter((c) => !OBSERVE_ONLY_CATEGORIES.includes(c));
23603
23318
  var CATEGORY_PEAK_SEVERITY = {
@@ -23618,9 +23333,11 @@ function severityFloorPolicy(category) {
23618
23333
  const peak = CATEGORY_PEAK_SEVERITY[category];
23619
23334
  return peak === "critical" || peak === "high" ? "warn" : "monitor";
23620
23335
  }
23621
- var PolicyKind = external_exports.enum(["builtin", "custom"]).meta({ id: "PolicyKind" });
23622
23336
  var KNOWN_BUILTIN_IDS = ["monitor", "warn", "redact", "vault", "block"];
23623
23337
  var BuiltinPolicyId = external_exports.enum(KNOWN_BUILTIN_IDS).meta({ id: "BuiltinPolicyId" });
23338
+ var RedactFallback = BuiltinPolicyId.extract(["monitor", "warn", "block"]).meta({
23339
+ id: "RedactFallback"
23340
+ });
23624
23341
  var BUILTIN_ORDER = KNOWN_BUILTIN_IDS;
23625
23342
  var BUILTIN_POLICY_SPECS = {
23626
23343
  monitor: {
@@ -23657,6 +23374,42 @@ var BUILTIN_POLICY_SPECS = {
23657
23374
  function builtinPolicyToAction(id) {
23658
23375
  return BUILTIN_POLICY_SPECS[id].action;
23659
23376
  }
23377
+ var PALETTE_WEAKEST_FIRST = [
23378
+ ...new Set(KNOWN_BUILTIN_IDS.map(builtinPolicyToAction))
23379
+ ];
23380
+ var BELOW_PALETTE = ACTION_TAKEN_KEYS.filter(
23381
+ (action) => !PALETTE_WEAKEST_FIRST.includes(action)
23382
+ );
23383
+ var ACTION_STRENGTH_ORDER = [
23384
+ ...BELOW_PALETTE,
23385
+ ...PALETTE_WEAKEST_FIRST
23386
+ ];
23387
+ function actionRank(action) {
23388
+ return ACTION_STRENGTH_ORDER.indexOf(action);
23389
+ }
23390
+ function isActionAtLeast(action, floor) {
23391
+ return actionRank(action) >= actionRank(floor);
23392
+ }
23393
+ function strongerAction(a, b) {
23394
+ return actionRank(a) >= actionRank(b) ? a : b;
23395
+ }
23396
+ function weakestBuiltinAtLeast(floor) {
23397
+ return KNOWN_BUILTIN_IDS.find((id) => isActionAtLeast(builtinPolicyToAction(id), floor)) ?? "block";
23398
+ }
23399
+ var PackPolicyFloor = external_exports.object({
23400
+ /**
23401
+ * The weakest archetype the device may assign. Stated as a BuiltinPolicyId
23402
+ * rather than a raw ActionTaken because that is the vocabulary the user
23403
+ * picks from — a floor a UI cannot name is one it cannot explain.
23404
+ */
23405
+ floor: BuiltinPolicyId,
23406
+ /**
23407
+ * True when the organization AUTHORED a policy governing this pack rather
23408
+ * than stating a minimum: it gave the answer, so the pack is not
23409
+ * re-assignable locally in either direction.
23410
+ */
23411
+ locked: external_exports.boolean()
23412
+ }).describe("PackPolicyFloor");
23660
23413
  var CATEGORY_EXPRESSIBLE_IDS = KNOWN_BUILTIN_IDS.filter(
23661
23414
  (id) => !BUILTIN_POLICY_SPECS[id].reversible
23662
23415
  );
@@ -23714,6 +23467,397 @@ var PolicyStatsResponse = external_exports.object({
23714
23467
  detectionsGoverned: external_exports.number().int().nonnegative()
23715
23468
  }).meta({ id: "PolicyStatsResponse" });
23716
23469
 
23470
+ // ../../packages/schema/src/zod/vault.ts
23471
+ var POINTER_FORMAT_VERSION = 2;
23472
+ var CATEGORY_ALTERNATION = DetectionCategory.options.join("|");
23473
+ var POINTER_TOKEN_PATTERN = new RegExp(
23474
+ `\\[\\[aka:(?:${CATEGORY_ALTERNATION}):[A-Z2-7]{2,7}\\.[A-Z2-7]{26}\\.[A-Z2-7]{16}\\]\\]`
23475
+ );
23476
+ var POINTER_TOKEN_ANCHORED = new RegExp(`^${POINTER_TOKEN_PATTERN.source}$`);
23477
+ function pointerTokenScanner() {
23478
+ return new RegExp(POINTER_TOKEN_PATTERN.source, "g");
23479
+ }
23480
+ var PointerToken = external_exports.string().regex(POINTER_TOKEN_ANCHORED);
23481
+ var ParsedPointer = external_exports.object({
23482
+ category: DetectionCategory,
23483
+ keyVersion: external_exports.number().int().positive(),
23484
+ pointerId: external_exports.string(),
23485
+ tag: external_exports.string()
23486
+ });
23487
+ var VaultEntry = external_exports.object({
23488
+ pointerId: external_exports.string(),
23489
+ // The keyed HMAC of the raw value under `exception.key`, and the epoch it was
23490
+ // derived under. This is what a reveal-to-model grant matches on, and it rotates
23491
+ // independently of the vault encryption key below.
23492
+ valueFingerprint: external_exports.string().regex(/^[0-9a-f]{64}$/),
23493
+ fingerprintKeyVersion: external_exports.number().int().positive(),
23494
+ // The vault-key epoch this row's ciphertext was sealed under.
23495
+ keyVersion: external_exports.number().int().positive(),
23496
+ // Fixed at first mint and never updated: the same value detected later under a
23497
+ // different rule's category keeps the category it was minted with, so one
23498
+ // value always produces exactly one wire token.
23499
+ category: DetectionCategory,
23500
+ ruleId: external_exports.string(),
23501
+ // Partial-reveal preview for badges and listings. Never the raw value.
23502
+ maskedMatch: external_exports.string(),
23503
+ provider: external_exports.string().optional(),
23504
+ ciphertext: external_exports.string(),
23505
+ nonce: external_exports.string(),
23506
+ authTag: external_exports.string(),
23507
+ // How many times this value has been detected on this machine — the reuse
23508
+ // signal the vault dashboard reads. Distinct from VaultDeref.pointerCount.
23509
+ occurrenceCount: external_exports.number().int().nonnegative(),
23510
+ // True when a PERSON asked for this value to be replaced — the surfaced-
23511
+ // secrets strike — rather than a pack enforcing its assignment. One value is
23512
+ // one row however many paths vault it, so this is what tells a policy sweep
23513
+ // that the row carries somebody's own instruction and not just an assignment
23514
+ // that has since been lowered. STICKY and MONOTONIC: a later automatic
23515
+ // vaulting of the same value must never clear it — what the user said about
23516
+ // the value does not expire.
23517
+ userAuthorized: external_exports.boolean(),
23518
+ firstSeen: external_exports.string(),
23519
+ lastSeen: external_exports.string()
23520
+ });
23521
+ var PointerDescriptor = external_exports.object({
23522
+ category: DetectionCategory,
23523
+ provider: external_exports.string().optional(),
23524
+ maskedMatch: external_exports.string(),
23525
+ occurrences: external_exports.number().int().nonnegative(),
23526
+ firstSeen: external_exports.string(),
23527
+ lastSeen: external_exports.string()
23528
+ });
23529
+ var PointerIdentity = external_exports.object({
23530
+ ruleId: external_exports.string(),
23531
+ valueFingerprint: external_exports.string().regex(/^[0-9a-f]{64}$/),
23532
+ fingerprintKeyVersion: external_exports.number().int().positive()
23533
+ });
23534
+ var DetokenizeTarget = external_exports.enum(["human", "model"]);
23535
+ var VaultDerefReason = external_exports.enum([
23536
+ "display",
23537
+ "explicit-reveal",
23538
+ "view-render",
23539
+ "model-input",
23540
+ "remediation",
23541
+ "purge"
23542
+ ]);
23543
+ var VaultDerefOutcome = external_exports.enum(["revealed", "refused", "unavailable"]);
23544
+ var VaultDeref = external_exports.object({
23545
+ id: external_exports.guid(),
23546
+ pointerId: external_exports.string(),
23547
+ at: external_exports.string(),
23548
+ target: DetokenizeTarget,
23549
+ reason: VaultDerefReason,
23550
+ outcome: VaultDerefOutcome,
23551
+ // Present only on a model-target crossing that a reveal grant authorized.
23552
+ grantId: external_exports.string().optional(),
23553
+ // How many pointers ONE batched render resolved. 1 for unbatched rows. Named
23554
+ // apart from VaultEntry.occurrenceCount, which counts detections of a value.
23555
+ pointerCount: external_exports.number().int().positive().default(1)
23556
+ });
23557
+ var VaultSightingKind = external_exports.enum([
23558
+ "prompt",
23559
+ "tool-input",
23560
+ "tool-output",
23561
+ "file",
23562
+ "transcript"
23563
+ ]);
23564
+ var VaultSighting = external_exports.object({
23565
+ location: external_exports.string(),
23566
+ kind: VaultSightingKind,
23567
+ firstSeen: external_exports.string(),
23568
+ lastSeen: external_exports.string()
23569
+ });
23570
+ var VaultInventoryEntry = external_exports.object({
23571
+ pointerId: external_exports.string(),
23572
+ category: DetectionCategory,
23573
+ provider: external_exports.string().optional(),
23574
+ maskedMatch: external_exports.string(),
23575
+ occurrences: external_exports.number().int().nonnegative(),
23576
+ firstSeen: external_exports.string(),
23577
+ lastSeen: external_exports.string(),
23578
+ // The active reveal-to-model grant covering this value, when one exists —
23579
+ // the inventory badges it, the row links to revocation.
23580
+ revealGrantId: external_exports.string().nullable(),
23581
+ sightings: external_exports.array(VaultSighting)
23582
+ });
23583
+ var DEFAULT_VAULT_INVENTORY_LIMIT = 50;
23584
+ var DEFAULT_VAULT_DEREFS_LIMIT = 50;
23585
+ var MAX_VAULT_PAGE_LIMIT = 200;
23586
+ var ListVaultInventoryQuery = external_exports.object({
23587
+ limit: external_exports.coerce.number().int().min(1).max(MAX_VAULT_PAGE_LIMIT).optional(),
23588
+ // Opaque; names the last row of the page just served.
23589
+ cursor: external_exports.string().optional()
23590
+ });
23591
+ var ListVaultInventoryResponse = external_exports.object({
23592
+ // Vaulted values across the whole store, not just this page — cursor-
23593
+ // independent, so paging never changes what the count claims.
23594
+ totals: external_exports.object({ values: external_exports.number().int().nonnegative() }),
23595
+ items: external_exports.array(VaultInventoryEntry),
23596
+ // `null` once the last page is reached.
23597
+ nextCursor: external_exports.string().nullable()
23598
+ });
23599
+ var ListVaultReuseQuery = external_exports.object({
23600
+ limit: external_exports.coerce.number().int().min(1).max(MAX_VAULT_PAGE_LIMIT).optional(),
23601
+ cursor: external_exports.string().optional()
23602
+ });
23603
+ var ListVaultReuseResponse = external_exports.object({
23604
+ // Reused values across the whole store — the number the section's claim
23605
+ // ("values detected in more than one place") is about.
23606
+ totals: external_exports.object({ reused: external_exports.number().int().nonnegative() }),
23607
+ items: external_exports.array(VaultInventoryEntry),
23608
+ nextCursor: external_exports.string().nullable()
23609
+ });
23610
+ var ListVaultDerefsQuery = external_exports.object({
23611
+ // Include the batched, high-volume reasons (display, view-render). Omitted
23612
+ // hides them and counts them into `hiddenBatched` instead, so the model
23613
+ // crossings stay visible. A real boolean, not `z.stringbool()`: this arrives
23614
+ // over a Server Action, which preserves the type, never as a URL param.
23615
+ includeBatched: external_exports.boolean().optional(),
23616
+ limit: external_exports.coerce.number().int().min(1).max(MAX_VAULT_PAGE_LIMIT).optional(),
23617
+ cursor: external_exports.string().optional()
23618
+ });
23619
+ var ListVaultDerefsResponse = external_exports.object({
23620
+ items: external_exports.array(VaultDeref),
23621
+ nextCursor: external_exports.string().nullable(),
23622
+ // Display/view-render rows the query hid, over the WHOLE trail rather than
23623
+ // this page — it is the count the "N hidden" line and its toggle speak for.
23624
+ // Always 0 when `includeBatched` was set, since nothing was hidden.
23625
+ hiddenBatched: external_exports.number().int().nonnegative()
23626
+ });
23627
+ var VaultKeyCustody = external_exports.string();
23628
+ var VaultInlineReveal = external_exports.enum(["masked", "full", "off"]);
23629
+ var VAULT_CONSENT_VERSION = 1;
23630
+ var VaultConsent = external_exports.object({
23631
+ acknowledgedAt: external_exports.iso.datetime(),
23632
+ version: external_exports.number().int().positive()
23633
+ });
23634
+
23635
+ // ../../packages/schema/src/zod/local.ts
23636
+ var WORKSPACE_SETTINGS_SPEC_VERSION = 7;
23637
+ var MODEL_JUDGE_PAYLOAD_VERSION = 1;
23638
+ var RunMode = external_exports.enum(["standalone", "attached"]);
23639
+ var ControlPlaneConnection = external_exports.object({
23640
+ endpoint: external_exports.string().min(1),
23641
+ // Display name for the deployment, shown instead of the raw endpoint.
23642
+ label: external_exports.string().min(1).optional(),
23643
+ attachedAt: external_exports.iso.datetime()
23644
+ }).meta({ id: "ControlPlaneConnection" });
23645
+ var SimpleDetectionPolicy = external_exports.enum(["redact", "warn"]);
23646
+ var HistoricalAccess = external_exports.enum(["full", "session-only"]);
23647
+ var ModelJudgeConsent = external_exports.object({
23648
+ acknowledgedAt: external_exports.iso.datetime(),
23649
+ payloadVersion: external_exports.number().int().positive()
23650
+ });
23651
+ var HistorySyncConsent = external_exports.object({
23652
+ acknowledgedAt: external_exports.iso.datetime(),
23653
+ payloadVersion: external_exports.number().int().positive(),
23654
+ endpoint: external_exports.string()
23655
+ });
23656
+ var WorkspaceSettings = external_exports.object({
23657
+ specVersion: external_exports.number().int().positive().default(WORKSPACE_SETTINGS_SPEC_VERSION),
23658
+ runMode: RunMode.default("standalone"),
23659
+ // Present only while attached; a detach clears it. Its presence is what makes
23660
+ // `runMode: 'attached'` mean anything — see isAttached.
23661
+ controlPlane: ControlPlaneConnection.optional(),
23662
+ policy: SimpleDetectionPolicy.default("redact"),
23663
+ // Consent for scanning pre-install surfaces; opt-in (see HistoricalAccess).
23664
+ historicalAccess: HistoricalAccess.default("session-only"),
23665
+ // In-place egress extraction on the scan paths; disable to stop all Data
23666
+ // Shares writes.
23667
+ dataSharesInPlace: external_exports.boolean().default(true),
23668
+ // Consent to keep a RECOVERABLE encrypted copy of detected values in the local
23669
+ // vault, instead of destroying them. Absent by default: this is a custody
23670
+ // change from one-way redaction, so it is never an assumed grant on upgrade.
23671
+ // Revoking stops future vaulting; it does not erase what is already stored —
23672
+ // purging the vault is the eraser.
23673
+ vaultConsent: VaultConsent.optional(),
23674
+ // Where the vault master key lives.
23675
+ vaultKeyCustody: VaultKeyCustody.default("file"),
23676
+ // How a pointer renders in assistant prose on screen (see VaultInlineReveal).
23677
+ vaultInlineReveal: VaultInlineReveal.default("masked"),
23678
+ // What a `redact` policy degrades to on a FIELD the host cannot rewrite in
23679
+ // place. Not a handling policy: the policy has already resolved to redact,
23680
+ // and this only says what happens when the host offers no channel to carry it
23681
+ // out — Antigravity's PreToolUse has no updatedInput at all, and Codex and
23682
+ // Claude Code decline to mask a field that EXECUTES because masking would
23683
+ // change what runs. Per FIELD rather than per host, so a host that can
23684
+ // rewrite some inputs keeps true redaction on those.
23685
+ //
23686
+ // Spelled in the built-in policy vocabulary rather than as a fresh enum, so
23687
+ // an attached machine's merge is `strongerAction` over the one action ladder
23688
+ // and no second rank order exists to drift from it. 'deny' is a host wire
23689
+ // word and stays out of the stored value.
23690
+ redactFallback: RedactFallback.default("warn"),
23691
+ // Absent until /aka:setup completes; its presence is what "onboarded" means.
23692
+ onboardedAt: external_exports.iso.datetime().optional(),
23693
+ // Records that the user consented to sending findings to the model API for
23694
+ // the /aka:setup judge, along with the payload-shape version they agreed to.
23695
+ // Absent until granted; a stale payloadVersion means the consent no longer
23696
+ // covers the current payload and must be re-granted.
23697
+ modelJudgeConsent: ModelJudgeConsent.optional(),
23698
+ // Records that the user consented to the DEFERRED send — the outbox — along
23699
+ // with the payload shape and the endpoint they agreed to. Since payload v2
23700
+ // that covers both the pre-attach backlog and undelivered captures (which
23701
+ // carry prompt/reply text in `content`); the key name predates the widening.
23702
+ // Absent until granted, and a grant for a different endpoint or an older
23703
+ // payload no longer counts.
23704
+ historySyncConsent: HistorySyncConsent.optional()
23705
+ });
23706
+ function defaultWorkspaceSettings() {
23707
+ return WorkspaceSettings.parse({});
23708
+ }
23709
+ function isAttached(settings) {
23710
+ return settings.runMode === "attached" && settings.controlPlane !== void 0;
23711
+ }
23712
+ function toInventoryRow(input2, id, now) {
23713
+ return {
23714
+ id,
23715
+ objectType: input2.objectType,
23716
+ location: input2.location ?? null,
23717
+ title: input2.title ?? null,
23718
+ hostId: input2.hostId ?? null,
23719
+ attributes: JSON.stringify(input2.attributes),
23720
+ firstSeen: now,
23721
+ lastSeen: now
23722
+ };
23723
+ }
23724
+ function toSourceProjectRow(input2, id, now) {
23725
+ return {
23726
+ id,
23727
+ url: input2.url,
23728
+ name: input2.name ?? null,
23729
+ attributes: JSON.stringify(input2.attributes),
23730
+ firstSeen: now,
23731
+ lastSeen: now
23732
+ };
23733
+ }
23734
+ function toAuditEventRow(input2) {
23735
+ return {
23736
+ id: input2.id,
23737
+ parentId: input2.parentId ?? null,
23738
+ rootSessionId: input2.rootSessionId ?? null,
23739
+ eventType: input2.eventType,
23740
+ hostId: input2.hostId ?? null,
23741
+ harnessId: input2.harnessId ?? null,
23742
+ sourceProjectId: input2.sourceProjectId ?? null,
23743
+ startedAt: isoToEpochMillis(input2.startedAt),
23744
+ endedAt: input2.endedAt ? isoToEpochMillis(input2.endedAt) : null,
23745
+ severity: input2.severity ?? null,
23746
+ priority: input2.priority ?? null,
23747
+ content: input2.content ?? null,
23748
+ contentHash: input2.contentHash ?? null,
23749
+ attributes: input2.attributes ? JSON.stringify(input2.attributes) : null
23750
+ };
23751
+ }
23752
+ function toClassifiedDataRow(input2, id) {
23753
+ return {
23754
+ id,
23755
+ class: input2.class,
23756
+ label: input2.label ?? null,
23757
+ attributes: input2.attributes ? JSON.stringify(input2.attributes) : null
23758
+ };
23759
+ }
23760
+ function toInspectionDefinitionRow(input2, id) {
23761
+ return {
23762
+ id,
23763
+ ruleId: input2.ruleId,
23764
+ name: input2.name,
23765
+ category: input2.category,
23766
+ severity: input2.severity,
23767
+ definition: input2.definition,
23768
+ version: input2.version
23769
+ };
23770
+ }
23771
+ function toInspectionFindingRow(input2) {
23772
+ return {
23773
+ id: input2.id,
23774
+ auditEventId: input2.auditEventId,
23775
+ inspectionDefinitionId: input2.inspectionDefinitionId,
23776
+ classifiedDataId: input2.classifiedDataId ?? null,
23777
+ spanStart: input2.span.start,
23778
+ spanEnd: input2.span.end,
23779
+ maskedMatch: input2.maskedMatch,
23780
+ actionTaken: input2.actionTaken,
23781
+ confidence: input2.confidence,
23782
+ findingKey: input2.findingKey ?? null,
23783
+ firstDetectedAt: input2.firstDetectedAt ? isoToEpochMillis(input2.firstDetectedAt) : null
23784
+ };
23785
+ }
23786
+ function toCaptureAttributes(event) {
23787
+ const metadata = event.metadata;
23788
+ return {
23789
+ source_tool: event.sourceTool,
23790
+ ...metadata?.repo !== void 0 ? { repo: metadata.repo } : {},
23791
+ ...metadata?.filePath !== void 0 ? { file_path: metadata.filePath } : {},
23792
+ ...metadata?.toolName !== void 0 ? { tool_name: metadata.toolName } : {},
23793
+ ...metadata?.gitignored !== void 0 ? { gitignored: metadata.gitignored } : {},
23794
+ ...metadata?.wholeFile !== void 0 ? { whole_file: metadata.wholeFile } : {},
23795
+ ...metadata?.correlationId !== void 0 ? { correlation_id: metadata.correlationId } : {},
23796
+ ...metadata?.traceId !== void 0 ? { trace_id: metadata.traceId } : {},
23797
+ ...metadata?.exceptionIds !== void 0 ? { exception_ids: metadata.exceptionIds } : {},
23798
+ ...metadata?.inspectionMs !== void 0 ? { inspection_ms: metadata.inspectionMs } : {},
23799
+ // `model`/`turnIndex` have no dedicated CaptureAttributes field (no writer
23800
+ // has ever populated either), but every legacy metadata key still rides
23801
+ // the bag rather than being silently dropped — CaptureAttributes'
23802
+ // `.catchall(z.unknown())` carries the long tail.
23803
+ ...metadata?.model !== void 0 ? { model: metadata.model } : {},
23804
+ ...metadata?.turnIndex !== void 0 ? { turn_index: metadata.turnIndex } : {}
23805
+ };
23806
+ }
23807
+ function captureDefinitionVersion(finding) {
23808
+ return `capture/${finding.category}/${finding.severity}`;
23809
+ }
23810
+ function toCaptureDefinitionInput(finding) {
23811
+ return {
23812
+ ruleId: finding.ruleId,
23813
+ version: captureDefinitionVersion(finding),
23814
+ name: finding.ruleId,
23815
+ category: finding.category,
23816
+ severity: finding.severity,
23817
+ definition: JSON.stringify({ ruleId: finding.ruleId })
23818
+ };
23819
+ }
23820
+
23821
+ // ../../packages/schema/src/zod/managed.ts
23822
+ var MANAGED_SETTINGS_FILENAME = "managed-settings.json";
23823
+ var MANAGED_SETTINGS_SPEC_VERSION = 1;
23824
+ var ManagedSettingKey = external_exports.enum([
23825
+ "runMode",
23826
+ "historicalAccess",
23827
+ "vaultConsent",
23828
+ "vaultKeyCustody",
23829
+ "vaultInlineReveal",
23830
+ "modelJudgeConsent",
23831
+ "dataSharesInPlace",
23832
+ "redactFallback"
23833
+ ]).meta({ id: "ManagedSettingKey" });
23834
+ var ManagedSettingsValues = external_exports.object({
23835
+ runMode: external_exports.enum(["standalone", "attached"]).optional(),
23836
+ controlPlane: external_exports.object({
23837
+ endpoint: external_exports.string().min(1),
23838
+ label: external_exports.string().min(1).optional()
23839
+ }).optional(),
23840
+ historicalAccess: external_exports.enum(["full", "session-only"]).optional(),
23841
+ vaultConsent: external_exports.boolean().optional(),
23842
+ vaultKeyCustody: external_exports.enum(["file", "keychain"]).optional(),
23843
+ vaultInlineReveal: external_exports.enum(["masked", "full", "off"]).optional(),
23844
+ modelJudgeConsent: external_exports.boolean().optional(),
23845
+ dataSharesInPlace: external_exports.boolean().optional(),
23846
+ redactFallback: RedactFallback.optional()
23847
+ }).meta({ id: "ManagedSettingsValues" });
23848
+ var ManagedSettings = external_exports.object({
23849
+ specVersion: external_exports.number().int().positive().default(MANAGED_SETTINGS_SPEC_VERSION),
23850
+ // Shown on every locked control, so the user can tell an administrative
23851
+ // decision from a bug. Absent renders as a generic "your organization".
23852
+ organization: external_exports.string().min(1).optional(),
23853
+ // What the administrator pinned.
23854
+ values: ManagedSettingsValues.default({}),
23855
+ // Which of those the user may not change. A key here with no matching value
23856
+ // freezes whatever the user last chose; a value with no lock is a DEFAULT
23857
+ // the user may still override. The two are separable on purpose.
23858
+ lockedFields: external_exports.array(ManagedSettingKey).default([])
23859
+ }).meta({ id: "ManagedSettings" });
23860
+
23717
23861
  // ../../packages/schema/src/zod/project-files.ts
23718
23862
  var ProjectFileInput = external_exports.object({
23719
23863
  path: external_exports.string().min(1),
@@ -23959,10 +24103,12 @@ var DismissRecommendedActionResponse = external_exports.object({ id: external_ex
23959
24103
  var RecommendedActionIdParam = external_exports.object({ id: external_exports.string() });
23960
24104
 
23961
24105
  // ../../packages/schema/src/zod/settings-action.ts
24106
+ var HistorySyncConsentChoice = external_exports.enum(["granted", "revoked", "unchanged"]).meta({ id: "HistorySyncConsentChoice" });
24107
+ var ModelJudgeConsentChoice = external_exports.enum(["granted", "revoked", "unchanged"]).meta({ id: "ModelJudgeConsentChoice" });
23962
24108
  var SaveSettingsInput = external_exports.object({
23963
24109
  historicalAccess: external_exports.string(),
23964
- modelJudgeConsent: external_exports.boolean(),
23965
- historySyncConsent: external_exports.boolean(),
24110
+ modelJudgeConsent: ModelJudgeConsentChoice,
24111
+ historySyncConsent: HistorySyncConsentChoice,
23966
24112
  vaultConsent: external_exports.string(),
23967
24113
  vaultInlineReveal: external_exports.string()
23968
24114
  });
@@ -24112,9 +24258,9 @@ function deriveReviewReasons(trust, transports) {
24112
24258
  if (transports.includes("http") || transports.includes("ws")) reasons.push("plaintext_transport");
24113
24259
  return reasons;
24114
24260
  }
24115
- function buildReviewInfo(trust, transports) {
24261
+ function buildReviewInfo(trust, transports, decided) {
24116
24262
  const reasons = deriveReviewReasons(trust, transports);
24117
- return { needsReview: reasons.length > 0, reasons };
24263
+ return { needsReview: reasons.length > 0 && !decided, reasons };
24118
24264
  }
24119
24265
  function distinctTransports(transports) {
24120
24266
  return Array.from(new Set(transports));
@@ -24312,8 +24458,8 @@ function readControlPlaneCredential(settingsDir2, connection) {
24312
24458
  }
24313
24459
 
24314
24460
  // ../../packages/persistence/src/database.ts
24315
- import { randomUUID as randomUUID10 } from "crypto";
24316
- import { join as join4, sep } from "path";
24461
+ import { randomUUID as randomUUID11 } from "crypto";
24462
+ import { dirname as dirname2, join as join7, sep } from "path";
24317
24463
  import { DatabaseSync } from "node:sqlite";
24318
24464
 
24319
24465
  // ../../packages/persistence/src/ids.ts
@@ -24568,6 +24714,10 @@ function allRows(stmt, params) {
24568
24714
  if (Array.isArray(params)) return stmt.all(...params);
24569
24715
  return stmt.all(params);
24570
24716
  }
24717
+ function* iterateRows(stmt, params) {
24718
+ const rows = params === void 0 ? stmt.iterate() : Array.isArray(params) ? stmt.iterate(...params) : stmt.iterate(params);
24719
+ for (const row of rows) yield row;
24720
+ }
24571
24721
  function getRow(stmt, params) {
24572
24722
  if (params === void 0) return stmt.get();
24573
24723
  if (Array.isArray(params)) return stmt.get(...params);
@@ -25036,10 +25186,17 @@ function ensureSyncedAtColumn(db, table) {
25036
25186
  if (!columns.includes("sync_claimed_at")) {
25037
25187
  db.exec(`ALTER TABLE ${table} ADD COLUMN sync_claimed_at integer`);
25038
25188
  }
25189
+ if (!columns.includes("outbox_owed")) {
25190
+ db.exec(`ALTER TABLE ${table} ADD COLUMN outbox_owed integer`);
25191
+ }
25039
25192
  db.exec(
25040
25193
  `CREATE INDEX IF NOT EXISTS idx_audit_events_sync
25041
25194
  ON audit_events (event_type, synced_at, sync_claimed_at, started_at)`
25042
25195
  );
25196
+ db.exec(
25197
+ `CREATE INDEX IF NOT EXISTS idx_audit_outbox_owed
25198
+ ON audit_events (event_type, synced_at, sync_claimed_at, started_at) WHERE outbox_owed = 1`
25199
+ );
25043
25200
  db.exec(
25044
25201
  `CREATE INDEX IF NOT EXISTS idx_audit_claimed
25045
25202
  ON audit_events (sync_claimed_at) WHERE sync_claimed_at IS NOT NULL`
@@ -25144,7 +25301,6 @@ function decodeKeysetCursor(cursor) {
25144
25301
  // ../../packages/persistence/src/repositories/activity.ts
25145
25302
  var DAY_MS = 864e5;
25146
25303
  var LIVE_ACTIVITY_WINDOW_MS = 30 * 6e4;
25147
- var LAST_ACTIVITY_EXPR = `max(started_at, coalesce(ended_at, started_at))`;
25148
25304
  function defaultTimeZone() {
25149
25305
  try {
25150
25306
  return Intl.DateTimeFormat().resolvedOptions().timeZone;
@@ -25199,6 +25355,7 @@ var DB_EVENT_TYPE_TO_KIND = {
25199
25355
  error: "error",
25200
25356
  active: "active"
25201
25357
  };
25358
+ var TIMELINE_EVENT_TYPES = Object.keys(DB_EVENT_TYPE_TO_KIND).map((kind) => `'${kind}'`).join(", ");
25202
25359
  function safeParseStringArray(raw) {
25203
25360
  if (!raw) return [];
25204
25361
  const parsed2 = safeJson(raw, null);
@@ -25272,6 +25429,37 @@ var TIMELINE_COLUMNS = `
25272
25429
  json_extract(attributes, '$.targetId') AS target_id,
25273
25430
  json_extract(attributes, '$.internal') AS internal,
25274
25431
  json_extract(attributes, '$.flagged') AS flagged`;
25432
+ var LLM_USAGE_SELECT = `
25433
+ SELECT root_session_id AS sessionId,
25434
+ provider,
25435
+ model,
25436
+ service_tier AS serviceTier,
25437
+ coalesce(sum(input_tokens), 0) AS inputTokens,
25438
+ coalesce(sum(output_tokens), 0) AS outputTokens,
25439
+ coalesce(sum(cache_creation_input_tokens), 0) AS cacheCreationTokens,
25440
+ coalesce(sum(cache_read_input_tokens), 0) AS cacheReadTokens,
25441
+ coalesce(sum(ephemeral_1h_input_tokens), 0) AS ephemeral1hTokens,
25442
+ coalesce(sum(ephemeral_5m_input_tokens), 0) AS ephemeral5mTokens,
25443
+ coalesce(sum(web_search_requests), 0) AS webSearchRequests`;
25444
+ var LLM_USAGE_SCOPE = `event_type = 'llm_call' AND attributes IS NOT NULL AND root_session_id IS NOT NULL`;
25445
+ var LLM_USAGE_GROUP = `GROUP BY root_session_id, provider, model, service_tier`;
25446
+ function usageLeaves(rows) {
25447
+ return rows.map((row) => {
25448
+ const attributes = {
25449
+ input_tokens: row.inputTokens,
25450
+ output_tokens: row.outputTokens,
25451
+ cache_creation_input_tokens: row.cacheCreationTokens,
25452
+ cache_read_input_tokens: row.cacheReadTokens,
25453
+ ephemeral_1h_input_tokens: row.ephemeral1hTokens,
25454
+ ephemeral_5m_input_tokens: row.ephemeral5mTokens,
25455
+ web_search_requests: row.webSearchRequests
25456
+ };
25457
+ if (row.provider !== null) attributes.provider = row.provider;
25458
+ if (row.model !== null) attributes.model = row.model;
25459
+ if (row.serviceTier !== null) attributes.service_tier = row.serviceTier;
25460
+ return { sessionId: row.sessionId, attributes };
25461
+ });
25462
+ }
25275
25463
  var SESSION_ROOT = `event_type = 'session'`;
25276
25464
  var HAS_ACTIVITY = `EXISTS (
25277
25465
  SELECT 1 FROM audit_events c
@@ -25297,16 +25485,17 @@ var SqliteActivityRepository = class {
25297
25485
  const liveThreshold = this.now() - LIVE_ACTIVITY_WINDOW_MS;
25298
25486
  const liveNow = countScalar(
25299
25487
  this.db,
25300
- `SELECT count(*) AS n FROM audit_events s
25488
+ `SELECT count(*) AS n FROM audit_events s INDEXED BY sqlite_autoindex_audit_events_1
25301
25489
  WHERE s.event_type = 'session' AND s.ended_at IS NULL
25302
- AND max(
25303
- s.started_at,
25304
- coalesce(
25305
- (SELECT max(${LAST_ACTIVITY_EXPR}) FROM audit_events e WHERE e.root_session_id = s.id),
25306
- s.started_at
25307
- )
25308
- ) >= ?`,
25309
- [liveThreshold]
25490
+ AND s.id IN (
25491
+ SELECT id FROM audit_events WHERE event_type = 'session' AND started_at >= ?
25492
+ UNION
25493
+ SELECT root_session_id FROM audit_events INDEXED BY idx_audit_started_at
25494
+ WHERE started_at >= ?
25495
+ UNION
25496
+ SELECT root_session_id FROM audit_events INDEXED BY idx_audit_ended_at
25497
+ WHERE ended_at >= ?)`,
25498
+ [liveThreshold, liveThreshold, liveThreshold]
25310
25499
  );
25311
25500
  const toolCallsToday = countScalar(
25312
25501
  this.db,
@@ -25436,7 +25625,7 @@ var SqliteActivityRepository = class {
25436
25625
  this.db.prepare(
25437
25626
  `SELECT ${TIMELINE_COLUMNS}
25438
25627
  FROM audit_events
25439
- WHERE id = ? OR root_session_id = ?
25628
+ WHERE (id = ? OR root_session_id = ?) AND event_type IN (${TIMELINE_EVENT_TYPES})
25440
25629
  ORDER BY started_at ASC, id ASC`
25441
25630
  ),
25442
25631
  [sessionId, sessionId]
@@ -25449,14 +25638,14 @@ var SqliteActivityRepository = class {
25449
25638
  coalesce(sum(output_tokens), 0) AS output,
25450
25639
  coalesce(sum(cache_creation_input_tokens), 0) AS cache_creation,
25451
25640
  coalesce(sum(cache_read_input_tokens), 0) AS cache_read
25452
- FROM audit_events
25641
+ FROM audit_events INDEXED BY idx_audit_session_type
25453
25642
  WHERE root_session_id = ? AND event_type = 'llm_call'`
25454
25643
  ),
25455
25644
  [sessionId]
25456
25645
  ) ?? { input: 0, output: 0, cache_creation: 0, cache_read: 0 };
25457
25646
  const primaryModel = getRow(
25458
25647
  this.db.prepare(
25459
- `SELECT model, provider FROM audit_events
25648
+ `SELECT model, provider FROM audit_events INDEXED BY idx_audit_session_type
25460
25649
  WHERE root_session_id = ? AND event_type = 'llm_call'
25461
25650
  ORDER BY started_at ASC, id ASC
25462
25651
  LIMIT 1`
@@ -25467,7 +25656,7 @@ var SqliteActivityRepository = class {
25467
25656
  this.db.prepare(
25468
25657
  `SELECT coalesce(json_extract(attributes, '$.tool_name'), json_extract(attributes, '$.tool')) AS tool,
25469
25658
  count(*) AS n
25470
- FROM audit_events
25659
+ FROM audit_events INDEXED BY idx_audit_session
25471
25660
  WHERE root_session_id = ? AND event_type = 'tool_call'
25472
25661
  GROUP BY coalesce(json_extract(attributes, '$.tool_name'), json_extract(attributes, '$.tool'))`
25473
25662
  ),
@@ -25475,7 +25664,7 @@ var SqliteActivityRepository = class {
25475
25664
  );
25476
25665
  const modelRows = allRows(
25477
25666
  this.db.prepare(
25478
- `SELECT DISTINCT model FROM audit_events
25667
+ `SELECT DISTINCT model FROM audit_events INDEXED BY idx_audit_session_type
25479
25668
  WHERE root_session_id = ? AND event_type = 'llm_call' AND model IS NOT NULL AND model <> ''
25480
25669
  ORDER BY model`
25481
25670
  ),
@@ -25484,7 +25673,7 @@ var SqliteActivityRepository = class {
25484
25673
  const derivedModels = modelRows.map((r) => r.model);
25485
25674
  const commits = countScalar(
25486
25675
  this.db,
25487
- `SELECT count(*) AS n FROM audit_events
25676
+ `SELECT count(*) AS n FROM audit_events INDEXED BY idx_audit_session
25488
25677
  WHERE root_session_id = ? AND event_type = 'commit'`,
25489
25678
  [sessionId]
25490
25679
  );
@@ -25520,25 +25709,57 @@ var SqliteActivityRepository = class {
25520
25709
  return Promise.resolve(session);
25521
25710
  }
25522
25711
  /**
25523
- * Cross-session token report — every `llm_call` leaf (optionally windowed to
25524
- * `started_at >= fromMs`) grouped into per-session `SessionTokenReport`s, with
25525
- * USD cost DERIVED at read time via the shared `defaultCostModel` (never
25526
- * stored). `fromMs` lets the Activity page scope the usage panel to its
25527
- * selected time range; omit it for all-time (the CLI/TUI overview). The
25528
- * caller collapses these onto per-model rows with `aggregateTokenUsage`.
25712
+ * Cross-session token report — every `llm_call` in the store (or in a
25713
+ * `started_at >= fromMs` window, the Activity page's range) grouped per
25714
+ * session, with USD cost DERIVED at read time via the shared
25715
+ * `defaultCostModel` (never stored). The caller collapses these onto
25716
+ * per-model rows with `aggregateTokenUsage`.
25717
+ *
25718
+ * Grouped in SQL over `idx_audit_llm_usage` — one entry per call carrying
25719
+ * the members the rollup sums — and priced once per group, which is exact
25720
+ * (see LlmUsageRow). Reading the bags and folding them in JS measured 31 ms
25721
+ * for a seven-day window at 50k calls, and naming the VIRTUAL columns
25722
+ * against the table 40 ms, since each is a json_extract recomputed per row;
25723
+ * the index stores the values once, at write, and answers the same window in
25724
+ * 8.5 ms. `INDEXED BY` is deliberate: with or without ANALYZE statistics the
25725
+ * planner prefers the general event-type index and fetches every row to
25726
+ * recompute the columns it could have read. The index is one every open
25727
+ * store carries, since opening runs the migrations, so the hard requirement
25728
+ * `INDEXED BY` introduces is already met; token-rollup-plans.test.ts pins
25729
+ * the plan. All-time is a scan of the whole index — still one narrow entry
25730
+ * per call, no bag parsed.
25529
25731
  */
25530
25732
  tokenReports(fromMs) {
25531
- const leaves = this.readLlmCallLeaves(fromMs === void 0 ? {} : { fromMs });
25532
- return Promise.resolve(buildTokenReports(leaves, defaultCostModel));
25733
+ const rows = allRows(
25734
+ this.db.prepare(
25735
+ `${LLM_USAGE_SELECT}
25736
+ FROM audit_events INDEXED BY idx_audit_llm_usage
25737
+ WHERE ${LLM_USAGE_SCOPE}${fromMs === void 0 ? "" : " AND started_at >= ?"}
25738
+ ${LLM_USAGE_GROUP}`
25739
+ ),
25740
+ fromMs === void 0 ? void 0 : [fromMs]
25741
+ );
25742
+ return Promise.resolve(buildTokenReports(usageLeaves(rows), defaultCostModel));
25533
25743
  }
25534
25744
  /**
25535
- * One session's token report — its `llm_call` leaves grouped per (provider,
25536
- * model) with derived cost, or `null` when the session made no `llm_call`s
25537
- * (an empty/tool-only session). Feeds the session-detail pane's per-model
25538
- * breakdown + estimated cost.
25745
+ * One session's token report — its `llm_call`s grouped per (provider,
25746
+ * model, tier) with derived cost, or `null` when the session made no
25747
+ * `llm_call`s (an empty/tool-only session). Feeds the session-detail pane's
25748
+ * per-model breakdown + estimated cost. The same rollup as `tokenReports`,
25749
+ * seeking one root through a root-led `llm_call` index; the bag-reading fold
25750
+ * it replaces walked every `llm_call` in the store to find one session's.
25539
25751
  */
25540
25752
  tokenReportForSession(sessionId) {
25541
- const reports = buildTokenReports(this.readLlmCallLeaves({ sessionId }), defaultCostModel);
25753
+ const rows = allRows(
25754
+ this.db.prepare(
25755
+ `${LLM_USAGE_SELECT}
25756
+ FROM audit_events
25757
+ WHERE ${LLM_USAGE_SCOPE} AND root_session_id = ?
25758
+ ${LLM_USAGE_GROUP}`
25759
+ ),
25760
+ [sessionId]
25761
+ );
25762
+ const reports = buildTokenReports(usageLeaves(rows), defaultCostModel);
25542
25763
  return Promise.resolve(reports[0] ?? null);
25543
25764
  }
25544
25765
  /**
@@ -25562,42 +25783,6 @@ var SqliteActivityRepository = class {
25562
25783
  for (const row of rows) seen.add(toHarness(row.harness));
25563
25784
  return Promise.resolve([...seen]);
25564
25785
  }
25565
- /**
25566
- * The raw `llm_call` leaves (session id + parsed attribute bag) for the token
25567
- * rollups, optionally narrowed to one session and/or a `started_at >= fromMs`
25568
- * window. A leaf whose attributes blob is NULL or unparseable is skipped
25569
- * (best-effort read — a corrupt bag never breaks the report). `root_session_id`
25570
- * is the leaf's session (the reconciler sets parent_id = root_session_id).
25571
- */
25572
- readLlmCallLeaves(opts = {}) {
25573
- const conditions = ["event_type = 'llm_call'", "attributes IS NOT NULL"];
25574
- const params = [];
25575
- if (opts.sessionId !== void 0) {
25576
- conditions.push("root_session_id = ?");
25577
- params.push(opts.sessionId);
25578
- }
25579
- if (opts.fromMs !== void 0) {
25580
- conditions.push("started_at >= ?");
25581
- params.push(opts.fromMs);
25582
- }
25583
- const rows = allRows(
25584
- this.db.prepare(
25585
- `SELECT root_session_id AS sessionId, attributes
25586
- FROM audit_events
25587
- WHERE ${conditions.join(" AND ")}`
25588
- ),
25589
- params
25590
- );
25591
- return mapRowsTolerant(
25592
- rows.filter(
25593
- (row) => row.sessionId !== null
25594
- ),
25595
- (row) => ({
25596
- sessionId: row.sessionId,
25597
- attributes: JSON.parse(row.attributes)
25598
- })
25599
- );
25600
- }
25601
25786
  /**
25602
25787
  * Per-session turns/findings/shares + last-activity for a page of session ids,
25603
25788
  * in grouped queries (not one per row). An id with no matching rows still
@@ -25612,20 +25797,23 @@ var SqliteActivityRepository = class {
25612
25797
  const inClause = placeholders(sessionIds.length);
25613
25798
  const lastActivityRows = allRows(
25614
25799
  this.db.prepare(
25615
- `SELECT root_session_id AS id, max(${LAST_ACTIVITY_EXPR}) AS m FROM audit_events
25616
- WHERE root_session_id IN (${inClause})
25617
- GROUP BY root_session_id`
25800
+ `SELECT ids.value AS id,
25801
+ (SELECT max(started_at) FROM audit_events e WHERE e.root_session_id = ids.value) AS ms,
25802
+ (SELECT max(ended_at) FROM audit_events e
25803
+ WHERE e.root_session_id = ids.value AND e.ended_at IS NOT NULL) AS me
25804
+ FROM json_each(?) AS ids`
25618
25805
  ),
25619
- sessionIds
25806
+ [JSON.stringify(sessionIds)]
25620
25807
  );
25621
25808
  for (const row of lastActivityRows) {
25622
- if (row.id === null) continue;
25623
25809
  const entry = result.get(row.id);
25624
- if (entry && row.m !== null) entry.lastActivityMs = row.m;
25810
+ const last = Math.max(row.ms ?? 0, row.me ?? 0);
25811
+ if (entry && last > 0) entry.lastActivityMs = last;
25625
25812
  }
25626
25813
  const turnsRows = allRows(
25627
25814
  this.db.prepare(
25628
- `SELECT root_session_id AS id, count(*) AS n FROM audit_events
25815
+ `SELECT root_session_id AS id, count(*) AS n
25816
+ FROM audit_events INDEXED BY idx_audit_session_prompt
25629
25817
  WHERE root_session_id IN (${inClause}) AND event_type = 'prompt'
25630
25818
  GROUP BY root_session_id`
25631
25819
  ),
@@ -25640,7 +25828,7 @@ var SqliteActivityRepository = class {
25640
25828
  this.db.prepare(
25641
25829
  `SELECT root_session_id AS id,
25642
25830
  count(DISTINCT json_extract(attributes, '$.run_key')) AS n
25643
- FROM audit_events
25831
+ FROM audit_events INDEXED BY idx_audit_session_run_key
25644
25832
  WHERE root_session_id IN (${inClause}) AND event_type = 'llm_call'
25645
25833
  AND json_extract(attributes, '$.run_key') IS NOT NULL
25646
25834
  GROUP BY root_session_id`
@@ -25670,7 +25858,7 @@ var SqliteActivityRepository = class {
25670
25858
  this.db.prepare(
25671
25859
  `SELECT root_session_id AS id,
25672
25860
  count(DISTINCT json_extract(attributes, '$.destination')) AS n
25673
- FROM audit_events
25861
+ FROM audit_events INDEXED BY idx_audit_session_share
25674
25862
  WHERE root_session_id IN (${inClause}) AND event_type = 'share'
25675
25863
  GROUP BY root_session_id`
25676
25864
  ),
@@ -26699,7 +26887,6 @@ var LATEST_RESOLUTION_BY_KEY_SQL = `(
26699
26887
 
26700
26888
  // ../../packages/persistence/src/repositories/findings.ts
26701
26889
  var PREVIEW_INSTANCES_PER_GROUP = 200;
26702
- var SCAN_BATCH_ROWS = 1e3;
26703
26890
  var DEFAULT_LOCATIONS_LIMIT = 100;
26704
26891
  var LOCATION_RULE_IDS_CAP = 20;
26705
26892
  function compareLocationOrder(a, b) {
@@ -26728,6 +26915,25 @@ function deriveInstanceStatus(row) {
26728
26915
  latestResolutionStatus: row.latest_status
26729
26916
  });
26730
26917
  }
26918
+ function toFlatFindingRow(r) {
26919
+ return {
26920
+ id: r.id,
26921
+ ruleId: r.rule_id,
26922
+ category: r.category,
26923
+ severity: r.severity,
26924
+ maskedMatch: r.masked_match,
26925
+ actionTaken: r.action_taken,
26926
+ confidence: r.confidence,
26927
+ occurredAt: epochMillisToIso(r.occurred_at),
26928
+ sourceTool: r.source_tool,
26929
+ repo: r.repo ?? "",
26930
+ file: r.file ?? "",
26931
+ ...r.tool_name === null ? {} : { toolName: r.tool_name },
26932
+ eventId: r.event_id,
26933
+ ...r.session_id === null ? {} : { sessionId: r.session_id },
26934
+ status: deriveInstanceStatus(r)
26935
+ };
26936
+ }
26731
26937
  function encodeGroupCursor(group) {
26732
26938
  const payload = {
26733
26939
  sev: group.severity,
@@ -26803,7 +27009,7 @@ var SqliteFindingsRepository = class {
26803
27009
  this.db.prepare(
26804
27010
  `SELECT f.id, f.audit_event_id AS event_id, d.rule_id, d.category, d.severity,
26805
27011
  f.masked_match, f.action_taken, f.confidence, e.started_at AS occurred_at,
26806
- json_extract(e.attributes, '$.source_tool') AS source_tool,
27012
+ e.source_tool AS source_tool,
26807
27013
  e.event_type AS kind
26808
27014
  FROM audit_events e
26809
27015
  CROSS JOIN inspection_findings f ON f.audit_event_id = e.id
@@ -26911,56 +27117,11 @@ var SqliteFindingsRepository = class {
26911
27117
  predicate,
26912
27118
  params: sessionParams
26913
27119
  });
26914
- const rows = allRows(
26915
- this.db.prepare(
26916
- `SELECT id, rule_id, category, severity, masked_match, action_taken, confidence,
26917
- occurred_at, source_tool, repo, file, tool_name, event_id, session_id,
26918
- kind, finding_key, latest_status
26919
- FROM (
26920
- SELECT f.id AS id, d.rule_id AS rule_id, d.category AS category,
26921
- d.severity AS severity, f.masked_match AS masked_match,
26922
- f.action_taken AS action_taken, f.confidence AS confidence,
26923
- e.started_at AS occurred_at,
26924
- json_extract(e.attributes, '$.source_tool') AS source_tool,
26925
- json_extract(e.attributes, '$.repo') AS repo,
26926
- json_extract(e.attributes, '$.file_path') AS file,
26927
- json_extract(e.attributes, '$.tool_name') AS tool_name,
26928
- f.audit_event_id AS event_id, e.root_session_id AS session_id,
26929
- e.event_type AS kind, f.finding_key AS finding_key,
26930
- latest.status AS latest_status,
26931
- ROW_NUMBER() OVER (
26932
- PARTITION BY d.rule_id
26933
- ORDER BY e.started_at DESC, f.id DESC
26934
- ) AS rn
26935
- FROM inspection_findings f
26936
- JOIN audit_events e ON e.id = f.audit_event_id
26937
- JOIN inspection_definitions d ON d.id = f.inspection_definition_id
26938
- LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
26939
- ON latest.finding_key = f.finding_key
26940
- ${predicate}
26941
- )
26942
- WHERE rn <= :cap
26943
- ORDER BY occurred_at DESC, id DESC`
26944
- ),
26945
- { cap: PREVIEW_INSTANCES_PER_GROUP, ...sessionParams }
26946
- );
26947
- const groupable = rows.map((r) => ({
26948
- id: r.id,
26949
- ruleId: r.rule_id,
26950
- category: r.category,
26951
- severity: r.severity,
26952
- maskedMatch: r.masked_match,
26953
- actionTaken: r.action_taken,
26954
- confidence: r.confidence,
26955
- occurredAt: epochMillisToIso(r.occurred_at),
26956
- sourceTool: r.source_tool,
26957
- repo: r.repo ?? "",
26958
- file: r.file ?? "",
26959
- ...r.tool_name === null ? {} : { toolName: r.tool_name },
26960
- eventId: r.event_id,
26961
- ...r.session_id === null ? {} : { sessionId: r.session_id },
26962
- status: deriveInstanceStatus(r)
26963
- }));
27120
+ const rows = this.previewRows(aggregates, {
27121
+ sessionId: query.sessionId,
27122
+ from: query.from
27123
+ });
27124
+ const groupable = rows.map(toFlatFindingRow);
26964
27125
  const allGroups = buildFindingGroups(groupable, { aggregates });
26965
27126
  const filterOpts = {
26966
27127
  severity: query.severity,
@@ -27046,8 +27207,10 @@ var SqliteFindingsRepository = class {
27046
27207
  *
27047
27208
  * The scan runs from the top of the scope on every request, not from the
27048
27209
  * cursor: `totals` and `facets` describe the whole filtered scope and must not
27049
- * move as the caller pages. Rows are pulled in batches so memory stays flat
27050
- * while the counting runs, and only the page itself is retained.
27210
+ * move as the caller pages. Rows come off ONE statement, iterated rather
27211
+ * than materialized (`scanFindingRows`), so memory stays flat while the
27212
+ * counting runs — a generator streaming the index order, not a sequence of
27213
+ * fetched batches; only the page itself is retained.
27051
27214
  */
27052
27215
  listFindingInstances(query) {
27053
27216
  const opts = {
@@ -27063,6 +27226,10 @@ var SqliteFindingsRepository = class {
27063
27226
  };
27064
27227
  const limit = query.limit ?? DEFAULT_FLAT_FINDINGS_LIMIT;
27065
27228
  const cursor = query.cursor === void 0 ? null : decodeKeysetCursor(query.cursor);
27229
+ const isPastCursor = cursor === null ? () => true : (row) => {
27230
+ const rowMs = isoToEpochMillis(row.occurredAt);
27231
+ return rowMs <= cursor.startedAtMs && (rowMs < cursor.startedAtMs || row.id < cursor.id);
27232
+ };
27066
27233
  const accumulator = createInstanceFacetAccumulator(opts);
27067
27234
  const items = [];
27068
27235
  let total = 0;
@@ -27075,6 +27242,7 @@ var SqliteFindingsRepository = class {
27075
27242
  accumulator.add(row);
27076
27243
  if (!matchesInstanceFilters(row, opts)) continue;
27077
27244
  total += 1;
27245
+ if (!isPastCursor(row)) continue;
27078
27246
  if (items.length < limit) {
27079
27247
  items.push(toInstanceDetail(row));
27080
27248
  last = row;
@@ -27083,15 +27251,6 @@ var SqliteFindingsRepository = class {
27083
27251
  }
27084
27252
  }
27085
27253
  const nextCursor = hasMore && last ? encodeKeysetCursor({ startedAtMs: isoToEpochMillis(last.occurredAt), id: last.id }) : null;
27086
- if (cursor !== null) {
27087
- const resumed = this.pageAfter(cursor, opts, limit, query);
27088
- return Promise.resolve({
27089
- totals: { findings: total },
27090
- facets: accumulator.facets(),
27091
- items: resumed.items,
27092
- nextCursor: resumed.nextCursor
27093
- });
27094
- }
27095
27254
  return Promise.resolve({
27096
27255
  totals: { findings: total },
27097
27256
  facets: accumulator.facets(),
@@ -27099,35 +27258,6 @@ var SqliteFindingsRepository = class {
27099
27258
  nextCursor
27100
27259
  });
27101
27260
  }
27102
- /**
27103
- * The page of matching rows strictly after `cursor`. Separate from the
27104
- * counting pass because that one starts at the top of the scope by design;
27105
- * this one narrows the scan with the same keyset predicate the activity list
27106
- * uses, so a later page costs less than the first rather than more.
27107
- */
27108
- pageAfter(cursor, opts, limit, query) {
27109
- const items = [];
27110
- let last;
27111
- let hasMore = false;
27112
- for (const row of this.scanFindingRows({
27113
- sessionId: query.sessionId,
27114
- from: query.from,
27115
- after: cursor
27116
- })) {
27117
- if (!matchesInstanceFilters(row, opts)) continue;
27118
- if (items.length < limit) {
27119
- items.push(toInstanceDetail(row));
27120
- last = row;
27121
- } else {
27122
- hasMore = true;
27123
- break;
27124
- }
27125
- }
27126
- return {
27127
- items,
27128
- nextCursor: hasMore && last ? encodeKeysetCursor({ startedAtMs: isoToEpochMillis(last.occurredAt), id: last.id }) : null
27129
- };
27130
- }
27131
27261
  /**
27132
27262
  * The same findings folded by location: repository, then file within it.
27133
27263
  *
@@ -27210,25 +27340,111 @@ var SqliteFindingsRepository = class {
27210
27340
  });
27211
27341
  }
27212
27342
  /**
27213
- * Every finding in scope as a FlatFindingRow, newest first, pulled in batches.
27343
+ * Each group's newest instances, for the table's expanded rows.
27344
+ *
27345
+ * ONE index-ordered scan with early termination, and the shape is the point.
27346
+ * The natural spelling — `ROW_NUMBER() OVER (PARTITION BY rule_id ORDER BY
27347
+ * started_at DESC)` then `WHERE rn <= cap` — sorts EVERY finding in scope
27348
+ * through a temp B-tree to keep a bounded preview of each group, and then
27349
+ * sorts the survivors again for the page order. Both sorts grow with the
27350
+ * store while the answer does not.
27351
+ *
27352
+ * Instead the scan walks `audit_events` newest-first off `idx_audit_started_at`
27353
+ * (or the session or window index the scope names — see `findingScanSql`),
27354
+ * which is already the order the page wants, and keeps rows per rule until
27355
+ * each rule has as many as it can show. The aggregate the caller already holds
27356
+ * says how many that is: `min(instanceCount, PREVIEW_INSTANCES_PER_GROUP)`
27357
+ * per rule, summed, is the number of rows this scan has to find, and it stops
27358
+ * on the last one. That sum is bounded by `rules * PREVIEW_INSTANCES_PER_GROUP`
27359
+ * (8,000 at this repo's 40-rule bench corpus), not by a fixed row count — a
27360
+ * store with many firing rules widens it. The bound that DOES hold
27361
+ * unconditionally is the sorted form's floor: this scan visits at most as
27362
+ * many rows as `ROW_NUMBER() OVER (PARTITION BY rule_id …)` would have
27363
+ * sorted, and stops the moment every rule has its cap, where the sorted form
27364
+ * sorts the whole scope regardless. The true worst case — the rarest rule's
27365
+ * wanted instances sitting at the tail of the scope — is one pass over
27366
+ * everything in scope with a block sort of the id tie-break only, never a
27367
+ * sort of the scope, which is still that floor.
27368
+ *
27369
+ * A row whose rule the aggregate did not see is skipped: the two statements
27370
+ * run without a shared snapshot, so a capture landing between them can add a
27371
+ * rule here that has no counts there, and the counts are what the group is
27372
+ * built from.
27373
+ */
27374
+ previewRows(aggregates, scope) {
27375
+ const wanted = /* @__PURE__ */ new Map();
27376
+ let remaining = 0;
27377
+ for (const [ruleId, agg] of aggregates) {
27378
+ const n = Math.min(agg.instanceCount, PREVIEW_INSTANCES_PER_GROUP);
27379
+ wanted.set(ruleId, n);
27380
+ remaining += n;
27381
+ }
27382
+ const rows = [];
27383
+ if (remaining === 0) return rows;
27384
+ const { sql, params } = this.findingScanSql(scope);
27385
+ const taken = /* @__PURE__ */ new Map();
27386
+ for (const r of iterateRows(this.db.prepare(sql), params)) {
27387
+ const want = wanted.get(r.rule_id);
27388
+ if (want === void 0) continue;
27389
+ const have = taken.get(r.rule_id) ?? 0;
27390
+ if (have >= want) continue;
27391
+ taken.set(r.rule_id, have + 1);
27392
+ rows.push(r);
27393
+ remaining -= 1;
27394
+ if (remaining === 0) break;
27395
+ }
27396
+ return rows;
27397
+ }
27398
+ /**
27399
+ * Every finding in scope as a FlatFindingRow, newest first, streamed.
27214
27400
  *
27215
27401
  * A generator so a caller streams the scope without it ever being an array:
27216
27402
  * the flat list counts and facets the whole filtered scope, which on a large
27217
- * store is far more rows than any page. Each batch advances the same keyset
27218
- * predicate the page read uses, so the scan is a sequence of bounded reads
27219
- * rather than one unbounded result set.
27220
- *
27221
- * The latest-resolution lookup is the CORRELATED form, not the derived table
27222
- * the grouped path joins: only `status` is needed, idx_finding_resolution_key
27223
- * makes it a point lookup per row, and the derived table would re-materialize
27224
- * a window over the whole resolution table once per batch.
27403
+ * store is far more rows than any page. The rows come off ONE statement,
27404
+ * iterated rather than materialized, in the index order `findingScanSql`
27405
+ * arranges — so the scan is a single pass with a block sort of the id
27406
+ * tie-break only, never a sort of the scope, where a sequence of
27407
+ * keyset-bounded batches re-sorted everything below the cursor on every
27408
+ * batch and cost the square of the scope.
27225
27409
  *
27226
- * `scope` carries ONLY what no facet counts. A filter dimension narrowed here
27227
- * would be missing from its own facet, which is computed by excluding that
27228
- * dimension — see listFindingInstances.
27410
+ * `sessionId` and `from` carry ONLY what no facet counts — a filter
27411
+ * dimension narrowed here would be missing from its own facet, which is
27412
+ * computed by excluding that dimension (see listFindingInstances). There is
27413
+ * no `after`/cursor parameter: a keyset page is collected inline from this
27414
+ * same pass (`listFindingInstances`' `isPastCursor`) rather than by a second,
27415
+ * narrower statement, since the counting pass already visits every row a
27416
+ * page-2+ request would otherwise re-seek for.
27229
27417
  */
27230
27418
  *scanFindingRows(scope) {
27231
- const conditions = [`e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})`];
27419
+ const { sql, params } = this.findingScanSql(scope);
27420
+ for (const r of iterateRows(this.db.prepare(sql), params)) {
27421
+ yield toFlatFindingRow(r);
27422
+ }
27423
+ }
27424
+ /**
27425
+ * The one statement both instance-level scans run: every finding in scope,
27426
+ * joined to its event and definition, newest first.
27427
+ *
27428
+ * THE PLAN IS THE POINT, and two things in the SQL exist only to pin it —
27429
+ * the same two `recentFindings` documents at length, for the same reason:
27430
+ *
27431
+ * - **`+e.event_type`** makes the capture-kind predicate non-indexable, so
27432
+ * the planner cannot pick `idx_audit_type_t` and then sort. That index
27433
+ * yields `started_at` order per event type, not across the four, so
27434
+ * satisfying the ORDER BY from it would need a merge SQLite does not do.
27435
+ * Freed of it, the planner walks `idx_audit_started_at` backwards — or
27436
+ * `idx_audit_session` for a session scope, which is also `started_at`
27437
+ * ordered within the session — and the order falls out of the index.
27438
+ * - **`CROSS JOIN`** pins `audit_events` as the driving table. With plain
27439
+ * JOINs the planner drives from the findings and sorts everything.
27440
+ *
27441
+ * The latest-resolution lookup is the CORRELATED form: only `status` is
27442
+ * needed, `idx_finding_resolution_key_created` answers it with one backward
27443
+ * index probe per keyed row, and a derived table over the whole resolution
27444
+ * table would be materialized before the first row streamed.
27445
+ */
27446
+ findingScanSql(scope) {
27447
+ const conditions = [`+e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})`];
27232
27448
  const params = [];
27233
27449
  if (scope.sessionId !== void 0 && scope.sessionId !== "") {
27234
27450
  conditions.push("e.root_session_id = ?");
@@ -27242,58 +27458,24 @@ var SqliteFindingsRepository = class {
27242
27458
  d.severity AS severity, f.masked_match AS masked_match,
27243
27459
  f.action_taken AS action_taken, f.confidence AS confidence,
27244
27460
  e.started_at AS occurred_at,
27245
- json_extract(e.attributes, '$.source_tool') AS source_tool,
27246
- json_extract(e.attributes, '$.repo') AS repo,
27247
- json_extract(e.attributes, '$.file_path') AS file,
27248
- json_extract(e.attributes, '$.tool_name') AS tool_name,
27461
+ e.source_tool AS source_tool,
27462
+ e.repo AS repo,
27463
+ e.file_path AS file,
27464
+ e.tool_name AS tool_name,
27249
27465
  f.audit_event_id AS event_id, e.root_session_id AS session_id,
27250
27466
  e.event_type AS kind, f.finding_key AS finding_key,
27251
27467
  ${latestResolutionStatusSql("f")} AS latest_status
27252
- FROM inspection_findings f
27253
- JOIN audit_events e ON e.id = f.audit_event_id
27254
- JOIN inspection_definitions d ON d.id = f.inspection_definition_id
27468
+ FROM audit_events e
27469
+ CROSS JOIN inspection_findings f ON f.audit_event_id = e.id
27470
+ CROSS JOIN inspection_definitions d ON d.id = f.inspection_definition_id
27255
27471
  WHERE ${conditions.join(" AND ")}
27256
- AND (e.started_at < ? OR (e.started_at = ? AND f.id < ?))
27257
- ORDER BY e.started_at DESC, f.id DESC
27258
- LIMIT ?`;
27259
- let after = scope.after ?? { startedAtMs: Number.MAX_SAFE_INTEGER, id: "\uFFFF" };
27260
- for (; ; ) {
27261
- const rows = allRows(this.db.prepare(sql), [
27262
- ...params,
27263
- after.startedAtMs,
27264
- after.startedAtMs,
27265
- after.id,
27266
- SCAN_BATCH_ROWS
27267
- ]);
27268
- for (const r of rows) {
27269
- yield {
27270
- id: r.id,
27271
- ruleId: r.rule_id,
27272
- category: r.category,
27273
- severity: r.severity,
27274
- maskedMatch: r.masked_match,
27275
- actionTaken: r.action_taken,
27276
- confidence: r.confidence,
27277
- occurredAt: epochMillisToIso(r.occurred_at),
27278
- sourceTool: r.source_tool,
27279
- repo: r.repo ?? "",
27280
- file: r.file ?? "",
27281
- ...r.tool_name === null ? {} : { toolName: r.tool_name },
27282
- eventId: r.event_id,
27283
- ...r.session_id === null ? {} : { sessionId: r.session_id },
27284
- status: deriveInstanceStatus(r)
27285
- };
27286
- }
27287
- if (rows.length < SCAN_BATCH_ROWS) return;
27288
- const lastRow = rows[rows.length - 1];
27289
- if (lastRow === void 0) return;
27290
- after = { startedAtMs: lastRow.occurred_at, id: lastRow.id };
27291
- }
27472
+ ORDER BY e.started_at DESC, f.id DESC`;
27473
+ return { sql, params };
27292
27474
  }
27293
27475
  groupAggregates(withSearchText, scope) {
27294
- const innerSearchColumns = withSearchText ? `, group_concat(DISTINCT json_extract(e.attributes, '$.repo')) AS repos,
27295
- group_concat(DISTINCT json_extract(e.attributes, '$.file_path')) AS files,
27296
- group_concat(DISTINCT 'via ' || json_extract(e.attributes, '$.tool_name')) AS tool_names` : `, NULL AS repos, NULL AS files, NULL AS tool_names`;
27476
+ const innerSearchColumns = withSearchText ? `, group_concat(DISTINCT e.repo) AS repos,
27477
+ group_concat(DISTINCT e.file_path) AS files,
27478
+ group_concat(DISTINCT 'via ' || e.tool_name) AS tool_names` : `, NULL AS repos, NULL AS files, NULL AS tool_names`;
27297
27479
  const rows = this.db.prepare(
27298
27480
  `SELECT rule_id,
27299
27481
  sum(tuple_count) AS instance_count,
@@ -27311,7 +27493,7 @@ var SqliteFindingsRepository = class {
27311
27493
  coalesce(latest.status, '') AS status_tuple,
27312
27494
  count(*) AS tuple_count,
27313
27495
  max(e.started_at) AS latest_at,
27314
- group_concat(DISTINCT json_extract(e.attributes, '$.source_tool')) AS source_tools,
27496
+ group_concat(DISTINCT e.source_tool) AS source_tools,
27315
27497
  group_concat(DISTINCT f.action_taken) AS actions_taken
27316
27498
  ${innerSearchColumns}
27317
27499
  FROM inspection_findings f
@@ -27442,6 +27624,8 @@ function isoDay(ms) {
27442
27624
  // ../../packages/persistence/src/repositories/history-sync.ts
27443
27625
  var STRUCTURAL_EVENT_TYPES = ["session", "llm_call", "tool_call"];
27444
27626
  var TYPE_LIST = STRUCTURAL_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
27627
+ var OUTBOX_CAPTURE_EVENT_TYPES = ["prompt", "response", "tool_use"];
27628
+ var CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
27445
27629
  var SKIPPED = -1;
27446
27630
  var ROW_COLUMNS = `id,
27447
27631
  parent_id AS parentId,
@@ -27481,6 +27665,20 @@ var SqliteHistorySyncRepository = class {
27481
27665
  ORDER BY (event_type = 'session') DESC, started_at
27482
27666
  LIMIT :limit`
27483
27667
  );
27668
+ this.captureRowsStmt = db.prepare(
27669
+ `SELECT ${ROW_COLUMNS}
27670
+ FROM audit_events
27671
+ WHERE synced_at IS NULL
27672
+ AND sync_claimed_at IS NULL
27673
+ AND outbox_owed = 1
27674
+ AND event_type IN (${CAPTURE_TYPE_LIST})
27675
+ AND started_at < :before
27676
+ ORDER BY started_at
27677
+ LIMIT :limit`
27678
+ );
27679
+ this.markOwedStmt = db.prepare(
27680
+ `UPDATE audit_events SET outbox_owed = 1 WHERE id = :id AND synced_at IS NULL`
27681
+ );
27484
27682
  this.stampStmt = db.prepare(
27485
27683
  `UPDATE audit_events SET synced_at = :at, sync_claimed_at = NULL WHERE id = :id`
27486
27684
  );
@@ -27512,6 +27710,12 @@ var SqliteHistorySyncRepository = class {
27512
27710
  FROM audit_events
27513
27711
  WHERE event_type IN (${TYPE_LIST})`
27514
27712
  );
27713
+ this.captureSkipCountStmt = db.prepare(
27714
+ `SELECT COUNT(*) AS skipped
27715
+ FROM audit_events
27716
+ WHERE synced_at = ${String(SKIPPED)}
27717
+ AND event_type IN (${CAPTURE_TYPE_LIST})`
27718
+ );
27515
27719
  this.fingerprintStmt = db.prepare(
27516
27720
  `SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
27517
27721
  FROM history_sync WHERE id = 1`
@@ -27521,6 +27725,10 @@ var SqliteHistorySyncRepository = class {
27521
27725
  SET endpoint_fingerprint = :fingerprint, backlog_before = :backlogBefore
27522
27726
  WHERE id = 1`
27523
27727
  );
27728
+ this.disownCapturesStmt = db.prepare(
27729
+ `UPDATE audit_events SET outbox_owed = NULL
27730
+ WHERE outbox_owed IS NOT NULL AND event_type IN (${CAPTURE_TYPE_LIST})`
27731
+ );
27524
27732
  this.rearmStmt = db.prepare(
27525
27733
  `UPDATE audit_events SET synced_at = NULL
27526
27734
  WHERE synced_at > 0 AND event_type IN (${TYPE_LIST})`
@@ -27593,6 +27801,10 @@ var SqliteHistorySyncRepository = class {
27593
27801
  closeWindowStmt;
27594
27802
  releaseBoundaryStmt;
27595
27803
  freezeBoundaryStmt;
27804
+ captureRowsStmt;
27805
+ markOwedStmt;
27806
+ captureSkipCountStmt;
27807
+ disownCapturesStmt;
27596
27808
  partitionStmt;
27597
27809
  claimRowStmt;
27598
27810
  releaseRowStmt;
@@ -27626,6 +27838,34 @@ var SqliteHistorySyncRepository = class {
27626
27838
  pendingRows(sessionId, limit, before) {
27627
27839
  return allRows(this.rowsStmt, { sessionId, limit, before });
27628
27840
  }
27841
+ /**
27842
+ * Captures this machine still owes the deployment, oldest first.
27843
+ *
27844
+ * Selected by the `outbox_owed` marker the attached forward path writes, not
27845
+ * by a time window — see captureRowsStmt for why a window could not express
27846
+ * this. `before` is the grace window that leaves a just-recorded capture to
27847
+ * the live path.
27848
+ */
27849
+ pendingCaptureRows(limit, before) {
27850
+ return allRows(this.captureRowsStmt, { limit, before });
27851
+ }
27852
+ /**
27853
+ * Record that a capture is OWED to the deployment.
27854
+ *
27855
+ * Written by the attached forward path when a live send did not confirm
27856
+ * delivery, and read by the drain as the whole of its eligibility test. It is
27857
+ * a fact rather than an inference: the machine was attached, the send did not
27858
+ * land, so the row is owed — which no time window can state, because the same
27859
+ * window that holds the rows a past attachment left owed also holds every
27860
+ * capture recorded while the machine was DETACHED, and those were never
27861
+ * offered to anyone.
27862
+ *
27863
+ * Idempotent, and never un-set: `markSynced` settling the row is what takes it
27864
+ * out of the drain's read.
27865
+ */
27866
+ markCaptureOwed(id) {
27867
+ this.markOwedStmt.run({ id });
27868
+ }
27629
27869
  /** Record delivery. Called only AFTER the far side has accepted the rows. */
27630
27870
  markSynced(ids, atMs) {
27631
27871
  this.stampAll(ids, atMs);
@@ -27709,10 +27949,12 @@ var SqliteHistorySyncRepository = class {
27709
27949
  this.countsStmt,
27710
27950
  { before }
27711
27951
  );
27952
+ const captures = getRow(this.captureSkipCountStmt);
27712
27953
  return {
27713
27954
  pending: row?.pending ?? 0,
27714
27955
  sent: row?.sent ?? 0,
27715
- skipped: row?.skipped ?? 0
27956
+ skipped: row?.skipped ?? 0,
27957
+ capturesSkipped: captures?.skipped ?? 0
27716
27958
  };
27717
27959
  }
27718
27960
  /**
@@ -27753,7 +27995,11 @@ var SqliteHistorySyncRepository = class {
27753
27995
  withTransaction(
27754
27996
  this.db,
27755
27997
  () => {
27998
+ const previous = getRow(this.fingerprintStmt)?.fingerprint;
27756
27999
  this.rearmStmt.run();
28000
+ if (previous !== null && previous !== void 0 && previous !== fingerprint) {
28001
+ this.disownCapturesStmt.run();
28002
+ }
27757
28003
  this.setFingerprintStmt.run({ fingerprint, backlogBefore });
27758
28004
  },
27759
28005
  "IMMEDIATE"
@@ -27950,7 +28196,256 @@ var SqliteInspectionFindingsRepository = class {
27950
28196
  };
27951
28197
 
27952
28198
  // ../../packages/persistence/src/repositories/installed-packs.ts
27953
- import { createHash as createHash2, randomUUID as randomUUID3 } from "crypto";
28199
+ import { createHash as createHash2, randomUUID as randomUUID4 } from "crypto";
28200
+
28201
+ // ../../packages/persistence/src/policy-floor.ts
28202
+ import { readFileSync as readFileSync5 } from "fs";
28203
+ import { join as join6 } from "path";
28204
+
28205
+ // ../../packages/persistence/src/local-layout.ts
28206
+ import { renameSync as renameSync3 } from "fs";
28207
+ import { mkdir } from "fs/promises";
28208
+ import { homedir } from "os";
28209
+ import { join as join4 } from "path";
28210
+ function defaultDataDir() {
28211
+ return join4(homedir(), ".aka");
28212
+ }
28213
+ function settingsDir(base = defaultDataDir()) {
28214
+ return join4(base, "settings");
28215
+ }
28216
+ function dataDir(base = defaultDataDir()) {
28217
+ return join4(base, "data");
28218
+ }
28219
+ function dbPath(base = defaultDataDir()) {
28220
+ return join4(dataDir(base), "aka.db");
28221
+ }
28222
+ async function ensureDataDir(dir = defaultDataDir()) {
28223
+ await mkdir(dir, { recursive: true, mode: DATA_DIR_MODE });
28224
+ tightenDir(dir);
28225
+ }
28226
+ function ensureLayoutDirSync(dir = defaultDataDir()) {
28227
+ ensureDataDirSync(dir);
28228
+ }
28229
+ function migrateLegacyLayout(base = defaultDataDir()) {
28230
+ const moves = [
28231
+ { name: "config.json", dest: settingsDir(base) },
28232
+ { name: "policy-cache.json", dest: dataDir(base) }
28233
+ ];
28234
+ for (const { name, dest } of moves) {
28235
+ try {
28236
+ ensureDataDirSync(dest);
28237
+ const moved = join4(dest, name);
28238
+ renameSync3(join4(base, name), moved);
28239
+ tightenFile(moved);
28240
+ } catch {
28241
+ }
28242
+ }
28243
+ }
28244
+
28245
+ // ../../packages/persistence/src/settings.ts
28246
+ import { readFileSync as readFileSync4 } from "fs";
28247
+ import { join as join5 } from "path";
28248
+
28249
+ // ../../packages/persistence/src/file-lock.ts
28250
+ import { randomUUID as randomUUID3 } from "crypto";
28251
+ import {
28252
+ closeSync,
28253
+ existsSync as existsSync2,
28254
+ openSync,
28255
+ readFileSync as readFileSync2,
28256
+ rmSync as rmSync5,
28257
+ statSync as statSync3,
28258
+ writeFileSync as writeFileSync2
28259
+ } from "fs";
28260
+ import { hostname as hostname3 } from "os";
28261
+ var PARK = new Int32Array(new SharedArrayBuffer(4));
28262
+
28263
+ // ../../packages/persistence/src/managed-settings.ts
28264
+ import { readFileSync as readFileSync3 } from "fs";
28265
+ import { posix, win32 } from "path";
28266
+ function managedSettingsPaths(platform2 = process.platform) {
28267
+ if (platform2 === "darwin") {
28268
+ return [
28269
+ posix.join("/Library", "Application Support", "AKASecurity", MANAGED_SETTINGS_FILENAME),
28270
+ posix.join("/Library", "Managed Preferences", MANAGED_SETTINGS_FILENAME)
28271
+ ];
28272
+ }
28273
+ if (platform2 === "win32") {
28274
+ return [win32.join("C:\\", "ProgramData", "AKASecurity", MANAGED_SETTINGS_FILENAME)];
28275
+ }
28276
+ return [posix.join("/etc", "aka", MANAGED_SETTINGS_FILENAME)];
28277
+ }
28278
+ function readManagedSettings(paths = managedSettingsPaths()) {
28279
+ for (const path of paths) {
28280
+ let text;
28281
+ try {
28282
+ text = readFileSync3(path, "utf8");
28283
+ } catch {
28284
+ continue;
28285
+ }
28286
+ const record2 = parseJsonObject(text);
28287
+ if (!record2) continue;
28288
+ const parsed2 = ManagedSettings.safeParse(record2);
28289
+ if (parsed2.success) return parsed2.data;
28290
+ }
28291
+ return null;
28292
+ }
28293
+ function overlayManagedSettings(settings, managed, now = () => /* @__PURE__ */ new Date()) {
28294
+ if (!managed) return settings;
28295
+ const { values } = managed;
28296
+ const merged = { ...settings };
28297
+ if (values.runMode !== void 0) merged.runMode = values.runMode;
28298
+ if (values.controlPlane !== void 0) {
28299
+ merged.controlPlane = {
28300
+ ...values.controlPlane,
28301
+ // The administrator pinned WHICH deployment, not WHEN this machine
28302
+ // joined it. Keep the user's own attach time when the endpoint is
28303
+ // unchanged, so a managed machine does not appear to re-attach on every
28304
+ // read; stamp a fresh one when the administrator moved it.
28305
+ attachedAt: settings.controlPlane?.endpoint === values.controlPlane.endpoint ? settings.controlPlane.attachedAt : now().toISOString()
28306
+ };
28307
+ }
28308
+ if (values.historicalAccess !== void 0) merged.historicalAccess = values.historicalAccess;
28309
+ if (values.vaultKeyCustody !== void 0) merged.vaultKeyCustody = values.vaultKeyCustody;
28310
+ if (values.vaultInlineReveal !== void 0) merged.vaultInlineReveal = values.vaultInlineReveal;
28311
+ if (values.dataSharesInPlace !== void 0) merged.dataSharesInPlace = values.dataSharesInPlace;
28312
+ if (values.redactFallback !== void 0) merged.redactFallback = values.redactFallback;
28313
+ if (values.vaultConsent !== void 0) {
28314
+ merged.vaultConsent = values.vaultConsent ? (
28315
+ // Keep an existing valid grant so its acknowledgedAt survives; mint one
28316
+ // at the current version otherwise.
28317
+ settings.vaultConsent?.version === VAULT_CONSENT_VERSION ? settings.vaultConsent : { acknowledgedAt: now().toISOString(), version: VAULT_CONSENT_VERSION }
28318
+ ) : void 0;
28319
+ }
28320
+ if (values.modelJudgeConsent !== void 0) {
28321
+ merged.modelJudgeConsent = values.modelJudgeConsent ? settings.modelJudgeConsent?.payloadVersion === MODEL_JUDGE_PAYLOAD_VERSION ? settings.modelJudgeConsent : {
28322
+ acknowledgedAt: now().toISOString(),
28323
+ payloadVersion: MODEL_JUDGE_PAYLOAD_VERSION
28324
+ } : void 0;
28325
+ }
28326
+ return merged;
28327
+ }
28328
+
28329
+ // ../../packages/persistence/src/settings.ts
28330
+ var SETTINGS_FILENAME = "settings.json";
28331
+ function readWorkspaceSettings(base = defaultDataDir()) {
28332
+ return overlayManagedSettings(readUserSettings(base), readManagedSettings());
28333
+ }
28334
+ function readUserSettings(base) {
28335
+ const record2 = readJson(join5(settingsDir(base), SETTINGS_FILENAME));
28336
+ if (!record2) return defaultWorkspaceSettings();
28337
+ try {
28338
+ return WorkspaceSettings.parse(record2);
28339
+ } catch {
28340
+ return defaultWorkspaceSettings();
28341
+ }
28342
+ }
28343
+ function readJson(file2) {
28344
+ let text;
28345
+ try {
28346
+ text = readFileSync4(file2, "utf8");
28347
+ } catch {
28348
+ return null;
28349
+ }
28350
+ return parseJsonObject(text) ?? null;
28351
+ }
28352
+
28353
+ // ../../packages/persistence/src/policy-floor.ts
28354
+ function refusalMessage(pack, attempted, floor, refusal) {
28355
+ switch (refusal) {
28356
+ case "lock":
28357
+ return `refusing to re-assign '${pack}': its policy is set by the connected control plane`;
28358
+ case "disable":
28359
+ return `refusing to disable '${pack}': it is governed by the connected control plane`;
28360
+ case "floor":
28361
+ return `refusing to set '${pack}' to '${attempted ?? "unassigned"}': the connected control plane requires at least '${floor}'`;
28362
+ }
28363
+ }
28364
+ var PolicyFloorError = class extends Error {
28365
+ /** `namespace/packId` of the detection whose write was refused. */
28366
+ pack;
28367
+ /**
28368
+ * The archetype the caller asked for, or null when the write named none —
28369
+ * clearing the assignment, or switching the detection off.
28370
+ */
28371
+ attempted;
28372
+ /** The weakest archetype the control plane permits for this pack. */
28373
+ floor;
28374
+ refusal;
28375
+ constructor(pack, attempted, floor, refusal) {
28376
+ super(refusalMessage(pack, attempted, floor, refusal));
28377
+ this.name = "PolicyFloorError";
28378
+ this.pack = pack;
28379
+ this.attempted = attempted;
28380
+ this.floor = floor;
28381
+ this.refusal = refusal;
28382
+ }
28383
+ };
28384
+ function readCachedPolicyBundle(base = defaultDataDir()) {
28385
+ try {
28386
+ const raw = readFileSync5(join6(dataDir(base), POLICY_CACHE_FILENAME), "utf8");
28387
+ const parsed2 = JSON.parse(raw);
28388
+ if (typeof parsed2 !== "object" || parsed2 === null) return null;
28389
+ return PolicyBundle.parse(parsed2.bundle);
28390
+ } catch {
28391
+ return null;
28392
+ }
28393
+ }
28394
+ function indexEnabled(policies) {
28395
+ const byRuleId = /* @__PURE__ */ new Map();
28396
+ const byCategory = /* @__PURE__ */ new Map();
28397
+ for (const policy of policies) {
28398
+ if (!policy.enabled) continue;
28399
+ if ("ruleId" in policy.target) {
28400
+ if (!byRuleId.has(policy.target.ruleId)) byRuleId.set(policy.target.ruleId, policy.action);
28401
+ } else if (!byCategory.has(policy.target.category)) {
28402
+ byCategory.set(policy.target.category, policy.action);
28403
+ }
28404
+ }
28405
+ return { byRuleId, byCategory };
28406
+ }
28407
+ function hasAuthoredPolicy(policies, rules, byRuleId) {
28408
+ const ruleIds = new Set(rules.map((rule) => rule.id));
28409
+ const categories = new Set(rules.map((rule) => rule.category));
28410
+ const bundleNamesPack = rules.some((rule) => byRuleId.has(rule.id));
28411
+ return policies.some((policy) => {
28412
+ if (!policy.enabled || policy.provenance !== "authored") return false;
28413
+ return "ruleId" in policy.target ? ruleIds.has(policy.target.ruleId) : bundleNamesPack && categories.has(policy.target.category);
28414
+ });
28415
+ }
28416
+ function controlPlanePolicyFloor(rules, base = defaultDataDir()) {
28417
+ const floors = openControlPlaneFloors(base);
28418
+ return floors === null ? null : floors.floorFor(rules);
28419
+ }
28420
+ function openControlPlaneFloors(base = defaultDataDir()) {
28421
+ if (!isAttached(readWorkspaceSettings(base))) return null;
28422
+ const bundle = readCachedPolicyBundle(base);
28423
+ if (bundle === null) return null;
28424
+ const indexes = indexEnabled(bundle.policies);
28425
+ return { floorFor: (rules) => resolveFloor(rules, bundle.policies, indexes) };
28426
+ }
28427
+ function resolveFloor(rules, policies, { byRuleId, byCategory }) {
28428
+ let action = null;
28429
+ for (const rule of rules) {
28430
+ const resolved = byRuleId.get(rule.id) ?? byCategory.get(rule.category);
28431
+ if (resolved === void 0) continue;
28432
+ action = action === null ? resolved : strongerAction(action, resolved);
28433
+ }
28434
+ if (action === null) return null;
28435
+ return {
28436
+ floor: weakestBuiltinAtLeast(action),
28437
+ locked: hasAuthoredPolicy(policies, rules, byRuleId)
28438
+ };
28439
+ }
28440
+ function policyAssignmentRefusal(policyId, floor) {
28441
+ if (floor.locked) return "lock";
28442
+ const effective = policyId ?? DEFAULT_PACK_POLICY_ID;
28443
+ return isActionAtLeast(builtinPolicyToAction(effective), builtinPolicyToAction(floor.floor)) ? null : "floor";
28444
+ }
28445
+ function packEnablementRefusal(enabled, floor) {
28446
+ if (floor === null || enabled) return null;
28447
+ return "disable";
28448
+ }
27954
28449
 
27955
28450
  // ../../packages/persistence/src/semver.ts
27956
28451
  function parse3(version2) {
@@ -28044,8 +28539,19 @@ function ruleIdsOf(rulesJson) {
28044
28539
  return ids;
28045
28540
  }
28046
28541
  var SqliteInstalledPacksRepository = class {
28047
- constructor(db) {
28542
+ /**
28543
+ * `baseDir` is the `~/.aka` LAYOUT BASE, not the data dir — the control-plane
28544
+ * floor needs both halves of it (settings/ says whether this machine is
28545
+ * attached, data/ holds the cached bundle). It is optional because a caller
28546
+ * holding only a DatabaseSync — every test construction site, and any embedder
28547
+ * that opens the store itself — has no layout to point at, and such a caller
28548
+ * gets the pre-existing behaviour: no floor, no lock. Production threads it in
28549
+ * from `openLocalDatabase`, which is the single construction site that owns a
28550
+ * real `~/.aka`.
28551
+ */
28552
+ constructor(db, baseDir) {
28048
28553
  this.db = db;
28554
+ this.baseDir = baseDir;
28049
28555
  this.insertMissingStmt = db.prepare(
28050
28556
  `INSERT INTO installed_packs (id, namespace, pack_id, version, name, rules_json, enabled, created_at, updated_at)
28051
28557
  VALUES (:id, :namespace, :packId, :version, :name, :rulesJson, 1, :now, :now)
@@ -28067,11 +28573,17 @@ var SqliteInstalledPacksRepository = class {
28067
28573
  this.signatureStmt = db.prepare(
28068
28574
  `SELECT namespace, pack_id AS packId, version, rules_json AS rulesJson FROM available_packs`
28069
28575
  );
28576
+ this.packRulesStmt = db.prepare(
28577
+ `SELECT rules_json AS rulesJson FROM installed_packs
28578
+ WHERE namespace = ? AND pack_id = ?`
28579
+ );
28070
28580
  }
28071
28581
  db;
28582
+ baseDir;
28072
28583
  insertMissingStmt;
28073
28584
  upsertAvailableStmt;
28074
28585
  signatureStmt;
28586
+ packRulesStmt;
28075
28587
  /**
28076
28588
  * Record the running binary's detection inventory. Refreshes the
28077
28589
  * available_packs mirror (pruning packs the binary no longer ships) and
@@ -28113,7 +28625,7 @@ var SqliteInstalledPacksRepository = class {
28113
28625
  let behind = false;
28114
28626
  for (const row of rows) {
28115
28627
  const params = {
28116
- id: randomUUID3(),
28628
+ id: randomUUID4(),
28117
28629
  namespace: row.namespace,
28118
28630
  packId: row.packId,
28119
28631
  version: row.version,
@@ -28125,7 +28637,7 @@ var SqliteInstalledPacksRepository = class {
28125
28637
  if (stored === void 0 || !isMirrorDowngrade(row, stored)) {
28126
28638
  this.upsertAvailableStmt.run({
28127
28639
  ...params,
28128
- id: randomUUID3(),
28640
+ id: randomUUID4(),
28129
28641
  recordedBy: meta4?.recordedBy ?? null
28130
28642
  });
28131
28643
  } else {
@@ -28371,9 +28883,65 @@ var SqliteInstalledPacksRepository = class {
28371
28883
  // NOT on the hook path — so, unlike recordInventory, these surface errors to the
28372
28884
  // caller rather than swallowing them. Each returns whether a row matched, so the
28373
28885
  // caller can tell an edit from a no-such-detection.
28886
+ /**
28887
+ * The rules one installed pack owns, reduced to what a floor computation
28888
+ * reads. Display-tolerant parsing on purpose: a pack whose snapshot is
28889
+ * unreadable contributes no rules to a scan either, so it is not a detection
28890
+ * the control plane can be governing, and an empty list correctly imposes no
28891
+ * floor. Enabled state is deliberately not filtered — a disabled pack is one
28892
+ * the user can re-enable, and its assignment stays governed meanwhile.
28893
+ */
28894
+ packFloorRules(namespace, packId) {
28895
+ const row = getRow(this.packRulesStmt, [namespace, packId]);
28896
+ if (!row) return [];
28897
+ return parseRules(row.rulesJson).map((rule) => ({ id: rule.id, category: rule.category }));
28898
+ }
28899
+ /**
28900
+ * What the connected control plane imposes on one installed pack, or null on a
28901
+ * machine that is its own authority (standalone, no cached bundle, or a
28902
+ * repository constructed without a layout base).
28903
+ *
28904
+ * Exposed as a READ so a surface can render the constraint — grey out the
28905
+ * choices below the floor, mark a locked detection as locked — rather than
28906
+ * offer the user a picker whose selections it will then be told it may not
28907
+ * make. The refusal in `setPolicy` does not depend on any surface calling this.
28908
+ */
28909
+ policyFloor(namespace, packId) {
28910
+ if (this.baseDir === void 0) return null;
28911
+ return controlPlanePolicyFloor(this.packFloorRules(namespace, packId), this.baseDir);
28912
+ }
28913
+ /**
28914
+ * The same answer for several packs, keyed `namespace/packId` and carrying an
28915
+ * entry only for a pack the control plane actually governs.
28916
+ *
28917
+ * A surface listing every detection asks per pack, and asking through
28918
+ * `policyFloor` re-reads the settings, re-reads and re-parses the whole cached
28919
+ * bundle and rebuilds its indexes once per pack — the entire cost of one
28920
+ * answer, repeated for each row, on every render. This reads all of that once.
28921
+ * Packs whose rules the snapshot cannot produce simply contribute no entry,
28922
+ * exactly as the single-pack read returns null for them.
28923
+ */
28924
+ policyFloors(packs2) {
28925
+ const floors = /* @__PURE__ */ new Map();
28926
+ if (this.baseDir === void 0) return floors;
28927
+ const source = openControlPlaneFloors(this.baseDir);
28928
+ if (source === null) return floors;
28929
+ for (const pack of packs2) {
28930
+ const floor = source.floorFor(this.packFloorRules(pack.namespace, pack.packId));
28931
+ if (floor !== null) floors.set(`${pack.namespace}/${pack.packId}`, floor);
28932
+ }
28933
+ return floors;
28934
+ }
28374
28935
  /**
28375
28936
  * Assign (or clear, with null) the enforcement policy for one installed pack.
28376
- * `policyId` must be a known built-in id (monitor/warn/redact/block).
28937
+ * `policyId` must be a known built-in id (monitor/warn/redact/block/vault).
28938
+ *
28939
+ * On an ATTACHED machine the organization's bundle is a floor this refuses to
28940
+ * write below, and a detection the organization has authored a policy for is
28941
+ * refused outright — see policy-floor.ts for both, and for why the refusal is
28942
+ * a throw rather than a silently substituted value. This is the one device-local
28943
+ * write path for the assignment, so the check belongs here rather than on any
28944
+ * surface that offers the choice.
28377
28945
  */
28378
28946
  setPolicy(namespace, packId, policyId) {
28379
28947
  if (policyId !== null && !BuiltinPolicyId.safeParse(policyId).success) {
@@ -28381,14 +28949,38 @@ var SqliteInstalledPacksRepository = class {
28381
28949
  `Unknown policy '${policyId}'. Must be one of: ${KNOWN_BUILTIN_IDS.join(", ")}.`
28382
28950
  );
28383
28951
  }
28952
+ const requested = policyId;
28953
+ const floor = this.policyFloor(namespace, packId);
28954
+ if (floor !== null) {
28955
+ const refusal = policyAssignmentRefusal(requested, floor);
28956
+ if (refusal !== null) {
28957
+ throw new PolicyFloorError(`${namespace}/${packId}`, requested, floor.floor, refusal);
28958
+ }
28959
+ }
28384
28960
  const res = this.db.prepare(
28385
28961
  `UPDATE installed_packs SET policy_id = :policyId, updated_at = :now
28386
28962
  WHERE namespace = :namespace AND pack_id = :packId`
28387
28963
  ).run({ policyId, now: Date.now(), namespace, packId });
28388
28964
  return Number(res.changes) > 0;
28389
28965
  }
28390
- /** Enable or disable one installed pack. */
28966
+ /**
28967
+ * Enable or disable one installed pack.
28968
+ *
28969
+ * On an ATTACHED machine a detection the organization's bundle governs at all
28970
+ * may not be switched OFF here — see packEnablementRefusal for why that is not
28971
+ * merely another point below the floor, and why re-enabling stays open. Like
28972
+ * the assignment above, the check belongs at this write path rather than on a
28973
+ * surface: this is the one device-local writer of the column, and a refusal
28974
+ * that lived in a page would leave the CLI free.
28975
+ */
28391
28976
  setEnabled(namespace, packId, enabled) {
28977
+ const floor = this.policyFloor(namespace, packId);
28978
+ if (floor !== null) {
28979
+ const refusal = packEnablementRefusal(enabled, floor);
28980
+ if (refusal !== null) {
28981
+ throw new PolicyFloorError(`${namespace}/${packId}`, null, floor.floor, refusal);
28982
+ }
28983
+ }
28392
28984
  const res = this.db.prepare(
28393
28985
  `UPDATE installed_packs SET enabled = :enabled, updated_at = :now
28394
28986
  WHERE namespace = :namespace AND pack_id = :packId`
@@ -28474,7 +29066,7 @@ var SqliteInventoryRepository = class {
28474
29066
  };
28475
29067
 
28476
29068
  // ../../packages/persistence/src/repositories/inventory-assets.ts
28477
- import { randomUUID as randomUUID4 } from "crypto";
29069
+ import { randomUUID as randomUUID5 } from "crypto";
28478
29070
  var CATEGORY_ORDER = ["config", "skill", "mcp", "hook"];
28479
29071
  var VALID_HARNESS_IDS = new Set(HarnessId.options);
28480
29072
  var WORKTREE_CHECKOUT_FILTER = "(url IS NULL OR (url NOT LIKE '%/.claude/worktrees/%' AND url NOT LIKE '%\\.claude\\worktrees\\%'))";
@@ -28963,7 +29555,7 @@ var SqliteInventoryAssetsRepository = class {
28963
29555
  `INSERT INTO file_access_override (id, project_id, path, access, created_at, updated_at)
28964
29556
  VALUES (:id, :projectId, :path, :access, :now, :now)
28965
29557
  ON CONFLICT (project_id, path) DO UPDATE SET access = excluded.access, updated_at = excluded.updated_at`
28966
- ).run({ id: randomUUID4(), projectId, path, access, now: Date.now() });
29558
+ ).run({ id: randomUUID5(), projectId, path, access, now: Date.now() });
28967
29559
  }
28968
29560
  return true;
28969
29561
  }
@@ -28984,7 +29576,7 @@ var SqliteInventoryAssetsRepository = class {
28984
29576
  `INSERT INTO mcp_trust_override (id, asset_id, trust, created_at, updated_at)
28985
29577
  VALUES (:id, :assetId, :trust, :now, :now)
28986
29578
  ON CONFLICT (asset_id) DO UPDATE SET trust = excluded.trust, updated_at = excluded.updated_at`
28987
- ).run({ id: randomUUID4(), assetId, trust, now: Date.now() });
29579
+ ).run({ id: randomUUID5(), assetId, trust, now: Date.now() });
28988
29580
  }
28989
29581
  this.configRowsCache = void 0;
28990
29582
  return "ok";
@@ -29281,7 +29873,7 @@ var SqliteInventoryAssetsRepository = class {
29281
29873
  };
29282
29874
 
29283
29875
  // ../../packages/persistence/src/repositories/policies.ts
29284
- import { randomUUID as randomUUID5 } from "crypto";
29876
+ import { randomUUID as randomUUID6 } from "crypto";
29285
29877
  var SqlitePoliciesRepository = class {
29286
29878
  constructor(db) {
29287
29879
  this.db = db;
@@ -29316,7 +29908,7 @@ var SqlitePoliciesRepository = class {
29316
29908
  failOpenTransaction(this.db, () => {
29317
29909
  for (const [category, action] of Object.entries(DEFAULT_ACTIONS)) {
29318
29910
  stmt.run({
29319
- id: randomUUID5(),
29911
+ id: randomUUID6(),
29320
29912
  target: JSON.stringify({ category }),
29321
29913
  action,
29322
29914
  now: Date.now()
@@ -29336,7 +29928,7 @@ var SqlitePoliciesRepository = class {
29336
29928
  `INSERT INTO policies (id, scope, target, action, enabled, created_at, updated_at)
29337
29929
  VALUES (:id, 'global', :target, :action, 1, :now, :now)
29338
29930
  ON CONFLICT(scope, target) DO UPDATE SET action = excluded.action, enabled = 1, updated_at = excluded.updated_at`
29339
- ).run({ id: randomUUID5(), target: JSON.stringify({ category }), action, now });
29931
+ ).run({ id: randomUUID6(), target: JSON.stringify({ category }), action, now });
29340
29932
  }
29341
29933
  // Caps every global per-category policy currently set to block/redact down
29342
29934
  // to warn (see warn-era-cap.ts). Rule-targeted policies are untouched.
@@ -29404,7 +29996,7 @@ var SqlitePolicyCatalogRepository = class {
29404
29996
  };
29405
29997
 
29406
29998
  // ../../packages/persistence/src/repositories/project-files.ts
29407
- import { randomUUID as randomUUID6 } from "crypto";
29999
+ import { randomUUID as randomUUID7 } from "crypto";
29408
30000
  var SqliteProjectFilesRepository = class {
29409
30001
  constructor(db) {
29410
30002
  this.db = db;
@@ -29436,7 +30028,7 @@ var SqliteProjectFilesRepository = class {
29436
30028
  const stamp = Math.max(now, maxStamp + 1);
29437
30029
  for (const file2 of scan2.files) {
29438
30030
  this.upsertStmt.run({
29439
- id: randomUUID6(),
30031
+ id: randomUUID7(),
29440
30032
  projectId,
29441
30033
  path: file2.path,
29442
30034
  name: file2.name,
@@ -29450,9 +30042,9 @@ var SqliteProjectFilesRepository = class {
29450
30042
  };
29451
30043
 
29452
30044
  // ../../packages/persistence/src/repositories/resolutions.ts
29453
- import { randomUUID as randomUUID7 } from "crypto";
30045
+ import { randomUUID as randomUUID8 } from "crypto";
29454
30046
  var SqliteResolutionsRepository = class {
29455
- constructor(db, now = () => Date.now(), newId = () => randomUUID7()) {
30047
+ constructor(db, now = () => Date.now(), newId = () => randomUUID8()) {
29456
30048
  this.db = db;
29457
30049
  this.now = now;
29458
30050
  this.newId = newId;
@@ -29665,7 +30257,7 @@ var SqliteScanLedgerRepository = class {
29665
30257
  };
29666
30258
 
29667
30259
  // ../../packages/persistence/src/repositories/secret-vault.ts
29668
- import { randomUUID as randomUUID8 } from "crypto";
30260
+ import { randomUUID as randomUUID9 } from "crypto";
29669
30261
  function pageLimit(requested, fallback) {
29670
30262
  if (requested === void 0) return fallback;
29671
30263
  return Math.min(Math.max(1, Math.trunc(requested)), MAX_VAULT_PAGE_LIMIT);
@@ -29711,12 +30303,14 @@ var SELECT_COLUMNS = `
29711
30303
  ciphertext,
29712
30304
  nonce,
29713
30305
  auth_tag AS authTag,
30306
+ user_authorized AS userAuthorized,
29714
30307
  occurrence_count AS occurrenceCount,
29715
30308
  first_seen AS firstSeen,
29716
30309
  last_seen AS lastSeen`;
29717
30310
  function toRow(raw) {
29718
- const { provider, ...rest } = raw;
29719
- return provider === null ? rest : { ...rest, provider };
30311
+ const { provider, userAuthorized, ...rest } = raw;
30312
+ const row = { ...rest, userAuthorized: userAuthorized !== 0 };
30313
+ return provider === null ? row : { ...row, provider };
29720
30314
  }
29721
30315
  var SqliteSecretVaultRepository = class {
29722
30316
  constructor(db) {
@@ -29726,17 +30320,18 @@ var SqliteSecretVaultRepository = class {
29726
30320
  pointer_id, value_fingerprint, fingerprint_key_version, key_version,
29727
30321
  format_version, category, rule_id, masked_match, provider,
29728
30322
  ciphertext, nonce, auth_tag,
29729
- occurrence_count, first_seen, last_seen
30323
+ user_authorized, occurrence_count, first_seen, last_seen
29730
30324
  ) VALUES (
29731
30325
  :pointerId, :valueFingerprint, :fingerprintKeyVersion, :keyVersion,
29732
30326
  :formatVersion, :category, :ruleId, :maskedMatch, :provider,
29733
30327
  :ciphertext, :nonce, :authTag,
29734
- 1, :now, :now
30328
+ :userAuthorized, 1, :now, :now
29735
30329
  )`
29736
30330
  );
29737
30331
  this.bumpStmt = db.prepare(
29738
30332
  `UPDATE secret_vault
29739
- SET occurrence_count = occurrence_count + 1, last_seen = :now
30333
+ SET occurrence_count = occurrence_count + 1, last_seen = :now,
30334
+ user_authorized = max(user_authorized, :userAuthorized)
29740
30335
  WHERE value_fingerprint = :valueFingerprint`
29741
30336
  );
29742
30337
  this.byPointerStmt = db.prepare(
@@ -29756,6 +30351,7 @@ var SqliteSecretVaultRepository = class {
29756
30351
  SET value_fingerprint = :valueFingerprint, fingerprint_key_version = :fingerprintKeyVersion
29757
30352
  WHERE pointer_id = :pointerId`
29758
30353
  );
30354
+ this.deleteByPointerStmt = db.prepare(`DELETE FROM secret_vault WHERE pointer_id = :pointerId`);
29759
30355
  this.derefStmt = db.prepare(
29760
30356
  `INSERT INTO secret_vault_deref (id, pointer_id, at, target, reason, outcome, grant_id, pointer_count)
29761
30357
  VALUES (:id, :pointerId, :at, :target, :reason, :outcome, :grantId, :pointerCount)`
@@ -29769,6 +30365,7 @@ var SqliteSecretVaultRepository = class {
29769
30365
  listStmt;
29770
30366
  replaceCiphertextStmt;
29771
30367
  refreshFingerprintStmt;
30368
+ deleteByPointerStmt;
29772
30369
  derefStmt;
29773
30370
  /**
29774
30371
  * Vault a value, or record another sighting of one already vaulted. Keyed on
@@ -29777,6 +30374,11 @@ var SqliteSecretVaultRepository = class {
29777
30374
  * pointer, category and ciphertext, so the same secret always resolves to one
29778
30375
  * wire token. `minted` is true only when this call created the row.
29779
30376
  *
30377
+ * `userAuthorized` is the one field a repeat call may still change, and only
30378
+ * upwards: it records that a PERSON asked for this value to be replaced, and
30379
+ * the row is shared with every automatic path that vaults the same value. See
30380
+ * `bumpStmt` for why clearing it is the defect this shape exists to refuse.
30381
+ *
29780
30382
  * The read-then-write runs in one IMMEDIATE transaction so two concurrent
29781
30383
  * writers cannot both decide they are minting.
29782
30384
  */
@@ -29803,13 +30405,18 @@ var SqliteSecretVaultRepository = class {
29803
30405
  ciphertext: input2.ciphertext,
29804
30406
  nonce: input2.nonce,
29805
30407
  authTag: input2.authTag,
30408
+ userAuthorized: input2.userAuthorized === true ? 1 : 0,
29806
30409
  now
29807
30410
  })
29808
30411
  );
29809
30412
  minted = true;
29810
30413
  return;
29811
30414
  }
29812
- this.bumpStmt.run({ valueFingerprint: input2.valueFingerprint, now });
30415
+ this.bumpStmt.run({
30416
+ valueFingerprint: input2.valueFingerprint,
30417
+ userAuthorized: input2.userAuthorized === true ? 1 : 0,
30418
+ now
30419
+ });
29813
30420
  },
29814
30421
  "IMMEDIATE"
29815
30422
  );
@@ -29869,6 +30476,42 @@ var SqliteSecretVaultRepository = class {
29869
30476
  );
29870
30477
  return destroyed;
29871
30478
  }
30479
+ /**
30480
+ * Destroy the named entries and report WHICH ones went — the scoped
30481
+ * counterpart to `purgeAll`, for a caller that has already put those specific
30482
+ * values back where they came from. Ids the store does not hold are absent
30483
+ * from the answer rather than an error, so a set assembled from a stale read
30484
+ * is not a fault. The deref audit is left alone, exactly as the purge leaves
30485
+ * it.
30486
+ *
30487
+ * The ids come back rather than a count because the caller's next act is to
30488
+ * write a purge row per destroyed entry, and a record of destruction has to
30489
+ * be a record of what was really destroyed: a selection is a claim about a
30490
+ * read that has since gone stale, and auditing from it invents a purge for an
30491
+ * entry still sitting in the vault.
30492
+ *
30493
+ * One transaction over the whole set rather than a statement per id: the
30494
+ * caller hands this the result of a restore pass it has completed, and a
30495
+ * fault partway through must leave the vault as it was found rather than
30496
+ * destroying a prefix of it. The vault holds the only copy of what a pointer
30497
+ * stands for, so half a delete is not a state anything can recover from.
30498
+ */
30499
+ deleteByPointerIds(pointerIds) {
30500
+ if (pointerIds.length === 0) return [];
30501
+ const deleted = [];
30502
+ withTransaction(
30503
+ this.db,
30504
+ () => {
30505
+ for (const pointerId of pointerIds) {
30506
+ if (Number(this.deleteByPointerStmt.run({ pointerId }).changes) > 0) {
30507
+ deleted.push(pointerId);
30508
+ }
30509
+ }
30510
+ },
30511
+ "IMMEDIATE"
30512
+ );
30513
+ return deleted;
30514
+ }
29872
30515
  /**
29873
30516
  * Record (or re-stamp) one place a pointer has been written. One row per
29874
30517
  * (pointer, location); a re-sighting bumps last_seen. Best-effort bookkeeping
@@ -29881,7 +30524,7 @@ var SqliteSecretVaultRepository = class {
29881
30524
  VALUES (:id, :pointerId, :location, :kind, :now, :now)
29882
30525
  ON CONFLICT (pointer_id, location) DO UPDATE SET last_seen = :now`
29883
30526
  ).run({
29884
- id: randomUUID8(),
30527
+ id: randomUUID9(),
29885
30528
  pointerId: entry.pointerId,
29886
30529
  location: entry.location,
29887
30530
  kind: entry.kind,
@@ -30394,15 +31037,15 @@ var SqliteSecurityRepository = class {
30394
31037
  const from = now - RANGE_DAYS[range] * DAY_MS4;
30395
31038
  const rows = allRows(
30396
31039
  this.db.prepare(
30397
- `SELECT json_extract(e.attributes, '$.repo') AS repo, count(*) AS c
31040
+ `SELECT e.repo AS repo, count(*) AS c
30398
31041
  FROM inspection_findings f
30399
31042
  JOIN audit_events e ON e.id = f.audit_event_id
30400
31043
  WHERE e.started_at >= :from AND e.started_at < :to
30401
31044
  AND e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
30402
- AND json_extract(e.attributes, '$.repo') IS NOT NULL
30403
- AND json_extract(e.attributes, '$.repo') != ''
30404
- GROUP BY repo
30405
- ORDER BY c DESC, repo
31045
+ AND e.repo IS NOT NULL
31046
+ AND e.repo != ''
31047
+ GROUP BY e.repo
31048
+ ORDER BY c DESC, e.repo
30406
31049
  LIMIT :limit`
30407
31050
  ),
30408
31051
  { from, to: now, limit }
@@ -30464,7 +31107,7 @@ var SqliteSecurityRepository = class {
30464
31107
  `SELECT f.finding_key AS finding_key,
30465
31108
  d.rule_id AS rule_id,
30466
31109
  d.severity AS severity,
30467
- json_extract(e.attributes, '$.file_path') AS path,
31110
+ e.file_path AS path,
30468
31111
  COALESCE(f.first_detected_at, e.started_at) AS first_detected_at,
30469
31112
  latest.resolved_at AS latest_resolved_at
30470
31113
  FROM ${LATEST_RESOLUTION_BY_KEY_SQL} latest
@@ -30517,7 +31160,7 @@ var SqliteSecurityRepository = class {
30517
31160
  };
30518
31161
 
30519
31162
  // ../../packages/persistence/src/repositories/shares.ts
30520
- import { randomUUID as randomUUID9 } from "crypto";
31163
+ import { randomUUID as randomUUID10 } from "crypto";
30521
31164
  var MAX_EGRESS_CALL_SITES_PER_PROJECT = 5e3;
30522
31165
  var IN_CHUNK = 500;
30523
31166
  var KIND_ORDER = ["provider", "internal", "external", "ip"];
@@ -30605,7 +31248,7 @@ function buildSummary(dest, endpoints) {
30605
31248
  callSiteCount,
30606
31249
  transports: distinctTransports(transports),
30607
31250
  dataClasses: distinctDataClasses(dataClasses),
30608
- review: buildReviewInfo(dest.trust, transports),
31251
+ review: buildReviewInfo(dest.trust, transports, dest.overrideDecision !== null),
30609
31252
  network: dest.kind === "provider" ? null : parseNetwork(dest.networkJson),
30610
31253
  endpoints: endpoints.map(toEndpointSummary)
30611
31254
  };
@@ -30632,7 +31275,7 @@ function buildDetail(dest, endpoints, callSites) {
30632
31275
  lastSeen: new Date(lastSeenMs).toISOString(),
30633
31276
  transports: distinctTransports(transports),
30634
31277
  dataClasses: distinctDataClasses(endpoints.map((e) => e.dataClass)),
30635
- review: buildReviewInfo(dest.trust, transports),
31278
+ review: buildReviewInfo(dest.trust, transports, dest.overrideDecision !== null),
30636
31279
  network: dest.kind === "provider" ? null : parseNetwork(dest.networkJson),
30637
31280
  note: dest.note,
30638
31281
  endpoints: endpoints.map((ep) => ({
@@ -30661,7 +31304,11 @@ var SqliteSharesRepository = class {
30661
31304
  FROM share_destination d
30662
31305
  LEFT JOIN share_endpoint e ON e.destination_id = d.id
30663
31306
  AND e.transport IN ${PLAINTEXT_TRANSPORT_SQL}
30664
- WHERE d.trust IN ('unverified', 'ip') OR e.id IS NOT NULL`
31307
+ WHERE (d.trust IN ('unverified', 'ip') OR e.id IS NOT NULL)
31308
+ AND NOT EXISTS (
31309
+ SELECT 1 FROM egress_decision_override o
31310
+ WHERE o.host = d.host OR (o.destination_id = d.id AND o.host IS NULL)
31311
+ )`
30665
31312
  );
30666
31313
  const kindCounts = countBy(
30667
31314
  this.db,
@@ -30773,7 +31420,7 @@ var SqliteSharesRepository = class {
30773
31420
  (id, destination_id, host, decision, created_at, updated_at)
30774
31421
  VALUES (:id, :destinationId, :host, :decision, :now, :now)`
30775
31422
  ).run({
30776
- id: randomUUID9(),
31423
+ id: randomUUID10(),
30777
31424
  destinationId,
30778
31425
  host: dest.host,
30779
31426
  decision,
@@ -30922,7 +31569,7 @@ var SqliteSharesRepository = class {
30922
31569
  let destinationId = destIds.get(hit.host);
30923
31570
  if (destinationId === void 0) {
30924
31571
  destStmt.run({
30925
- id: randomUUID9(),
31572
+ id: randomUUID10(),
30926
31573
  kind: hit.kind,
30927
31574
  name: hit.name,
30928
31575
  host: hit.host,
@@ -30938,7 +31585,7 @@ var SqliteSharesRepository = class {
30938
31585
  let endpointId = endpointIds.get(endpointKey);
30939
31586
  if (endpointId === void 0) {
30940
31587
  endpointStmt.run({
30941
- id: randomUUID9(),
31588
+ id: randomUUID10(),
30942
31589
  destinationId,
30943
31590
  method: hit.method,
30944
31591
  transport: hit.transport,
@@ -30951,7 +31598,7 @@ var SqliteSharesRepository = class {
30951
31598
  endpointIds.set(endpointKey, endpointId);
30952
31599
  }
30953
31600
  siteStmt.run({
30954
- id: randomUUID9(),
31601
+ id: randomUUID10(),
30955
31602
  endpointId,
30956
31603
  project: input2.project,
30957
31604
  projectKey: input2.projectKey,
@@ -31316,6 +31963,7 @@ function purgeSampleData(db) {
31316
31963
  }
31317
31964
 
31318
31965
  // ../../packages/persistence/src/database.ts
31966
+ var CAPTURE_GRAIN = new Set(EventKind.options);
31319
31967
  var UNSAFE_TEST_ONLY_RAW_HANDLE = /* @__PURE__ */ Symbol(
31320
31968
  "aka.persistence.unsafeTestOnlyRawHandle"
31321
31969
  );
@@ -31363,7 +32011,7 @@ function backupLegacyStore(db, file2) {
31363
32011
  discardStore(file2, backup);
31364
32012
  return backup;
31365
32013
  }
31366
- function openAndInitialize(file2) {
32014
+ function openAndInitialize(file2, base) {
31367
32015
  let db = openWithPragmas(file2);
31368
32016
  try {
31369
32017
  if (isForeignSqliteLineage(db)) {
@@ -31376,7 +32024,7 @@ function openAndInitialize(file2) {
31376
32024
  applyMigrations(db, file2);
31377
32025
  tightenPerms(file2);
31378
32026
  const policies = new SqlitePoliciesRepository(db);
31379
- const installedPacks = new SqliteInstalledPacksRepository(db);
32027
+ const installedPacks = new SqliteInstalledPacksRepository(db, base);
31380
32028
  const repositories = {
31381
32029
  events: new SqliteEventsRepository(db),
31382
32030
  findings: new SqliteFindingsRepository(db),
@@ -31412,7 +32060,7 @@ function openAndInitialize(file2) {
31412
32060
  }
31413
32061
  function openLocalDatabase(dir) {
31414
32062
  ensureDataDirSync(dir);
31415
- const file2 = join4(dir, DB_FILENAME);
32063
+ const file2 = join7(dir, DB_FILENAME);
31416
32064
  reapStalePartials(file2);
31417
32065
  const {
31418
32066
  db,
@@ -31440,7 +32088,13 @@ function openLocalDatabase(dir) {
31440
32088
  inspectionDefinitions,
31441
32089
  inspectionFindings,
31442
32090
  configInventory
31443
- } = openAndInitialize(file2);
32091
+ } = openAndInitialize(
32092
+ file2,
32093
+ // `dir` is always `<base>/data` — every caller resolves it through
32094
+ // `dataDir()` — so its parent is the `~/.aka` base the layout splits into
32095
+ // settings/ and data/, and the pack-policy floor needs both halves.
32096
+ dirname2(dir)
32097
+ );
31444
32098
  function captureRowId(event) {
31445
32099
  return captureId(
31446
32100
  event.metadata?.sessionId ?? null,
@@ -31453,6 +32107,21 @@ function openLocalDatabase(dir) {
31453
32107
  historySync.markSynced([captureRowId(event)], atMs);
31454
32108
  });
31455
32109
  }
32110
+ function markCaptureOwed(event) {
32111
+ failOpenTransaction(db, () => {
32112
+ historySync.markCaptureOwed(captureRowId(event));
32113
+ });
32114
+ }
32115
+ function markAuditEventsDelivered(events2, atMs) {
32116
+ const stampable = events2.filter((event) => !CAPTURE_GRAIN.has(event.eventType));
32117
+ if (stampable.length === 0) return;
32118
+ failOpenTransaction(db, () => {
32119
+ historySync.markSynced(
32120
+ stampable.map((event) => event.id),
32121
+ atMs
32122
+ );
32123
+ });
32124
+ }
31456
32125
  function recordCapture(event, detected) {
31457
32126
  failOpenTransaction(db, () => {
31458
32127
  const sessionId = event.metadata?.sessionId;
@@ -31539,7 +32208,7 @@ function openLocalDatabase(dir) {
31539
32208
  const definitionId = definitionIds.get(`${finding.ruleId}@${finding.version}`);
31540
32209
  if (!definitionId) continue;
31541
32210
  inspectionFindings.insertFinding({
31542
- id: randomUUID10(),
32211
+ id: randomUUID11(),
31543
32212
  auditEventId: record2.scanEvent.id,
31544
32213
  inspectionDefinitionId: definitionId,
31545
32214
  span: finding.span,
@@ -31635,6 +32304,8 @@ function openLocalDatabase(dir) {
31635
32304
  inspectionFindings,
31636
32305
  recordCapture,
31637
32306
  markCaptureDelivered,
32307
+ markCaptureOwed,
32308
+ markAuditEventsDelivered,
31638
32309
  ensureInventory,
31639
32310
  recordConfigScan,
31640
32311
  recordProjectFiles,
@@ -31653,32 +32324,18 @@ function openLocalDatabase(dir) {
31653
32324
  };
31654
32325
  }
31655
32326
 
31656
- // ../../packages/persistence/src/file-lock.ts
31657
- import { randomUUID as randomUUID11 } from "crypto";
31658
- import {
31659
- closeSync,
31660
- existsSync as existsSync2,
31661
- openSync,
31662
- readFileSync as readFileSync2,
31663
- rmSync as rmSync5,
31664
- statSync as statSync3,
31665
- writeFileSync as writeFileSync2
31666
- } from "fs";
31667
- import { hostname as hostname3 } from "os";
31668
- var PARK = new Int32Array(new SharedArrayBuffer(4));
31669
-
31670
32327
  // ../../packages/persistence/src/finding-key.ts
31671
32328
  import { createHash as createHash3 } from "crypto";
31672
32329
 
31673
32330
  // ../../packages/persistence/src/fingerprint.ts
31674
32331
  import { createHmac, randomBytes } from "crypto";
31675
- import { existsSync as existsSync3, readFileSync as readFileSync3 } from "fs";
31676
- import { join as join5 } from "path";
32332
+ import { existsSync as existsSync3, readFileSync as readFileSync6 } from "fs";
32333
+ import { join as join8 } from "path";
31677
32334
  import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
31678
32335
  var EXCEPTION_KEY_FILENAME = "exception.key";
31679
32336
  var KEY_MATERIAL_BYTES = 32;
31680
32337
  function keyFilePath(dataDir2) {
31681
- return join5(dataDir2, EXCEPTION_KEY_FILENAME);
32338
+ return join8(dataDir2, EXCEPTION_KEY_FILENAME);
31682
32339
  }
31683
32340
  function parseKeyFile(raw) {
31684
32341
  const parsed2 = JSON.parse(raw);
@@ -31701,7 +32358,7 @@ function parseKeyFile(raw) {
31701
32358
  function readFingerprintKey(dataDir2) {
31702
32359
  let raw;
31703
32360
  try {
31704
- raw = readFileSync3(keyFilePath(dataDir2), "utf8");
32361
+ raw = readFileSync6(keyFilePath(dataDir2), "utf8");
31705
32362
  } catch (err) {
31706
32363
  if (err.code === "ENOENT") return null;
31707
32364
  throw err instanceof Error ? err : new Error(String(err));
@@ -31711,143 +32368,12 @@ function readFingerprintKey(dataDir2) {
31711
32368
 
31712
32369
  // ../../packages/persistence/src/history-preview.ts
31713
32370
  import { existsSync as existsSync4 } from "fs";
31714
- import { join as join6 } from "path";
32371
+ import { join as join9 } from "path";
31715
32372
  import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
31716
32373
 
31717
- // ../../packages/persistence/src/local-layout.ts
31718
- import { renameSync as renameSync3 } from "fs";
31719
- import { mkdir } from "fs/promises";
31720
- import { homedir } from "os";
31721
- import { join as join7 } from "path";
31722
- function defaultDataDir() {
31723
- return join7(homedir(), ".aka");
31724
- }
31725
- function settingsDir(base = defaultDataDir()) {
31726
- return join7(base, "settings");
31727
- }
31728
- function dataDir(base = defaultDataDir()) {
31729
- return join7(base, "data");
31730
- }
31731
- function dbPath(base = defaultDataDir()) {
31732
- return join7(dataDir(base), "aka.db");
31733
- }
31734
- async function ensureDataDir(dir = defaultDataDir()) {
31735
- await mkdir(dir, { recursive: true, mode: DATA_DIR_MODE });
31736
- tightenDir(dir);
31737
- }
31738
- function ensureLayoutDirSync(dir = defaultDataDir()) {
31739
- ensureDataDirSync(dir);
31740
- }
31741
- function migrateLegacyLayout(base = defaultDataDir()) {
31742
- const moves = [
31743
- { name: "config.json", dest: settingsDir(base) },
31744
- { name: "policy-cache.json", dest: dataDir(base) }
31745
- ];
31746
- for (const { name, dest } of moves) {
31747
- try {
31748
- ensureDataDirSync(dest);
31749
- const moved = join7(dest, name);
31750
- renameSync3(join7(base, name), moved);
31751
- tightenFile(moved);
31752
- } catch {
31753
- }
31754
- }
31755
- }
31756
-
31757
- // ../../packages/persistence/src/managed-settings.ts
31758
- import { readFileSync as readFileSync4 } from "fs";
31759
- import { posix, win32 } from "path";
31760
- function managedSettingsPaths(platform2 = process.platform) {
31761
- if (platform2 === "darwin") {
31762
- return [
31763
- posix.join("/Library", "Application Support", "AKASecurity", MANAGED_SETTINGS_FILENAME),
31764
- posix.join("/Library", "Managed Preferences", MANAGED_SETTINGS_FILENAME)
31765
- ];
31766
- }
31767
- if (platform2 === "win32") {
31768
- return [win32.join("C:\\", "ProgramData", "AKASecurity", MANAGED_SETTINGS_FILENAME)];
31769
- }
31770
- return [posix.join("/etc", "aka", MANAGED_SETTINGS_FILENAME)];
31771
- }
31772
- function readManagedSettings(paths = managedSettingsPaths()) {
31773
- for (const path of paths) {
31774
- let text;
31775
- try {
31776
- text = readFileSync4(path, "utf8");
31777
- } catch {
31778
- continue;
31779
- }
31780
- const record2 = parseJsonObject(text);
31781
- if (!record2) continue;
31782
- const parsed2 = ManagedSettings.safeParse(record2);
31783
- if (parsed2.success) return parsed2.data;
31784
- }
31785
- return null;
31786
- }
31787
- function overlayManagedSettings(settings, managed, now = () => /* @__PURE__ */ new Date()) {
31788
- if (!managed) return settings;
31789
- const { values } = managed;
31790
- const merged = { ...settings };
31791
- if (values.runMode !== void 0) merged.runMode = values.runMode;
31792
- if (values.controlPlane !== void 0) {
31793
- merged.controlPlane = {
31794
- ...values.controlPlane,
31795
- // The administrator pinned WHICH deployment, not WHEN this machine
31796
- // joined it. Keep the user's own attach time when the endpoint is
31797
- // unchanged, so a managed machine does not appear to re-attach on every
31798
- // read; stamp a fresh one when the administrator moved it.
31799
- attachedAt: settings.controlPlane?.endpoint === values.controlPlane.endpoint ? settings.controlPlane.attachedAt : now().toISOString()
31800
- };
31801
- }
31802
- if (values.historicalAccess !== void 0) merged.historicalAccess = values.historicalAccess;
31803
- if (values.vaultKeyCustody !== void 0) merged.vaultKeyCustody = values.vaultKeyCustody;
31804
- if (values.vaultInlineReveal !== void 0) merged.vaultInlineReveal = values.vaultInlineReveal;
31805
- if (values.dataSharesInPlace !== void 0) merged.dataSharesInPlace = values.dataSharesInPlace;
31806
- if (values.vaultConsent !== void 0) {
31807
- merged.vaultConsent = values.vaultConsent ? (
31808
- // Keep an existing valid grant so its acknowledgedAt survives; mint one
31809
- // at the current version otherwise.
31810
- settings.vaultConsent?.version === VAULT_CONSENT_VERSION ? settings.vaultConsent : { acknowledgedAt: now().toISOString(), version: VAULT_CONSENT_VERSION }
31811
- ) : void 0;
31812
- }
31813
- if (values.modelJudgeConsent !== void 0) {
31814
- merged.modelJudgeConsent = values.modelJudgeConsent ? settings.modelJudgeConsent?.payloadVersion === MODEL_JUDGE_PAYLOAD_VERSION ? settings.modelJudgeConsent : {
31815
- acknowledgedAt: now().toISOString(),
31816
- payloadVersion: MODEL_JUDGE_PAYLOAD_VERSION
31817
- } : void 0;
31818
- }
31819
- return merged;
31820
- }
31821
-
31822
- // ../../packages/persistence/src/settings.ts
31823
- import { readFileSync as readFileSync5 } from "fs";
31824
- import { join as join8 } from "path";
31825
- var SETTINGS_FILENAME = "settings.json";
31826
- function readWorkspaceSettings(base = defaultDataDir()) {
31827
- return overlayManagedSettings(readUserSettings(base), readManagedSettings());
31828
- }
31829
- function readUserSettings(base) {
31830
- const record2 = readJson(join8(settingsDir(base), SETTINGS_FILENAME));
31831
- if (!record2) return defaultWorkspaceSettings();
31832
- try {
31833
- return WorkspaceSettings.parse(record2);
31834
- } catch {
31835
- return defaultWorkspaceSettings();
31836
- }
31837
- }
31838
- function readJson(file2) {
31839
- let text;
31840
- try {
31841
- text = readFileSync5(file2, "utf8");
31842
- } catch {
31843
- return null;
31844
- }
31845
- return parseJsonObject(text) ?? null;
31846
- }
31847
-
31848
32374
  // ../../packages/persistence/src/store-symlinks.ts
31849
32375
  import { existsSync as existsSync5, lstatSync as lstatSync3, readlinkSync, realpathSync, statSync as statSync4 } from "fs";
31850
- import { dirname as dirname2, join as join9, resolve } from "path";
32376
+ import { dirname as dirname3, join as join10, resolve } from "path";
31851
32377
 
31852
32378
  // ../../packages/persistence/src/vault/crypto.ts
31853
32379
  import {
@@ -31861,19 +32387,19 @@ import {
31861
32387
  // ../../packages/persistence/src/vault/key-provider.ts
31862
32388
  import { execFileSync } from "child_process";
31863
32389
  import { randomBytes as randomBytes2 } from "crypto";
31864
- import { chmodSync as chmodSync3, readFileSync as readFileSync6, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
31865
- import { join as join10 } from "path";
32390
+ import { chmodSync as chmodSync3, readFileSync as readFileSync7, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
32391
+ import { join as join11 } from "path";
31866
32392
 
31867
32393
  // ../../packages/persistence/src/vault/vault.ts
31868
32394
  import { randomBytes as randomBytes3, randomUUID as randomUUID12 } from "crypto";
31869
32395
 
31870
32396
  // ../../packages/persistence/src/warn-era-cap.ts
31871
32397
  import { existsSync as existsSync6, writeFileSync as writeFileSync4 } from "fs";
31872
- import { join as join11 } from "path";
32398
+ import { join as join12 } from "path";
31873
32399
  var MARKER = "warn-era-capped";
31874
32400
  function capWarnEraEnforcementOnce(db, policyMode, dataDir2) {
31875
32401
  if (policyMode !== "warn") return { capped: 0, skipped: "not-warn" };
31876
- const marker = join11(dataDir2, MARKER);
32402
+ const marker = join12(dataDir2, MARKER);
31877
32403
  if (existsSync6(marker)) return { capped: 0, skipped: "already-run" };
31878
32404
  const capped = db.policies.capCategoryActions();
31879
32405
  writeFileSync4(marker, `${new Date(Date.now()).toISOString()}
@@ -31933,7 +32459,7 @@ function resolveProvider() {
31933
32459
  function loadConfig(base = defaultDataDir(), resolveProviderFn = resolveProvider) {
31934
32460
  try {
31935
32461
  ensureLayoutDirSync(base);
31936
- const settingsFile = join12(settingsDir(base), "settings.json");
32462
+ const settingsFile = join13(settingsDir(base), "settings.json");
31937
32463
  if (existsSync7(settingsFile)) tightenFile(settingsFile);
31938
32464
  } catch {
31939
32465
  }
@@ -31957,9 +32483,9 @@ function resolveProviderSafe(resolveProviderFn) {
31957
32483
  }
31958
32484
 
31959
32485
  // ../../packages/plugin-sdk/src/config-inventory.ts
31960
- import { readdirSync as readdirSync2, readFileSync as readFileSync8, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
32486
+ import { readdirSync as readdirSync2, readFileSync as readFileSync9, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
31961
32487
  import { homedir as homedir2 } from "os";
31962
- import { basename as basename3, join as join14 } from "path";
32488
+ import { basename as basename3, join as join15 } from "path";
31963
32489
 
31964
32490
  // ../../packages/detections/src/egress/registry.ts
31965
32491
  var EXTRACTOR_VERSION = "1";
@@ -35003,8 +35529,8 @@ function scanText(text, ruleVersions) {
35003
35529
  }
35004
35530
 
35005
35531
  // ../../packages/plugin-sdk/src/repo.ts
35006
- import { existsSync as existsSync8, readFileSync as readFileSync7, statSync as statSync6 } from "fs";
35007
- import { basename as basename2, dirname as dirname3, isAbsolute, join as join13, sep as sep2 } from "path";
35532
+ import { existsSync as existsSync8, readFileSync as readFileSync8, statSync as statSync6 } from "fs";
35533
+ import { basename as basename2, dirname as dirname4, isAbsolute, join as join14, sep as sep2 } from "path";
35008
35534
  function resolveRepoIdentity(cwd) {
35009
35535
  try {
35010
35536
  const root = findGitRoot(cwd);
@@ -35026,36 +35552,36 @@ function resolveRepoIdentity(cwd) {
35026
35552
  function findGitRoot(start) {
35027
35553
  let dir = start;
35028
35554
  for (; ; ) {
35029
- if (existsSync8(join13(dir, ".git"))) return dir;
35030
- const parent = dirname3(dir);
35555
+ if (existsSync8(join14(dir, ".git"))) return dir;
35556
+ const parent = dirname4(dir);
35031
35557
  if (parent === dir) return void 0;
35032
35558
  dir = parent;
35033
35559
  }
35034
35560
  }
35035
35561
  function resolveGitContext(root) {
35036
- const dotGit = join13(root, ".git");
35562
+ const dotGit = join14(root, ".git");
35037
35563
  try {
35038
35564
  if (statSync6(dotGit).isDirectory()) {
35039
- return { configPath: join13(dotGit, "config"), headRoot: root };
35565
+ return { configPath: join14(dotGit, "config"), headRoot: root };
35040
35566
  }
35041
35567
  } catch {
35042
35568
  return void 0;
35043
35569
  }
35044
35570
  const target = /^gitdir:\s*(.+?)\s*$/m.exec(safeRead(dotGit) ?? "")?.[1];
35045
35571
  if (!target) return void 0;
35046
- const gitdir = isAbsolute(target) ? target : join13(root, target);
35047
- if (existsSync8(join13(gitdir, "config"))) {
35048
- return { configPath: join13(gitdir, "config"), headRoot: root };
35572
+ const gitdir = isAbsolute(target) ? target : join14(root, target);
35573
+ if (existsSync8(join14(gitdir, "config"))) {
35574
+ return { configPath: join14(gitdir, "config"), headRoot: root };
35049
35575
  }
35050
- const commonRaw = safeRead(join13(gitdir, "commondir"))?.trim();
35576
+ const commonRaw = safeRead(join14(gitdir, "commondir"))?.trim();
35051
35577
  if (!commonRaw) return void 0;
35052
- const commonGitDir = isAbsolute(commonRaw) ? commonRaw : join13(gitdir, commonRaw);
35053
- const headRoot = basename2(commonGitDir) === ".git" ? dirname3(commonGitDir) : root;
35054
- return { configPath: join13(commonGitDir, "config"), headRoot };
35578
+ const commonGitDir = isAbsolute(commonRaw) ? commonRaw : join14(gitdir, commonRaw);
35579
+ const headRoot = basename2(commonGitDir) === ".git" ? dirname4(commonGitDir) : root;
35580
+ return { configPath: join14(commonGitDir, "config"), headRoot };
35055
35581
  }
35056
35582
  function safeRead(path) {
35057
35583
  try {
35058
- return readFileSync7(path, "utf8");
35584
+ return readFileSync8(path, "utf8");
35059
35585
  } catch {
35060
35586
  return void 0;
35061
35587
  }
@@ -35102,8 +35628,8 @@ import { Worker } from "worker_threads";
35102
35628
 
35103
35629
  // ../../packages/plugin-sdk/src/ignore-layers.ts
35104
35630
  var import_ignore = __toESM(require_ignore(), 1);
35105
- import { readFileSync as readFileSync9 } from "fs";
35106
- import { join as join15 } from "path";
35631
+ import { readFileSync as readFileSync10 } from "fs";
35632
+ import { join as join16 } from "path";
35107
35633
 
35108
35634
  // ../../packages/plugin-sdk/src/inventory-resolver.ts
35109
35635
  import { arch, hostname as hostname4, platform, release } from "os";
@@ -35140,24 +35666,24 @@ import {
35140
35666
  fstatSync,
35141
35667
  mkdirSync as mkdirSync2,
35142
35668
  openSync as openSync2,
35143
- readFileSync as readFileSync10,
35669
+ readFileSync as readFileSync11,
35144
35670
  readSync,
35145
35671
  writeFileSync as writeFileSync5
35146
35672
  } from "fs";
35147
- import { join as join16 } from "path";
35673
+ import { join as join17 } from "path";
35148
35674
  var TAIL_BYTES = 256 * 1024;
35149
35675
 
35150
35676
  // ../../packages/plugin-sdk/src/nudge.ts
35151
- import { mkdirSync as mkdirSync3, readFileSync as readFileSync11, writeFileSync as writeFileSync6 } from "fs";
35152
- import { join as join17 } from "path";
35677
+ import { mkdirSync as mkdirSync3, readFileSync as readFileSync12, writeFileSync as writeFileSync6 } from "fs";
35678
+ import { join as join18 } from "path";
35153
35679
 
35154
35680
  // ../../packages/plugin-sdk/src/paths.ts
35155
35681
  import { readdirSync as readdirSync3, realpathSync as realpathSync3 } from "fs";
35156
- import { basename as basename4, dirname as dirname4, sep as sep3 } from "path";
35682
+ import { basename as basename4, dirname as dirname5, sep as sep3 } from "path";
35157
35683
 
35158
35684
  // ../../packages/plugin-sdk/src/project-files.ts
35159
35685
  import { existsSync as existsSync10, readdirSync as readdirSync4 } from "fs";
35160
- import { basename as basename5, join as join18 } from "path";
35686
+ import { basename as basename5, join as join19 } from "path";
35161
35687
 
35162
35688
  // ../../packages/plugin-sdk/src/provider-env-antigravity.ts
35163
35689
  var optionalBaseUrl2 = external_exports.preprocess((v) => {
@@ -35203,7 +35729,7 @@ var THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1e3;
35203
35729
 
35204
35730
  // ../../packages/plugin-sdk/src/throttle.ts
35205
35731
  import { mkdirSync as mkdirSync4, statSync as statSync8, writeFileSync as writeFileSync7 } from "fs";
35206
- import { join as join19 } from "path";
35732
+ import { join as join20 } from "path";
35207
35733
 
35208
35734
  // ../../packages/plugin-runtime/src/attached/egress-wire.ts
35209
35735
  import { createHash as createHash5 } from "crypto";
@@ -35242,6 +35768,307 @@ function toEgressIngestRequest(input2) {
35242
35768
  };
35243
35769
  }
35244
35770
 
35771
+ // ../../packages/remote/src/http.ts
35772
+ import { request as httpRequest } from "http";
35773
+ import { request as httpsRequest } from "https";
35774
+ var DEFAULT_TIMEOUT_MS = 1e4;
35775
+ var MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
35776
+ var RemoteRequestError = class extends Error {
35777
+ constructor(status) {
35778
+ super(`control-plane request failed with status ${String(status)}`);
35779
+ this.status = status;
35780
+ this.name = "RemoteRequestError";
35781
+ }
35782
+ status;
35783
+ };
35784
+ var RemoteRouteAbsent = class extends Error {
35785
+ constructor(route) {
35786
+ super(`control plane does not serve ${route}`);
35787
+ this.route = route;
35788
+ this.name = "RemoteRouteAbsent";
35789
+ }
35790
+ route;
35791
+ };
35792
+ var RemoteRequestInvalid = class extends Error {
35793
+ constructor(route, cause) {
35794
+ super(`refusing to send a malformed body to ${route}`);
35795
+ this.cause = cause;
35796
+ this.name = "RemoteRequestInvalid";
35797
+ }
35798
+ cause;
35799
+ };
35800
+ var RemoteResponseInvalid = class extends Error {
35801
+ constructor(route, detail) {
35802
+ super(`control plane answered ${route} with ${detail}`);
35803
+ this.name = "RemoteResponseInvalid";
35804
+ }
35805
+ };
35806
+ var RemoteTransportError = class extends Error {
35807
+ /**
35808
+ * The status the peer sent, when headers arrived and only the BODY was
35809
+ * refused.
35810
+ *
35811
+ * Undefined for the ordinary case this class was written for — no answer at
35812
+ * all. It exists because two paths reject after a status has already been
35813
+ * delivered: an oversized body and an aborted response. Discarding it there
35814
+ * reported a deployment answering 401 with a verbose body as a network
35815
+ * outage, which sends the reader to look at their network instead of their
35816
+ * credential.
35817
+ */
35818
+ constructor(reason, status) {
35819
+ super(`control-plane request did not complete: ${reason}`);
35820
+ this.status = status;
35821
+ this.name = "RemoteTransportError";
35822
+ }
35823
+ status;
35824
+ };
35825
+ async function send(options) {
35826
+ const url2 = new URL(options.url);
35827
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
35828
+ const send_ = url2.protocol === "http:" ? httpRequest : httpsRequest;
35829
+ const requestOptions = {
35830
+ method: options.method,
35831
+ headers: {
35832
+ // CALLER HEADERS FIRST, so this module's own are not overridable. Spread
35833
+ // last they win, and two of the values below are ones no caller may
35834
+ // replace: `x-api-key` is the credential, and `content-length` is the
35835
+ // byte count that stops a multi-byte body being truncated by the
35836
+ // receiver. `SendOptions.headers` is a free-form record on an exported
35837
+ // function, so "no caller does that today" is not the guarantee to rely
35838
+ // on. The one header any caller actually passes — `if-none-match` on the
35839
+ // conditional GET — is untouched by this order.
35840
+ ...options.headers,
35841
+ // The credential. One header, matching what the deployment authenticates
35842
+ // on; a second copy in an `Authorization` header would be one more place
35843
+ // it can be logged by an intermediary for no gain.
35844
+ //
35845
+ // Spread conditionally rather than assigned as `undefined`: Node's header
35846
+ // handling and `content-length` bookkeeping treat a present-but-undefined
35847
+ // key differently from an absent one, and "the header is not there" is
35848
+ // the property the attach flow needs.
35849
+ ...options.apiKey === void 0 ? {} : { "x-api-key": options.apiKey },
35850
+ accept: "application/json",
35851
+ ...options.body === void 0 ? {} : {
35852
+ "content-type": "application/json",
35853
+ // Byte length, not string length: a multi-byte body sent with a
35854
+ // character count is truncated by the receiver.
35855
+ "content-length": String(Buffer.byteLength(options.body))
35856
+ }
35857
+ }
35858
+ };
35859
+ return new Promise((resolve2, reject) => {
35860
+ let settled = false;
35861
+ const fail = (reason, status) => {
35862
+ if (settled) return;
35863
+ settled = true;
35864
+ reject(new RemoteTransportError(reason, status));
35865
+ };
35866
+ const req = send_(url2, requestOptions, (res) => {
35867
+ const chunks = [];
35868
+ let size = 0;
35869
+ res.on("data", (chunk) => {
35870
+ size += chunk.length;
35871
+ if (size > MAX_RESPONSE_BYTES) {
35872
+ fail(`response exceeded ${String(MAX_RESPONSE_BYTES)} bytes`, res.statusCode);
35873
+ res.destroy();
35874
+ req.destroy();
35875
+ return;
35876
+ }
35877
+ chunks.push(chunk);
35878
+ });
35879
+ res.on("aborted", () => {
35880
+ fail("the response was aborted", res.statusCode);
35881
+ });
35882
+ res.on("end", () => {
35883
+ if (settled) return;
35884
+ settled = true;
35885
+ resolve2({
35886
+ status: res.statusCode ?? 0,
35887
+ headers: res.headers,
35888
+ body: Buffer.concat(chunks).toString("utf8")
35889
+ });
35890
+ });
35891
+ });
35892
+ const deadline = setTimeout(() => {
35893
+ fail(`no response within ${String(timeoutMs)}ms`);
35894
+ req.destroy();
35895
+ }, timeoutMs);
35896
+ deadline.unref();
35897
+ req.on("upgrade", (_res, socket) => {
35898
+ fail("the deployment answered with a protocol upgrade");
35899
+ socket.destroy();
35900
+ });
35901
+ req.on("close", () => {
35902
+ fail("the connection closed before a response was read");
35903
+ clearTimeout(deadline);
35904
+ });
35905
+ req.on("error", (err) => {
35906
+ fail(err.message);
35907
+ });
35908
+ if (options.body !== void 0) req.write(options.body);
35909
+ req.end();
35910
+ });
35911
+ }
35912
+
35913
+ // ../../packages/remote/src/client.ts
35914
+ var ROUTES = {
35915
+ events: "/v1/events",
35916
+ auditEvents: "/v1/audit-events",
35917
+ auditEventsBatch: "/v1/audit-events/batch",
35918
+ inventory: "/v1/inventory",
35919
+ storePosture: "/v1/store-posture",
35920
+ policyBundle: "/v1/policy-bundle",
35921
+ whoami: "/v1/plugin/whoami",
35922
+ shares: "/v1/shares",
35923
+ commands: "/v1/plugin/commands"
35924
+ };
35925
+ function ackRoute(id) {
35926
+ return `${ROUTES.commands}/${encodeURIComponent(id)}/ack`;
35927
+ }
35928
+ function headerValue(response, name) {
35929
+ const raw = response.headers[name];
35930
+ if (raw === void 0) return void 0;
35931
+ return Array.isArray(raw) ? raw[0] : raw;
35932
+ }
35933
+ function okBody(response) {
35934
+ if (response.status < 200 || response.status >= 300) {
35935
+ throw new RemoteRequestError(response.status);
35936
+ }
35937
+ return response.body;
35938
+ }
35939
+ function parsed(schema, body, route) {
35940
+ let json2;
35941
+ try {
35942
+ json2 = JSON.parse(body);
35943
+ } catch {
35944
+ throw new RemoteResponseInvalid(route, "a body that is not JSON");
35945
+ }
35946
+ const result = schema.safeParse(json2);
35947
+ if (!result.success) {
35948
+ throw new RemoteResponseInvalid(route, "a body this client cannot read");
35949
+ }
35950
+ return result.data;
35951
+ }
35952
+ function withoutTrailingSlashes(endpoint) {
35953
+ let end = endpoint.length;
35954
+ while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH) end -= 1;
35955
+ return endpoint.slice(0, end);
35956
+ }
35957
+ var SLASH = "/".charCodeAt(0);
35958
+ function createRemoteClient(options) {
35959
+ const base = withoutTrailingSlashes(options.endpoint);
35960
+ const url2 = (route) => `${base}${route}`;
35961
+ const common = { apiKey: options.apiKey, timeoutMs: options.timeoutMs };
35962
+ const sendOne = async (event) => {
35963
+ const validated = RecordAuditEventRequest.safeParse(event);
35964
+ if (!validated.success) throw new RemoteRequestInvalid(ROUTES.auditEvents, validated.error);
35965
+ const response = await send({
35966
+ ...common,
35967
+ method: "POST",
35968
+ url: url2(ROUTES.auditEvents),
35969
+ body: JSON.stringify(validated.data)
35970
+ });
35971
+ okBody(response);
35972
+ };
35973
+ return {
35974
+ async ingestEvents(batch) {
35975
+ const response = await send({
35976
+ ...common,
35977
+ method: "POST",
35978
+ url: url2(ROUTES.events),
35979
+ body: JSON.stringify(batch)
35980
+ });
35981
+ return parsed(IngestAck, okBody(response), ROUTES.events);
35982
+ },
35983
+ async ingestInventory(context) {
35984
+ const response = await send({
35985
+ ...common,
35986
+ method: "POST",
35987
+ url: url2(ROUTES.inventory),
35988
+ body: JSON.stringify(context)
35989
+ });
35990
+ return parsed(ResolvedInventory, okBody(response), ROUTES.inventory);
35991
+ },
35992
+ async recordAuditEvent(event) {
35993
+ await sendOne(event);
35994
+ },
35995
+ async recordAuditEvents(events, opts) {
35996
+ const validated = RecordAuditEventBatch.safeParse({ events });
35997
+ if (!validated.success) {
35998
+ throw new RemoteRequestInvalid(ROUTES.auditEventsBatch, validated.error);
35999
+ }
36000
+ const response = await send({
36001
+ ...common,
36002
+ method: "POST",
36003
+ url: url2(ROUTES.auditEventsBatch),
36004
+ body: JSON.stringify(validated.data)
36005
+ });
36006
+ if (response.status === 404) {
36007
+ if (opts?.fallbackToSingleEvents !== true) {
36008
+ throw new RemoteRouteAbsent(ROUTES.auditEventsBatch);
36009
+ }
36010
+ for (const event of validated.data.events) await sendOne(event);
36011
+ return { accepted: validated.data.events.length };
36012
+ }
36013
+ return parsed(AuditEventBatchAck, okBody(response), ROUTES.auditEventsBatch);
36014
+ },
36015
+ async reportStorePosture(snapshot) {
36016
+ const response = await send({
36017
+ ...common,
36018
+ method: "POST",
36019
+ url: url2(ROUTES.storePosture),
36020
+ body: JSON.stringify(snapshot)
36021
+ });
36022
+ okBody(response);
36023
+ },
36024
+ async getPolicyBundle(etag) {
36025
+ const response = await send({
36026
+ ...common,
36027
+ method: "GET",
36028
+ url: url2(ROUTES.policyBundle),
36029
+ ...etag === void 0 ? {} : { headers: { "if-none-match": etag } }
36030
+ });
36031
+ if (response.status === 304) {
36032
+ return { changed: false, etag: headerValue(response, "etag") ?? etag };
36033
+ }
36034
+ const bundle = parsed(PolicyBundle, okBody(response), ROUTES.policyBundle);
36035
+ return { changed: true, bundle, etag: headerValue(response, "etag") };
36036
+ },
36037
+ async whoami() {
36038
+ const response = await send({ ...common, method: "GET", url: url2(ROUTES.whoami) });
36039
+ return parsed(PluginWhoami, okBody(response), ROUTES.whoami);
36040
+ },
36041
+ async recordProjectEgress(request) {
36042
+ const validated = EgressIngestRequest.safeParse(request);
36043
+ if (!validated.success) throw new RemoteRequestInvalid(ROUTES.shares, validated.error);
36044
+ const response = await send({
36045
+ ...common,
36046
+ method: "POST",
36047
+ url: url2(ROUTES.shares),
36048
+ body: JSON.stringify(validated.data)
36049
+ });
36050
+ okBody(response);
36051
+ },
36052
+ async pollCommand() {
36053
+ const response = await send({ ...common, method: "GET", url: url2(ROUTES.commands) });
36054
+ if (response.status === 404) return null;
36055
+ return parsed(DeviceCommandPollResponse, okBody(response), ROUTES.commands).command;
36056
+ },
36057
+ async ackCommand(id, body) {
36058
+ const validated = DeviceCommandAckBody.safeParse(body);
36059
+ const route = ackRoute(id);
36060
+ if (!validated.success) throw new RemoteRequestInvalid(route, validated.error);
36061
+ const response = await send({
36062
+ ...common,
36063
+ method: "POST",
36064
+ url: url2(route),
36065
+ body: JSON.stringify(validated.data)
36066
+ });
36067
+ okBody(response);
36068
+ }
36069
+ };
36070
+ }
36071
+
35245
36072
  // ../../packages/plugin-runtime/src/attached/failure.ts
35246
36073
  function statusOf(err) {
35247
36074
  if (typeof err !== "object" || err === null || !("status" in err)) return null;
@@ -35260,12 +36087,27 @@ function classifyFailure(err) {
35260
36087
  }
35261
36088
  }
35262
36089
 
36090
+ // ../../packages/plugin-runtime/src/attached/with-timeout.ts
36091
+ var REQUEST_TIMEOUT_MS = 2e3;
36092
+ function withTimeout(promise2, ms) {
36093
+ let timer;
36094
+ const timeout = new Promise((_, reject) => {
36095
+ timer = setTimeout(() => {
36096
+ reject(new Error("attached gateway request timed out"));
36097
+ }, ms);
36098
+ });
36099
+ promise2.catch(() => void 0);
36100
+ return Promise.race([promise2, timeout]).finally(() => {
36101
+ clearTimeout(timer);
36102
+ });
36103
+ }
36104
+
35263
36105
  // ../../packages/plugin-runtime/src/attached/forward-drops.ts
35264
- import { readFileSync as readFileSync12 } from "fs";
35265
- import { join as join20 } from "path";
36106
+ import { readFileSync as readFileSync13 } from "fs";
36107
+ import { join as join21 } from "path";
35266
36108
  var FORWARD_DROPS_FILENAME = ATTACHED_FORWARD_DROPS_FILENAME;
35267
36109
  function forwardDropsPath(dataDir2) {
35268
- return join20(dataDir2, FORWARD_DROPS_FILENAME);
36110
+ return join21(dataDir2, FORWARD_DROPS_FILENAME);
35269
36111
  }
35270
36112
  function recordForwardDrops(dataDir2, count, nowMs) {
35271
36113
  if (count <= 0) return;
@@ -35283,7 +36125,7 @@ function recordForwardDrops(dataDir2, count, nowMs) {
35283
36125
  }
35284
36126
  function readForwardDrops(dataDir2) {
35285
36127
  try {
35286
- const parsed2 = JSON.parse(readFileSync12(forwardDropsPath(dataDir2), "utf8"));
36128
+ const parsed2 = JSON.parse(readFileSync13(forwardDropsPath(dataDir2), "utf8"));
35287
36129
  if (typeof parsed2 !== "object" || parsed2 === null) return null;
35288
36130
  const record2 = parsed2;
35289
36131
  if (typeof record2.droppedForwards !== "number" || !Number.isFinite(record2.droppedForwards)) {
@@ -35301,29 +36143,19 @@ function readForwardDrops(dataDir2) {
35301
36143
 
35302
36144
  // ../../packages/plugin-runtime/src/attached/forward-policy.ts
35303
36145
  import { randomUUID as randomUUID15 } from "crypto";
35304
- import { readFileSync as readFileSync13 } from "fs";
36146
+ import { readFileSync as readFileSync14 } from "fs";
35305
36147
  import { readFile, rename, writeFile } from "fs/promises";
35306
- import { join as join21 } from "path";
35307
-
35308
- // ../../packages/plugin-runtime/src/attached/with-timeout.ts
35309
- var REQUEST_TIMEOUT_MS = 2e3;
35310
- function withTimeout(promise2, ms) {
35311
- let timer;
35312
- const timeout = new Promise((_, reject) => {
35313
- timer = setTimeout(() => {
35314
- reject(new Error("attached gateway request timed out"));
35315
- }, ms);
35316
- });
35317
- promise2.catch(() => void 0);
35318
- return Promise.race([promise2, timeout]).finally(() => {
35319
- clearTimeout(timer);
35320
- });
35321
- }
35322
-
35323
- // ../../packages/plugin-runtime/src/attached/forward-policy.ts
36148
+ import { join as join22 } from "path";
35324
36149
  function isInvalidRequest(err) {
35325
36150
  return typeof err === "object" && err !== null && err.name === "RemoteRequestInvalid";
35326
36151
  }
36152
+ function isRouteAbsent(err) {
36153
+ return typeof err === "object" && err !== null && err.name === "RemoteRouteAbsent";
36154
+ }
36155
+ function isServerRejection(err) {
36156
+ const status = statusOf(err);
36157
+ return status !== null && status >= 400 && status <= 499 && status !== 401 && status !== 403 && status !== 404 && status !== 429;
36158
+ }
35327
36159
  var FORWARD_BUDGET_MS = 1500;
35328
36160
  var DECISION_PATH_BUDGET_MS = 800;
35329
36161
  var BREAKER_FAILURE_THRESHOLD = 3;
@@ -35351,7 +36183,7 @@ function parseBreakerState(raw, nowMs) {
35351
36183
  }
35352
36184
  function createForwardPolicy(deps) {
35353
36185
  const now = deps.now ?? (() => Date.now());
35354
- const file2 = join21(deps.dir, STATE_FILENAME);
36186
+ const file2 = join22(deps.dir, STATE_FILENAME);
35355
36187
  let state = null;
35356
36188
  let loading = null;
35357
36189
  async function readState() {
@@ -35391,6 +36223,20 @@ function createForwardPolicy(deps) {
35391
36223
  } catch {
35392
36224
  current = { ...CLOSED };
35393
36225
  }
36226
+ const restoreOpenedAtMs = (openedAtMs) => persist({
36227
+ consecutiveFailures: current.consecutiveFailures,
36228
+ openedAtMs,
36229
+ lastFailure: current.lastFailure
36230
+ });
36231
+ const recordFailure = (cause) => {
36232
+ const failures = current.consecutiveFailures + 1;
36233
+ const shouldOpen = current.openedAtMs !== null || failures >= BREAKER_FAILURE_THRESHOLD;
36234
+ return persist({
36235
+ consecutiveFailures: failures,
36236
+ openedAtMs: shouldOpen ? now() : null,
36237
+ lastFailure: cause
36238
+ });
36239
+ };
35394
36240
  const at = now();
35395
36241
  if (current.openedAtMs !== null) {
35396
36242
  if (at - current.openedAtMs < BREAKER_COOLDOWN_MS) {
@@ -35409,15 +36255,20 @@ function createForwardPolicy(deps) {
35409
36255
  }
35410
36256
  return { ok: true, value };
35411
36257
  } catch (err) {
35412
- if (isInvalidRequest(err)) return { ok: false, reason: "invalid-request" };
36258
+ if (isInvalidRequest(err)) {
36259
+ if (current.openedAtMs !== null) await restoreOpenedAtMs(current.openedAtMs);
36260
+ return { ok: false, reason: "invalid-request" };
36261
+ }
36262
+ if (isRouteAbsent(err)) {
36263
+ if (current.openedAtMs !== null) await restoreOpenedAtMs(null);
36264
+ return { ok: false, reason: "route-absent" };
36265
+ }
36266
+ if (isServerRejection(err)) {
36267
+ await recordFailure("unreachable");
36268
+ return { ok: false, reason: "rejected" };
36269
+ }
35413
36270
  const reason = classifyFailure(err);
35414
- const failures = current.consecutiveFailures + 1;
35415
- const shouldOpen = current.openedAtMs !== null || failures >= BREAKER_FAILURE_THRESHOLD;
35416
- await persist({
35417
- consecutiveFailures: failures,
35418
- openedAtMs: shouldOpen ? now() : null,
35419
- lastFailure: reason
35420
- });
36271
+ await recordFailure(reason);
35421
36272
  return { ok: false, reason };
35422
36273
  }
35423
36274
  }
@@ -35425,13 +36276,11 @@ function createForwardPolicy(deps) {
35425
36276
  }
35426
36277
 
35427
36278
  // ../../packages/plugin-runtime/src/attached/gateway.ts
35428
- var ACTION_STRENGTH = {
35429
- allow: 0,
35430
- log: 1,
35431
- warn: 2,
35432
- redact: 3,
35433
- block: 4
35434
- };
36279
+ function strongerOf(a, b) {
36280
+ if (a === null) return b;
36281
+ if (b === null) return a;
36282
+ return strongerAction(a, b);
36283
+ }
35435
36284
  function ruleCategoryMap(wireRules, localRules) {
35436
36285
  const map2 = /* @__PURE__ */ new Map();
35437
36286
  for (const rule of wireRules ?? []) map2.set(rule.id, rule.category);
@@ -35441,11 +36290,6 @@ function ruleCategoryMap(wireRules, localRules) {
35441
36290
  }
35442
36291
  return map2;
35443
36292
  }
35444
- function strongerOf(a, b) {
35445
- if (a === null) return b;
35446
- if (b === null) return a;
35447
- return ACTION_STRENGTH[a] >= ACTION_STRENGTH[b] ? a : b;
35448
- }
35449
36293
  function policyKey(policy) {
35450
36294
  return "ruleId" in policy.target ? `rule:${policy.target.ruleId}` : `category:${policy.target.category}`;
35451
36295
  }
@@ -35464,7 +36308,7 @@ function mergeRaiseOnly(localPolicies, remotePolicies, categoryByRuleId) {
35464
36308
  const floor = floorFor(policy, categoryByRuleId);
35465
36309
  remoteCategoryAction.set(
35466
36310
  policy.target.category,
35467
- floor !== null && ACTION_STRENGTH[policy.action] < ACTION_STRENGTH[floor] ? floor : policy.action
36311
+ floor !== null && !isActionAtLeast(policy.action, floor) ? floor : policy.action
35468
36312
  );
35469
36313
  }
35470
36314
  for (const policy of localPolicies) {
@@ -35481,7 +36325,7 @@ function mergeRaiseOnly(localPolicies, remotePolicies, categoryByRuleId) {
35481
36325
  }
35482
36326
  merged.set(
35483
36327
  key,
35484
- remoteFloor !== null && ACTION_STRENGTH[policy.action] < ACTION_STRENGTH[remoteFloor] ? { ...policy, action: remoteFloor } : policy
36328
+ remoteFloor !== null && !isActionAtLeast(policy.action, remoteFloor) ? { ...policy, action: remoteFloor } : policy
35485
36329
  );
35486
36330
  }
35487
36331
  const localCategoryAction = /* @__PURE__ */ new Map();
@@ -35501,13 +36345,13 @@ function mergeRaiseOnly(localPolicies, remotePolicies, categoryByRuleId) {
35501
36345
  if (category !== void 0) localFloor = localCategoryAction.get(category) ?? null;
35502
36346
  }
35503
36347
  const effectiveFloor = strongerOf(floor, localFloor);
35504
- const clamped = effectiveFloor !== null && ACTION_STRENGTH[policy.action] < ACTION_STRENGTH[effectiveFloor] ? { ...policy, action: effectiveFloor } : policy;
36348
+ const clamped = effectiveFloor !== null && !isActionAtLeast(policy.action, effectiveFloor) ? { ...policy, action: effectiveFloor } : policy;
35505
36349
  const existing = merged.get(key);
35506
36350
  if (existing === void 0) {
35507
36351
  merged.set(key, clamped);
35508
36352
  continue;
35509
36353
  }
35510
- if (ACTION_STRENGTH[clamped.action] > ACTION_STRENGTH[existing.action]) {
36354
+ if (actionRank(clamped.action) > actionRank(existing.action)) {
35511
36355
  merged.set(key, clamped);
35512
36356
  }
35513
36357
  }
@@ -35540,6 +36384,8 @@ var AttachedDataGateway = class {
35540
36384
  );
35541
36385
  if (forwarded.ok && forwarded.value.accepted + forwarded.value.duplicates > 0) {
35542
36386
  this.deps.local.markCaptureDelivered(record2.event, Date.now());
36387
+ } else {
36388
+ this.deps.local.markCaptureOwed(record2.event);
35543
36389
  }
35544
36390
  }
35545
36391
  async ensureInventory(ctx) {
@@ -35576,9 +36422,10 @@ var AttachedDataGateway = class {
35576
36422
  // a retried tool_call, exactly this path — can never stomp a populated row.
35577
36423
  async recordAuditEvent(event) {
35578
36424
  await this.deps.local.recordAuditEvent(event);
35579
- await this.deps.forward.run(
36425
+ const forwarded = await this.deps.forward.run(
35580
36426
  () => this.deps.client.recordAuditEvent(reKeyForForward(event, this.remoteInventory))
35581
36427
  );
36428
+ if (forwarded.ok) this.deps.local.markAuditEventsDelivered([event], Date.now());
35582
36429
  }
35583
36430
  // Attached `llm_call` is written locally by the inner gateway, then routed to
35584
36431
  // the control plane through the existing `recordAuditEvent` ingest (no dedicated
@@ -35587,44 +36434,170 @@ var AttachedDataGateway = class {
35587
36434
  // which would write the event to the local store a second time.
35588
36435
  async recordLlmCall(input2) {
35589
36436
  await this.deps.local.recordLlmCall(input2);
35590
- await this.deps.forward.run(
35591
- () => this.deps.client.recordAuditEvent(
35592
- reKeyForForward(llmAuditEvent(input2), this.remoteInventory)
35593
- )
36437
+ const event = llmAuditEvent(input2);
36438
+ const forwarded = await this.deps.forward.run(
36439
+ () => this.deps.client.recordAuditEvent(reKeyForForward(event, this.remoteInventory))
35594
36440
  );
36441
+ if (forwarded.ok) this.deps.local.markAuditEventsDelivered([event], Date.now());
35595
36442
  }
35596
36443
  /**
35597
- * Forward one batch, item by item, under ONE aggregate deadline.
36444
+ * Forward one batch in CHUNKS of AUDIT_EVENT_BATCH_MAX, under ONE aggregate deadline.
36445
+ *
36446
+ * This used to send one HTTP request per event, which is what made the batch
36447
+ * budget bite: at 200ms round-trip a 3s budget admitted ~15 events and threw
36448
+ * away everything after them. The same rows now cross 50 at a time over
36449
+ * `POST /v1/audit-events/batch` — the route the attach-time drain has always
36450
+ * used — so the same budget admits ~750. The wire cap is the server's own
36451
+ * constant, sized against server cost, and the client REFUSES a longer array
36452
+ * client-side, so the chunking here is not a convention.
35598
36453
  *
35599
- * Per-item budgets bound each request and nothing bounded their sum — see
35600
- * BATCH_FORWARD_BUDGET_MS. When the deadline passes the remainder is dropped
35601
- * rather than sent: the local write has already succeeded, so every caller
35602
- * has a correct result to return, and a drop is the outcome this path is
35603
- * built to accept (G8) where a blown hook timeout is not.
36454
+ * Still serial, and still for the original reason: firing N requests at once
36455
+ * would trade a latency problem for a burst the plane's per-key rate limiting
36456
+ * answers with the refusals the breaker then counts. Fewer, fuller requests is
36457
+ * the fix; more concurrent ones is not.
35604
36458
  *
35605
- * Serial rather than concurrent on purpose. Firing N requests at once would
35606
- * trade a latency problem for a burst the plane's own per-key rate limiting
35607
- * would answer with the refusals the breaker then counts.
36459
+ * When the deadline passes the remainder is dropped rather than sent: the
36460
+ * local write has already succeeded, so every caller has a correct result to
36461
+ * return. What is dropped is COUNTED, everywhere it can happen — this path
36462
+ * returns BEFORE `ForwardPolicy.run` is reached, so without the tally in
36463
+ * `forward-drops.ts` a slow-but-answering plane produces no failures, keeps
36464
+ * the breaker closed, renders a healthy block, and discards the tail of every
36465
+ * batch indefinitely. The SAME tally also covers a single that fails inside
36466
+ * the per-item retry below — the breaker opening mid-retry is a failure the
36467
+ * breaker's own state DOES capture, but the events still in this chunk once
36468
+ * that happens are neither delivered nor otherwise counted anywhere, which is
36469
+ * the same invisibility with a different cause.
35608
36470
  *
35609
- * WHAT IS DROPPED IS COUNTED. Every other forward failure ends in
35610
- * `ForwardPolicy.run`'s catch and moves the breaker's file, which is what
35611
- * lets status call the forward unhealthy; this path returns BEFORE `run` is
35612
- * reached, so without the tally in `forward-drops.ts` a slow-but-answering
35613
- * plane produces no failures, keeps the breaker closed, renders a healthy
35614
- * block, and discards the tail of every batch indefinitely.
36471
+ * `ok` ALONE IS NOT DELIVERY, the same rule `recordCapture` states for the
36472
+ * single-event ack and at fifty times the blast radius here:
36473
+ * `AuditEventBatchAck.accepted` is an aggregate count the wire contract does
36474
+ * not tie to the chunk's own length, so a 2xx answering `{accepted: 30}` for
36475
+ * fifty events is well-formed. Trusting `ok` alone would stamp all fifty as
36476
+ * delivered and never re-offer the twenty the plane did not take. So success
36477
+ * is checked against `chunk.length`; anything short of it falls into the same
36478
+ * per-item pass as a refused chunk, which is the only way to recover the
36479
+ * rows that did not land, since the ack carries no per-row verdict to
36480
+ * resend by.
36481
+ *
36482
+ * That fallback ASSUMES a re-send of an already-landed row is a harmless
36483
+ * no-op rather than a second cost — an assumption this file cannot verify.
36484
+ * `AuditEventBatchAck` carries only `accepted`, unlike its sibling
36485
+ * `IngestAck` (`accepted` + `duplicates`, with `accepted + duplicates ==`
36486
+ * the batch size as the invariant `recordCapture` reads), so whether a
36487
+ * duplicate counts toward THIS route's `accepted` is not expressed
36488
+ * anywhere in this repo. If it follows its sibling's convention and does
36489
+ * NOT, a chunk containing even one already-delivered row — the ordinary
36490
+ * consequence of a lost stamp, which this file already treats as cheap —
36491
+ * answers short forever and enters the per-item pass on every pass it is
36492
+ * offered again. The cost of that is bounded rather than silent: the
36493
+ * pass converges (every row lands and stamps), so it is one wasted round
36494
+ * of singles rather than a stall, and it errs toward an extra resend
36495
+ * rather than toward the lost row the alternative risks.
36496
+ *
36497
+ * BATCH-ATOMIC SETTLEMENT is otherwise the rule: the receiver wraps a chunk in
36498
+ * one transaction, so a full 2xx settles every event in it and a non-2xx
36499
+ * settles none — which is why the whole chunk is stamped together on a FULL
36500
+ * accept and none of it otherwise. THREE reasons do not deserve whole-chunk
36501
+ * treatment, alongside a short accept, and all are re-sent one event at a
36502
+ * time:
36503
+ *
36504
+ * `invalid-request` a chunk the client refused to send at all. One malformed
36505
+ * event would otherwise cost the 49 good ones beside it —
36506
+ * a new way to lose data introduced by the very change
36507
+ * meant to stop losing it.
36508
+ * `route-absent` a deployment that predates the batch route. The
36509
+ * single-event route is the one it serves, and re-sending
36510
+ * here rather than inside the client is what gives each
36511
+ * request its own budget instead of 50 inside one.
36512
+ * `rejected` the deployment's SERVER-side twin of `invalid-request` —
36513
+ * a 4xx body refusal from schema drift on the other side
36514
+ * of the wire. Settlement is batch-atomic on this reason
36515
+ * exactly as on the others, so leaving it out would cost
36516
+ * the whole chunk for one event the DEPLOYMENT considers
36517
+ * malformed, where the per-item form cost only that one.
36518
+ *
36519
+ * Every other reason (breaker-open, a refusal, a timeout) applies to the whole
36520
+ * chunk, and re-sending it item by item would just spend the budget failing 50
36521
+ * more times — for those, the blast radius stays exactly what it was before
36522
+ * batching.
35615
36523
  */
35616
36524
  async forwardBatch(inputs, toEvent) {
35617
36525
  const deadline = Date.now() + BATCH_FORWARD_BUDGET_MS;
35618
- for (let i = 0; i < inputs.length; i += 1) {
35619
- const now = Date.now();
35620
- if (now >= deadline) {
35621
- recordForwardDrops(this.deps.dataDir, inputs.length - i, now);
35622
- return;
36526
+ const delivered = [];
36527
+ try {
36528
+ for (let i = 0; i < inputs.length; i += AUDIT_EVENT_BATCH_MAX) {
36529
+ const now = Date.now();
36530
+ if (now >= deadline) {
36531
+ recordForwardDrops(this.deps.dataDir, inputs.length - i, now);
36532
+ return;
36533
+ }
36534
+ const chunk = inputs.slice(i, i + AUDIT_EVENT_BATCH_MAX).map((input2) => toEvent(input2));
36535
+ const forwarded = await this.deps.forward.run(
36536
+ () => this.deps.client.recordAuditEvents(
36537
+ chunk.map((event) => reKeyForForward(event, this.remoteInventory))
36538
+ )
36539
+ );
36540
+ if (forwarded.ok) {
36541
+ if (forwarded.value.accepted === chunk.length) {
36542
+ delivered.push(...chunk);
36543
+ continue;
36544
+ }
36545
+ } else if (
36546
+ // THREE reasons are worth a second pass, one at a time, and they are
36547
+ // the three settled BEFORE the control plane refused anything, or
36548
+ // (for `rejected`) refused the BODY rather than the connection.
36549
+ //
36550
+ // `invalid-request` — the CLIENT refused the body before any request
36551
+ // went out: a defect in one event, not an outage. Re-sending singly
36552
+ // isolates the bad one instead of charging its 49 neighbours for it.
36553
+ //
36554
+ // `route-absent` — the deployment predates the batch route and serves
36555
+ // only the single-event one. The retry IS the compatibility path, and
36556
+ // it has to live HERE rather than inside the client: each single gets
36557
+ // its own FORWARD_BUDGET_MS through `run`, whereas the client's own
36558
+ // fallback would spend 50 sequential round trips inside the ONE
36559
+ // budget wrapping this call — turning a working older deployment into
36560
+ // a timeout, three of those into an open breaker, and every row into
36561
+ // a silent drop while the status surface called an answering
36562
+ // deployment down.
36563
+ //
36564
+ // `rejected` — the deployment's own 4xx refusal of the body, the
36565
+ // server-side twin of `invalid-request`: isolating it the same way
36566
+ // costs one event instead of the whole chunk for a defect the
36567
+ // deployment considers local to one row.
36568
+ //
36569
+ // Every other reason (breaker-open, a refusal, a timeout) applies to
36570
+ // the whole chunk; re-sending it item by item would just spend the
36571
+ // budget failing 50 more times.
36572
+ forwarded.reason !== "invalid-request" && forwarded.reason !== "route-absent" && forwarded.reason !== "rejected"
36573
+ ) {
36574
+ continue;
36575
+ }
36576
+ for (const [j, event] of chunk.entries()) {
36577
+ const at = Date.now();
36578
+ if (at >= deadline) {
36579
+ recordForwardDrops(this.deps.dataDir, inputs.length - i - j, at);
36580
+ return;
36581
+ }
36582
+ const single = await this.deps.forward.run(
36583
+ () => this.deps.client.recordAuditEvent(reKeyForForward(event, this.remoteInventory))
36584
+ );
36585
+ if (single.ok) {
36586
+ delivered.push(event);
36587
+ continue;
36588
+ }
36589
+ if (single.reason === "breaker-open") {
36590
+ recordForwardDrops(this.deps.dataDir, inputs.length - i - j, at);
36591
+ return;
36592
+ }
36593
+ recordForwardDrops(this.deps.dataDir, 1, at);
36594
+ }
36595
+ }
36596
+ } finally {
36597
+ try {
36598
+ this.deps.local.markAuditEventsDelivered(delivered, Date.now());
36599
+ } catch {
35623
36600
  }
35624
- const input2 = inputs[i];
35625
- await this.deps.forward.run(
35626
- () => this.deps.client.recordAuditEvent(reKeyForForward(toEvent(input2), this.remoteInventory))
35627
- );
35628
36601
  }
35629
36602
  }
35630
36603
  // Delegated as a BATCH rather than looped over recordLlmCall: the inner
@@ -35667,9 +36640,10 @@ var AttachedDataGateway = class {
35667
36640
  // local store.
35668
36641
  async recordConfigScan(record2) {
35669
36642
  await this.deps.local.recordConfigScan(record2);
35670
- await this.deps.forward.run(
36643
+ const forwarded = await this.deps.forward.run(
35671
36644
  () => this.deps.client.recordAuditEvent(reKeyForForward(record2.scanEvent, this.remoteInventory))
35672
36645
  );
36646
+ if (forwarded.ok) this.deps.local.markAuditEventsDelivered([record2.scanEvent], Date.now());
35673
36647
  }
35674
36648
  async recordBlockedDetection(entry) {
35675
36649
  return this.deps.local.recordBlockedDetection(entry);
@@ -35803,6 +36777,18 @@ var AttachedDataGateway = class {
35803
36777
  // exactly what it did, leaving the whole control inert on every device
35804
36778
  // while every test around it stayed green.
35805
36779
  prohibitedModels: cached2.prohibitedModels
36780
+ // ALSO HONOURED FROM THE CACHE, and not a bundle field at all: each
36781
+ // merged policy's own `provenance`. `mergeRaiseOnly` spreads the policies
36782
+ // it emits, so an 'authored' policy arriving from the control plane
36783
+ // keeps that marker even where the clamp rebuilds it with a stronger
36784
+ // action. The device reads it in exactly one direction — the rules such a
36785
+ // policy targets are not locally re-assignable — so it sits on the
36786
+ // `prohibitedModels` side of the line for the same reason that field
36787
+ // does: it can only ever ADD a refusal, never relax one, and an unsigned
36788
+ // cache therefore has no relaxation to grant by carrying it. Dropping it
36789
+ // would be the silent failure rather than the safe one — the action would
36790
+ // still be enforced while the local override the organization authored
36791
+ // away quietly came back.
35806
36792
  // `rulesComplete` is a STANDALONE-ONLY signal (the user's local installed
35807
36793
  // snapshot) and is taken from the LOCAL bundle only — never from the wire
35808
36794
  // or the on-disk cache. Honoring a cached one would hand the control plane, or
@@ -35842,10 +36828,10 @@ var AttachedDataGateway = class {
35842
36828
  //
35843
36829
  // Implementing these is what actually closes the skipped-local-maintenance
35844
36830
  // gap: the OSS structural guard `hasLocalStoreMaintenance()` is satisfied by
35845
- // any object carrying all five, so the composite qualifies and SessionStart
36831
+ // any object carrying them all, so the composite qualifies and SessionStart
35846
36832
  // runs maintenance on the device's real store.
35847
36833
  //
35848
- // ⚠ Three of the six are SYNCHRONOUS and must stay that way. `handle-session-start`
36834
+ // ⚠ Several of them are SYNCHRONOUS and must stay that way. `handle-session-start`
35849
36835
  // calls `capWarnEraEnforcement` without `await` and uses `staleBinaryNotice`'s
35850
36836
  // return value directly; declaring them `async` here would hand those call
35851
36837
  // sites a Promise and silently break both.
@@ -35868,9 +36854,15 @@ var AttachedDataGateway = class {
35868
36854
  // Delegated like the rest, and SYNCHRONOUS for the reason the note above
35869
36855
  // gives: `recordCapture` calls it after the forward has already settled, on a
35870
36856
  // path that has nothing left to await.
36857
+ markCaptureOwed(event) {
36858
+ this.deps.local.markCaptureOwed(event);
36859
+ }
35871
36860
  markCaptureDelivered(event, atMs) {
35872
36861
  this.deps.local.markCaptureDelivered(event, atMs);
35873
36862
  }
36863
+ markAuditEventsDelivered(events, atMs) {
36864
+ this.deps.local.markAuditEventsDelivered(events, atMs);
36865
+ }
35874
36866
  };
35875
36867
  function reKeyForForward(event, remote) {
35876
36868
  if (remote === null) {
@@ -35913,281 +36905,17 @@ function toolAuditEvent(input2) {
35913
36905
  }
35914
36906
 
35915
36907
  // ../../packages/plugin-runtime/src/attached/history-state.ts
35916
- import { readFileSync as readFileSync14 } from "fs";
35917
- import { join as join22 } from "path";
36908
+ import { readFileSync as readFileSync15 } from "fs";
36909
+ import { join as join23 } from "path";
35918
36910
 
35919
36911
  // ../../packages/plugin-runtime/src/attached/history-sync.ts
35920
36912
  import { createHash as createHash6 } from "crypto";
35921
36913
  import { hostname as hostname5 } from "os";
35922
36914
 
35923
- // ../../packages/remote/src/http.ts
35924
- import { request as httpRequest } from "http";
35925
- import { request as httpsRequest } from "https";
35926
- var DEFAULT_TIMEOUT_MS = 1e4;
35927
- var MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
35928
- var RemoteRequestError = class extends Error {
35929
- constructor(status) {
35930
- super(`control-plane request failed with status ${String(status)}`);
35931
- this.status = status;
35932
- this.name = "RemoteRequestError";
35933
- }
35934
- status;
35935
- };
35936
- var RemoteRequestInvalid = class extends Error {
35937
- constructor(route, cause) {
35938
- super(`refusing to send a malformed body to ${route}`);
35939
- this.cause = cause;
35940
- this.name = "RemoteRequestInvalid";
35941
- }
35942
- cause;
35943
- };
35944
- var RemoteResponseInvalid = class extends Error {
35945
- constructor(route, detail) {
35946
- super(`control plane answered ${route} with ${detail}`);
35947
- this.name = "RemoteResponseInvalid";
35948
- }
35949
- };
35950
- var RemoteTransportError = class extends Error {
35951
- /**
35952
- * The status the peer sent, when headers arrived and only the BODY was
35953
- * refused.
35954
- *
35955
- * Undefined for the ordinary case this class was written for — no answer at
35956
- * all. It exists because two paths reject after a status has already been
35957
- * delivered: an oversized body and an aborted response. Discarding it there
35958
- * reported a deployment answering 401 with a verbose body as a network
35959
- * outage, which sends the reader to look at their network instead of their
35960
- * credential.
35961
- */
35962
- constructor(reason, status) {
35963
- super(`control-plane request did not complete: ${reason}`);
35964
- this.status = status;
35965
- this.name = "RemoteTransportError";
35966
- }
35967
- status;
35968
- };
35969
- async function send(options) {
35970
- const url2 = new URL(options.url);
35971
- const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
35972
- const send_ = url2.protocol === "http:" ? httpRequest : httpsRequest;
35973
- const requestOptions = {
35974
- method: options.method,
35975
- headers: {
35976
- // CALLER HEADERS FIRST, so this module's own are not overridable. Spread
35977
- // last they win, and two of the values below are ones no caller may
35978
- // replace: `x-api-key` is the credential, and `content-length` is the
35979
- // byte count that stops a multi-byte body being truncated by the
35980
- // receiver. `SendOptions.headers` is a free-form record on an exported
35981
- // function, so "no caller does that today" is not the guarantee to rely
35982
- // on. The one header any caller actually passes — `if-none-match` on the
35983
- // conditional GET — is untouched by this order.
35984
- ...options.headers,
35985
- // The credential. One header, matching what the deployment authenticates
35986
- // on; a second copy in an `Authorization` header would be one more place
35987
- // it can be logged by an intermediary for no gain.
35988
- //
35989
- // Spread conditionally rather than assigned as `undefined`: Node's header
35990
- // handling and `content-length` bookkeeping treat a present-but-undefined
35991
- // key differently from an absent one, and "the header is not there" is
35992
- // the property the attach flow needs.
35993
- ...options.apiKey === void 0 ? {} : { "x-api-key": options.apiKey },
35994
- accept: "application/json",
35995
- ...options.body === void 0 ? {} : {
35996
- "content-type": "application/json",
35997
- // Byte length, not string length: a multi-byte body sent with a
35998
- // character count is truncated by the receiver.
35999
- "content-length": String(Buffer.byteLength(options.body))
36000
- }
36001
- }
36002
- };
36003
- return new Promise((resolve2, reject) => {
36004
- let settled = false;
36005
- const fail = (reason, status) => {
36006
- if (settled) return;
36007
- settled = true;
36008
- reject(new RemoteTransportError(reason, status));
36009
- };
36010
- const req = send_(url2, requestOptions, (res) => {
36011
- const chunks = [];
36012
- let size = 0;
36013
- res.on("data", (chunk) => {
36014
- size += chunk.length;
36015
- if (size > MAX_RESPONSE_BYTES) {
36016
- fail(`response exceeded ${String(MAX_RESPONSE_BYTES)} bytes`, res.statusCode);
36017
- res.destroy();
36018
- req.destroy();
36019
- return;
36020
- }
36021
- chunks.push(chunk);
36022
- });
36023
- res.on("aborted", () => {
36024
- fail("the response was aborted", res.statusCode);
36025
- });
36026
- res.on("end", () => {
36027
- if (settled) return;
36028
- settled = true;
36029
- resolve2({
36030
- status: res.statusCode ?? 0,
36031
- headers: res.headers,
36032
- body: Buffer.concat(chunks).toString("utf8")
36033
- });
36034
- });
36035
- });
36036
- const deadline = setTimeout(() => {
36037
- fail(`no response within ${String(timeoutMs)}ms`);
36038
- req.destroy();
36039
- }, timeoutMs);
36040
- deadline.unref();
36041
- req.on("upgrade", (_res, socket) => {
36042
- fail("the deployment answered with a protocol upgrade");
36043
- socket.destroy();
36044
- });
36045
- req.on("close", () => {
36046
- fail("the connection closed before a response was read");
36047
- clearTimeout(deadline);
36048
- });
36049
- req.on("error", (err) => {
36050
- fail(err.message);
36051
- });
36052
- if (options.body !== void 0) req.write(options.body);
36053
- req.end();
36054
- });
36055
- }
36056
-
36057
- // ../../packages/remote/src/client.ts
36058
- var ROUTES = {
36059
- events: "/v1/events",
36060
- auditEvents: "/v1/audit-events",
36061
- auditEventsBatch: "/v1/audit-events/batch",
36062
- inventory: "/v1/inventory",
36063
- storePosture: "/v1/store-posture",
36064
- policyBundle: "/v1/policy-bundle",
36065
- whoami: "/v1/plugin/whoami",
36066
- shares: "/v1/shares"
36067
- };
36068
- function headerValue(response, name) {
36069
- const raw = response.headers[name];
36070
- if (raw === void 0) return void 0;
36071
- return Array.isArray(raw) ? raw[0] : raw;
36072
- }
36073
- function okBody(response) {
36074
- if (response.status < 200 || response.status >= 300) {
36075
- throw new RemoteRequestError(response.status);
36076
- }
36077
- return response.body;
36078
- }
36079
- function parsed(schema, body, route) {
36080
- let json2;
36081
- try {
36082
- json2 = JSON.parse(body);
36083
- } catch {
36084
- throw new RemoteResponseInvalid(route, "a body that is not JSON");
36085
- }
36086
- const result = schema.safeParse(json2);
36087
- if (!result.success) {
36088
- throw new RemoteResponseInvalid(route, "a body this client cannot read");
36089
- }
36090
- return result.data;
36091
- }
36092
- function withoutTrailingSlashes(endpoint) {
36093
- let end = endpoint.length;
36094
- while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH) end -= 1;
36095
- return endpoint.slice(0, end);
36096
- }
36097
- var SLASH = "/".charCodeAt(0);
36098
- function createRemoteClient(options) {
36099
- const base = withoutTrailingSlashes(options.endpoint);
36100
- const url2 = (route) => `${base}${route}`;
36101
- const common = { apiKey: options.apiKey, timeoutMs: options.timeoutMs };
36102
- const sendOne = async (event) => {
36103
- const validated = RecordAuditEventRequest.safeParse(event);
36104
- if (!validated.success) throw new RemoteRequestInvalid(ROUTES.auditEvents, validated.error);
36105
- const response = await send({
36106
- ...common,
36107
- method: "POST",
36108
- url: url2(ROUTES.auditEvents),
36109
- body: JSON.stringify(validated.data)
36110
- });
36111
- okBody(response);
36112
- };
36113
- return {
36114
- async ingestEvents(batch) {
36115
- const response = await send({
36116
- ...common,
36117
- method: "POST",
36118
- url: url2(ROUTES.events),
36119
- body: JSON.stringify(batch)
36120
- });
36121
- return parsed(IngestAck, okBody(response), ROUTES.events);
36122
- },
36123
- async ingestInventory(context) {
36124
- const response = await send({
36125
- ...common,
36126
- method: "POST",
36127
- url: url2(ROUTES.inventory),
36128
- body: JSON.stringify(context)
36129
- });
36130
- return parsed(ResolvedInventory, okBody(response), ROUTES.inventory);
36131
- },
36132
- async recordAuditEvent(event) {
36133
- await sendOne(event);
36134
- },
36135
- async recordAuditEvents(events) {
36136
- const validated = RecordAuditEventBatch.safeParse({ events });
36137
- if (!validated.success) {
36138
- throw new RemoteRequestInvalid(ROUTES.auditEventsBatch, validated.error);
36139
- }
36140
- const response = await send({
36141
- ...common,
36142
- method: "POST",
36143
- url: url2(ROUTES.auditEventsBatch),
36144
- body: JSON.stringify(validated.data)
36145
- });
36146
- if (response.status === 404) {
36147
- for (const event of validated.data.events) await sendOne(event);
36148
- return { accepted: validated.data.events.length };
36149
- }
36150
- return parsed(AuditEventBatchAck, okBody(response), ROUTES.auditEventsBatch);
36151
- },
36152
- async reportStorePosture(snapshot) {
36153
- const response = await send({
36154
- ...common,
36155
- method: "POST",
36156
- url: url2(ROUTES.storePosture),
36157
- body: JSON.stringify(snapshot)
36158
- });
36159
- okBody(response);
36160
- },
36161
- async getPolicyBundle(etag) {
36162
- const response = await send({
36163
- ...common,
36164
- method: "GET",
36165
- url: url2(ROUTES.policyBundle),
36166
- ...etag === void 0 ? {} : { headers: { "if-none-match": etag } }
36167
- });
36168
- if (response.status === 304) {
36169
- return { changed: false, etag: headerValue(response, "etag") ?? etag };
36170
- }
36171
- const bundle = parsed(PolicyBundle, okBody(response), ROUTES.policyBundle);
36172
- return { changed: true, bundle, etag: headerValue(response, "etag") };
36173
- },
36174
- async whoami() {
36175
- const response = await send({ ...common, method: "GET", url: url2(ROUTES.whoami) });
36176
- return parsed(PluginWhoami, okBody(response), ROUTES.whoami);
36177
- },
36178
- async recordProjectEgress(request) {
36179
- const validated = EgressIngestRequest.safeParse(request);
36180
- if (!validated.success) throw new RemoteRequestInvalid(ROUTES.shares, validated.error);
36181
- const response = await send({
36182
- ...common,
36183
- method: "POST",
36184
- url: url2(ROUTES.shares),
36185
- body: JSON.stringify(validated.data)
36186
- });
36187
- okBody(response);
36188
- }
36189
- };
36190
- }
36915
+ // ../../packages/plugin-runtime/src/attached/capture-rebuild.ts
36916
+ var CORRELATION_ID = EventMetadata.shape.correlationId;
36917
+ var TRACE_ID = EventMetadata.shape.traceId;
36918
+ var EXCEPTION_ID = EventMetadata.shape.exceptionIds.unwrap().element;
36191
36919
 
36192
36920
  // ../../packages/plugin-runtime/src/attached/history-sync-trigger.ts
36193
36921
  import { spawn } from "child_process";
@@ -36195,14 +36923,14 @@ import { fileURLToPath as fileURLToPath2 } from "url";
36195
36923
  var HISTORY_SYNC_THROTTLE_MS = 5 * 60 * 1e3;
36196
36924
 
36197
36925
  // ../../packages/plugin-runtime/src/attached/plugin-block.ts
36198
- import { readFileSync as readFileSync15 } from "fs";
36926
+ import { readFileSync as readFileSync16 } from "fs";
36199
36927
  var manifestBuildCache = /* @__PURE__ */ new Map();
36200
36928
  function readManifestBuild(manifestUrl, packageName) {
36201
36929
  const key = manifestUrl.href;
36202
36930
  if (!manifestBuildCache.has(key)) {
36203
36931
  let build;
36204
36932
  try {
36205
- const manifest = JSON.parse(readFileSync15(manifestUrl, "utf8"));
36933
+ const manifest = JSON.parse(readFileSync16(manifestUrl, "utf8"));
36206
36934
  build = typeof manifest.version === "string" && manifest.version.length > 0 ? { package: packageName, version: manifest.version } : void 0;
36207
36935
  } catch {
36208
36936
  build = void 0;
@@ -36229,7 +36957,7 @@ function createPluginBlock(build, policyStore) {
36229
36957
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
36230
36958
  import { randomUUID as randomUUID16 } from "crypto";
36231
36959
  import { readFile as readFile2, rm, writeFile as writeFile2 } from "fs/promises";
36232
- import { join as join23 } from "path";
36960
+ import { join as join24 } from "path";
36233
36961
 
36234
36962
  // ../../packages/plugin-runtime/src/attached/atomic-publish.ts
36235
36963
  import { rename as rename2 } from "fs/promises";
@@ -36253,7 +36981,7 @@ async function publishByRename(tmp, file2, move = rename2) {
36253
36981
 
36254
36982
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
36255
36983
  function createPolicyStore(dir = dataDir()) {
36256
- const file2 = join23(dir, "policy-cache.json");
36984
+ const file2 = join24(dir, "policy-cache.json");
36257
36985
  async function read() {
36258
36986
  try {
36259
36987
  const raw = await readFile2(file2, "utf8");
@@ -36262,22 +36990,32 @@ function createPolicyStore(dir = dataDir()) {
36262
36990
  const record2 = parsed2;
36263
36991
  const bundle = PolicyBundle.parse(record2.bundle);
36264
36992
  const fetchedAtMs = typeof record2.fetchedAtMs === "number" ? record2.fetchedAtMs : 0;
36265
- const etag = typeof record2.etag === "string" ? record2.etag : void 0;
36993
+ const stored = typeof record2.etag === "string" ? record2.etag : void 0;
36994
+ const replayable = record2.shapeId === POLICY_BUNDLE_SHAPE_ID || knowsMoreThanThisBuild(record2.shapeId);
36995
+ const etag = replayable ? stored : void 0;
36266
36996
  return { bundle, fetchedAtMs, ...etag === void 0 ? {} : { etag } };
36267
36997
  } catch {
36268
36998
  return null;
36269
36999
  }
36270
37000
  }
36271
- async function write(bundle, etag) {
36272
- await ensureDataDir(dir);
36273
- const stored = {
36274
- bundle,
36275
- fetchedAtMs: Date.now(),
36276
- ...etag === void 0 ? {} : { etag }
36277
- };
37001
+ function knowsMoreThanThisBuild(shapeId) {
37002
+ if (typeof shapeId !== "string" || shapeId === "") return false;
37003
+ const theirs = new Set(shapeId.split(","));
37004
+ const ours = new Set(POLICY_BUNDLE_SHAPE_ID.split(","));
37005
+ return theirs.size > ours.size && [...ours].every((key) => theirs.has(key));
37006
+ }
37007
+ async function priorRecord() {
37008
+ try {
37009
+ const parsed2 = JSON.parse(await readFile2(file2, "utf8"));
37010
+ return typeof parsed2 === "object" && parsed2 !== null ? parsed2 : null;
37011
+ } catch {
37012
+ return null;
37013
+ }
37014
+ }
37015
+ async function publishRecord(record2) {
36278
37016
  const tmp = `${file2}.${randomUUID16()}.tmp`;
36279
37017
  try {
36280
- await writeFile2(tmp, JSON.stringify(stored), {
37018
+ await writeFile2(tmp, JSON.stringify(record2), {
36281
37019
  encoding: "utf8",
36282
37020
  mode: DATA_FILE_MODE,
36283
37021
  flag: "wx"
@@ -36288,6 +37026,27 @@ function createPolicyStore(dir = dataDir()) {
36288
37026
  throw err;
36289
37027
  }
36290
37028
  }
37029
+ async function write(bundle, etag) {
37030
+ await ensureDataDir(dir);
37031
+ const prior = await priorRecord();
37032
+ const priorVersion = prior?.bundle?.version;
37033
+ if (prior !== null && knowsMoreThanThisBuild(prior.shapeId) && priorVersion === bundle.version) {
37034
+ await publishRecord({
37035
+ ...prior,
37036
+ fetchedAtMs: Date.now()
37037
+ });
37038
+ return;
37039
+ }
37040
+ await publishRecord({
37041
+ bundle,
37042
+ fetchedAtMs: Date.now(),
37043
+ // Stamped on EVERY write, the 304 arm's included: that arm hands back the
37044
+ // bundle it already holds, and the point of the stamp is to describe the
37045
+ // build that last narrowed those bytes, which is this one.
37046
+ shapeId: POLICY_BUNDLE_SHAPE_ID,
37047
+ ...etag === void 0 ? {} : { etag }
37048
+ });
37049
+ }
36291
37050
  return { read, write, file: file2 };
36292
37051
  }
36293
37052
 
@@ -36453,11 +37212,11 @@ function readStorePosture(dbPath2) {
36453
37212
  // ../../packages/plugin-runtime/src/attached/posture-store.ts
36454
37213
  import { randomUUID as randomUUID17 } from "crypto";
36455
37214
  import { readFile as readFile3, rm as rm2, writeFile as writeFile3 } from "fs/promises";
36456
- import { join as join24 } from "path";
37215
+ import { join as join25 } from "path";
36457
37216
  var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
36458
37217
  function createPostureStore(dir = settingsDir(), legacyDir) {
36459
- const file2 = join24(dir, "posture-state.json");
36460
- const legacyFile = legacyDir === void 0 ? null : join24(legacyDir, "posture-state.json");
37218
+ const file2 = join25(dir, "posture-state.json");
37219
+ const legacyFile = legacyDir === void 0 ? null : join25(legacyDir, "posture-state.json");
36461
37220
  async function persist(state) {
36462
37221
  await ensureDataDir(dir);
36463
37222
  const tmp = `${file2}.${randomUUID17()}.tmp`;
@@ -36525,8 +37284,8 @@ function createPostureStore(dir = settingsDir(), legacyDir) {
36525
37284
  }
36526
37285
 
36527
37286
  // ../../packages/plugin-runtime/src/attached/sync-state.ts
36528
- import { readFileSync as readFileSync16 } from "fs";
36529
- import { join as join25 } from "path";
37287
+ import { readFileSync as readFileSync17 } from "fs";
37288
+ import { join as join26 } from "path";
36530
37289
 
36531
37290
  // ../../packages/plugin-runtime/src/attached/status.ts
36532
37291
  var REFUSAL_LINES = {
@@ -36844,9 +37603,21 @@ var StandaloneDataGateway = class {
36844
37603
  // for the whole of it, so a member that threw would make that answer a lie
36845
37604
  // the moment a composite delegated to it. A store-level no-op is the honest
36846
37605
  // shape — a standalone machine has nothing delivered to record.
37606
+ markCaptureOwed(event) {
37607
+ this.db.markCaptureOwed(event);
37608
+ }
36847
37609
  markCaptureDelivered(event, atMs) {
36848
37610
  this.db.markCaptureDelivered(event, atMs);
36849
37611
  }
37612
+ // Implemented, not stubbed, for the same reason its sibling above is: the
37613
+ // attached gateway is a DECORATOR over an instance of this class
37614
+ // (`attached/factory.ts` builds one and passes it as `deps.local`), so every
37615
+ // stamp the live forward makes lands here with a non-empty array. This is the
37616
+ // production write path for that feature, not a shape-satisfying no-op — a
37617
+ // machine that is merely standalone simply never calls it.
37618
+ markAuditEventsDelivered(events, atMs) {
37619
+ this.db.markAuditEventsDelivered(events, atMs);
37620
+ }
36850
37621
  staleBinaryNotice(currentVersion) {
36851
37622
  try {
36852
37623
  const newest = this.db.installedPacks.newestRecordedBinary();
@@ -36998,13 +37769,13 @@ import {
36998
37769
  fstatSync as fstatSync2,
36999
37770
  mkdirSync as mkdirSync5,
37000
37771
  openSync as openSync3,
37001
- readFileSync as readFileSync17,
37772
+ readFileSync as readFileSync18,
37002
37773
  readSync as readSync2,
37003
37774
  writeFileSync as writeFileSync8
37004
37775
  } from "fs";
37005
- import { join as join26 } from "path";
37776
+ import { join as join27 } from "path";
37006
37777
  function offsetsDir(dataDir2) {
37007
- return join26(dataDir2, "usage-offsets");
37778
+ return join27(dataDir2, "usage-offsets");
37008
37779
  }
37009
37780
  var SAFE_SESSION_ID = /^[A-Za-z0-9._-]+$/;
37010
37781
  function safeSessionId(sessionId) {
@@ -37014,11 +37785,11 @@ function safeSessionId(sessionId) {
37014
37785
  return createHash7("sha256").update(sessionId).digest("hex");
37015
37786
  }
37016
37787
  function offsetPath(dataDir2, sessionId) {
37017
- return join26(offsetsDir(dataDir2), safeSessionId(sessionId));
37788
+ return join27(offsetsDir(dataDir2), safeSessionId(sessionId));
37018
37789
  }
37019
37790
  function readOffset(dataDir2, sessionId) {
37020
37791
  try {
37021
- const raw = readFileSync17(offsetPath(dataDir2, sessionId), "utf8");
37792
+ const raw = readFileSync18(offsetPath(dataDir2, sessionId), "utf8");
37022
37793
  const parsed2 = JSON.parse(raw);
37023
37794
  if (typeof parsed2 === "object" && parsed2 !== null) {
37024
37795
  const rec = parsed2;
@@ -37076,9 +37847,9 @@ function readTail(transcriptPath, startOffset) {
37076
37847
  }
37077
37848
 
37078
37849
  // src/history/transcripts.ts
37079
- import { closeSync as closeSync4, openSync as openSync4, readdirSync as readdirSync5, readFileSync as readFileSync18, readSync as readSync3, statSync as statSync10 } from "fs";
37850
+ import { closeSync as closeSync4, openSync as openSync4, readdirSync as readdirSync5, readFileSync as readFileSync19, readSync as readSync3, statSync as statSync10 } from "fs";
37080
37851
  import { homedir as homedir3 } from "os";
37081
- import { join as join27 } from "path";
37852
+ import { join as join28 } from "path";
37082
37853
  function isRecord(value) {
37083
37854
  return typeof value === "object" && value !== null;
37084
37855
  }