@akasecurity/ai-tc-codex 0.9.9 → 0.9.10

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