@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.
@@ -492,7 +492,7 @@ var require_ignore = __commonJS({
492
492
  });
493
493
 
494
494
  // src/hooks/session-start.ts
495
- import { readFileSync as readFileSync20 } from "fs";
495
+ import { readFileSync as readFileSync21 } from "fs";
496
496
 
497
497
  // ../../packages/plugin-runtime/src/attached/egress-wire.ts
498
498
  import { createHash as createHash4 } from "crypto";
@@ -500,6 +500,7 @@ import { createHash as createHash4 } from "crypto";
500
500
  // ../../packages/persistence/src/attached-derived.ts
501
501
  import { rmSync } from "fs";
502
502
  import { join } from "path";
503
+ var POLICY_CACHE_FILENAME = "policy-cache.json";
503
504
  var ATTACHED_FORWARD_STATE_FILENAME = "attached-state.json";
504
505
  var ATTACHED_FORWARD_DROPS_FILENAME = "attached-forward-drops.json";
505
506
 
@@ -600,6 +601,30 @@ var SQLITE_MIGRATIONS = [
600
601
  {
601
602
  tag: "0022_audit_inspection_ms",
602
603
  sql: "ALTER TABLE `audit_events` ADD `inspection_ms` integer GENERATED ALWAYS AS (json_extract(attributes, '$.inspection_ms')) VIRTUAL;"
604
+ },
605
+ {
606
+ tag: "0023_secret_vault_user_authorized",
607
+ sql: "ALTER TABLE `secret_vault` ADD `user_authorized` integer DEFAULT 0 NOT NULL;"
608
+ },
609
+ {
610
+ tag: "0024_finding_resolution_key_created_index",
611
+ 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`);"
612
+ },
613
+ {
614
+ tag: "0025_audit_capture_attribute_columns",
615
+ 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;"
616
+ },
617
+ {
618
+ tag: "0026_audit_llm_call_usage_columns",
619
+ 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;"
620
+ },
621
+ {
622
+ tag: "0027_audit_llm_usage_index",
623
+ 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;"
624
+ },
625
+ {
626
+ tag: "0028_activity_session_probe_indexes",
627
+ 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"
603
628
  }
604
629
  ];
605
630
 
@@ -22256,6 +22281,26 @@ var AttachTokenResponse = external_exports.union([
22256
22281
  AttachTokenExpired,
22257
22282
  external_exports.object({ status: printable(64) })
22258
22283
  ]);
22284
+ var DeviceCommandKind = external_exports.enum(["shares_rescan"]);
22285
+ var DeviceCommand = external_exports.object({
22286
+ id: printable(128).min(1),
22287
+ kind: DeviceCommandKind,
22288
+ issuedAt: printable(64).min(1),
22289
+ expiresAt: printable(64).min(1)
22290
+ }).strict();
22291
+ var DeviceCommandPollResponse = external_exports.object({ command: DeviceCommand.nullable() });
22292
+ var DeviceCommandFailureReason = external_exports.enum(["scan_failed", "no_projects", "expired"]);
22293
+ var DeviceCommandAckBody = external_exports.discriminatedUnion("outcome", [
22294
+ external_exports.object({
22295
+ outcome: external_exports.literal("reported"),
22296
+ projectsScanned: external_exports.number().int().nonnegative()
22297
+ }).strict(),
22298
+ external_exports.object({
22299
+ outcome: external_exports.literal("failed"),
22300
+ reason: DeviceCommandFailureReason,
22301
+ projectsScanned: external_exports.number().int().nonnegative()
22302
+ }).strict()
22303
+ ]);
22259
22304
 
22260
22305
  // ../../packages/schema/src/zod/registry.ts
22261
22306
  var Namespace = external_exports.string().regex(/^[a-z][a-z0-9-]*$/);
@@ -22422,7 +22467,7 @@ var PackManifest = external_exports.object({
22422
22467
  }).meta({ id: "PackManifest" });
22423
22468
 
22424
22469
  // ../../packages/schema/src/zod/detection.ts
22425
- var OriginEnum = external_exports.enum(["library"]).meta({ id: "OriginEnum" });
22470
+ var OriginEnum = external_exports.enum(["library", "custom"]).meta({ id: "OriginEnum" });
22426
22471
  var DetectionFilterEnum = external_exports.enum(["all", "library", "custom", "customized", "updates"]);
22427
22472
  var LibraryStateEnum = external_exports.enum(["new", "imported", "update"]).meta({ id: "LibraryStateEnum" });
22428
22473
  var DetectionCounts = external_exports.object({
@@ -22559,14 +22604,17 @@ function optional2(key, parsed2, raw) {
22559
22604
  function isStringArray(value) {
22560
22605
  return Array.isArray(value) && value.every((entry) => typeof entry === "string");
22561
22606
  }
22607
+ var ORIGIN_VALUES = { library: true, custom: true };
22608
+ function resolveOrigin(origin) {
22609
+ return origin != null && Object.hasOwn(ORIGIN_VALUES, origin) ? origin : "library";
22610
+ }
22562
22611
  function summaryToDetectionListItem(s) {
22563
22612
  return {
22564
22613
  id: `${s.namespace}/${s.packId}`,
22565
22614
  name: s.name,
22566
22615
  version: s.version,
22567
22616
  enabled: s.enabled,
22568
- origin: "library",
22569
- // v1: every installed pack is library origin
22617
+ origin: resolveOrigin(s.origin),
22570
22618
  namespace: s.namespace,
22571
22619
  packId: s.packId,
22572
22620
  ruleCount: s.ruleCount,
@@ -22618,7 +22666,7 @@ function rowToDetectionDetail(row, findingsLast30d, update) {
22618
22666
  name: row.name,
22619
22667
  version: row.version,
22620
22668
  enabled: row.enabled,
22621
- origin: "library",
22669
+ origin: resolveOrigin(row.origin),
22622
22670
  namespace: row.namespace,
22623
22671
  packId: row.packId,
22624
22672
  ruleCount: row.rules.length,
@@ -22638,16 +22686,20 @@ function splitDetectionId(id) {
22638
22686
  }
22639
22687
  function buildDetectionsList(summaries, query) {
22640
22688
  const withUpdate = summaries.filter((s) => s.latestVersion != null);
22689
+ const originOf = (s) => resolveOrigin(s.origin);
22641
22690
  const counts = {
22642
22691
  all: summaries.length,
22643
- library: summaries.length,
22644
- // all origin=library in v1
22645
- custom: 0,
22692
+ library: summaries.filter((s) => originOf(s) === "library").length,
22693
+ custom: summaries.filter((s) => originOf(s) === "custom").length,
22694
+ // No origin member produces this, so it is 0 BY CONSTRUCTION rather than by
22695
+ // omission: `customized` would mean a LIBRARY pack whose rules were edited in
22696
+ // place, and that state does not exist — editing a library pack forks it. See
22697
+ // OriginEnum.
22646
22698
  customized: 0,
22647
22699
  updates: withUpdate.length
22648
22700
  };
22649
22701
  const filter = query.filter;
22650
- let filtered = filter === "custom" || filter === "customized" ? [] : filter === "updates" ? [...withUpdate] : [...summaries];
22702
+ let filtered = filter === "customized" ? [] : filter === "custom" ? summaries.filter((s) => originOf(s) === "custom") : filter === "library" ? summaries.filter((s) => originOf(s) === "library") : filter === "updates" ? [...withUpdate] : [...summaries];
22651
22703
  if (query.q) {
22652
22704
  const q = query.q.toLowerCase();
22653
22705
  filtered = filtered.filter(
@@ -22727,8 +22779,9 @@ var Event = external_exports.object({
22727
22779
  metadata: EventMetadata.optional()
22728
22780
  }).meta({ id: "Event" });
22729
22781
  var IngestEvent = Event.meta({ id: "IngestEvent" });
22782
+ var INGEST_BATCH_MAX = 100;
22730
22783
  var IngestBatch = external_exports.object({
22731
- events: external_exports.array(IngestEvent).min(1).max(100),
22784
+ events: external_exports.array(IngestEvent).min(1).max(INGEST_BATCH_MAX),
22732
22785
  // Dedup policy for this batch. Id-dedup ALWAYS applies. 'content-hash'
22733
22786
  // additionally rejects any event whose contentHash the store has already
22734
22787
  // recorded — for re-runnable bulk ingest (worktree scan, transcript
@@ -23284,380 +23337,11 @@ var PatchInstalledPackRequest = external_exports.object({
23284
23337
  message: "At least one field must be provided"
23285
23338
  }).meta({ id: "PatchInstalledPackRequest" });
23286
23339
 
23287
- // ../../packages/schema/src/zod/vault.ts
23288
- var POINTER_FORMAT_VERSION = 2;
23289
- var CATEGORY_ALTERNATION = DetectionCategory.options.join("|");
23290
- var POINTER_TOKEN_PATTERN = new RegExp(
23291
- `\\[\\[aka:(?:${CATEGORY_ALTERNATION}):[A-Z2-7]{2,7}\\.[A-Z2-7]{26}\\.[A-Z2-7]{16}\\]\\]`
23292
- );
23293
- var POINTER_TOKEN_ANCHORED = new RegExp(`^${POINTER_TOKEN_PATTERN.source}$`);
23294
- function pointerTokenScanner() {
23295
- return new RegExp(POINTER_TOKEN_PATTERN.source, "g");
23296
- }
23297
- var PointerToken = external_exports.string().regex(POINTER_TOKEN_ANCHORED);
23298
- var ParsedPointer = external_exports.object({
23299
- category: DetectionCategory,
23300
- keyVersion: external_exports.number().int().positive(),
23301
- pointerId: external_exports.string(),
23302
- tag: external_exports.string()
23303
- });
23304
- var VaultEntry = external_exports.object({
23305
- pointerId: external_exports.string(),
23306
- // The keyed HMAC of the raw value under `exception.key`, and the epoch it was
23307
- // derived under. This is what a reveal-to-model grant matches on, and it rotates
23308
- // independently of the vault encryption key below.
23309
- valueFingerprint: external_exports.string().regex(/^[0-9a-f]{64}$/),
23310
- fingerprintKeyVersion: external_exports.number().int().positive(),
23311
- // The vault-key epoch this row's ciphertext was sealed under.
23312
- keyVersion: external_exports.number().int().positive(),
23313
- // Fixed at first mint and never updated: the same value detected later under a
23314
- // different rule's category keeps the category it was minted with, so one
23315
- // value always produces exactly one wire token.
23316
- category: DetectionCategory,
23317
- ruleId: external_exports.string(),
23318
- // Partial-reveal preview for badges and listings. Never the raw value.
23319
- maskedMatch: external_exports.string(),
23320
- provider: external_exports.string().optional(),
23321
- ciphertext: external_exports.string(),
23322
- nonce: external_exports.string(),
23323
- authTag: external_exports.string(),
23324
- // How many times this value has been detected on this machine — the reuse
23325
- // signal the vault dashboard reads. Distinct from VaultDeref.pointerCount.
23326
- occurrenceCount: external_exports.number().int().nonnegative(),
23327
- firstSeen: external_exports.string(),
23328
- lastSeen: external_exports.string()
23329
- });
23330
- var PointerDescriptor = external_exports.object({
23331
- category: DetectionCategory,
23332
- provider: external_exports.string().optional(),
23333
- maskedMatch: external_exports.string(),
23334
- occurrences: external_exports.number().int().nonnegative(),
23335
- firstSeen: external_exports.string(),
23336
- lastSeen: external_exports.string()
23337
- });
23338
- var PointerIdentity = external_exports.object({
23339
- ruleId: external_exports.string(),
23340
- valueFingerprint: external_exports.string().regex(/^[0-9a-f]{64}$/),
23341
- fingerprintKeyVersion: external_exports.number().int().positive()
23342
- });
23343
- var DetokenizeTarget = external_exports.enum(["human", "model"]);
23344
- var VaultDerefReason = external_exports.enum([
23345
- "display",
23346
- "explicit-reveal",
23347
- "view-render",
23348
- "model-input",
23349
- "remediation",
23350
- "purge"
23351
- ]);
23352
- var VaultDerefOutcome = external_exports.enum(["revealed", "refused", "unavailable"]);
23353
- var VaultDeref = external_exports.object({
23354
- id: external_exports.guid(),
23355
- pointerId: external_exports.string(),
23356
- at: external_exports.string(),
23357
- target: DetokenizeTarget,
23358
- reason: VaultDerefReason,
23359
- outcome: VaultDerefOutcome,
23360
- // Present only on a model-target crossing that a reveal grant authorized.
23361
- grantId: external_exports.string().optional(),
23362
- // How many pointers ONE batched render resolved. 1 for unbatched rows. Named
23363
- // apart from VaultEntry.occurrenceCount, which counts detections of a value.
23364
- pointerCount: external_exports.number().int().positive().default(1)
23365
- });
23366
- var VaultSightingKind = external_exports.enum([
23367
- "prompt",
23368
- "tool-input",
23369
- "tool-output",
23370
- "file",
23371
- "transcript"
23372
- ]);
23373
- var VaultSighting = external_exports.object({
23374
- location: external_exports.string(),
23375
- kind: VaultSightingKind,
23376
- firstSeen: external_exports.string(),
23377
- lastSeen: external_exports.string()
23378
- });
23379
- var VaultInventoryEntry = external_exports.object({
23380
- pointerId: external_exports.string(),
23381
- category: DetectionCategory,
23382
- provider: external_exports.string().optional(),
23383
- maskedMatch: external_exports.string(),
23384
- occurrences: external_exports.number().int().nonnegative(),
23385
- firstSeen: external_exports.string(),
23386
- lastSeen: external_exports.string(),
23387
- // The active reveal-to-model grant covering this value, when one exists —
23388
- // the inventory badges it, the row links to revocation.
23389
- revealGrantId: external_exports.string().nullable(),
23390
- sightings: external_exports.array(VaultSighting)
23391
- });
23392
- var DEFAULT_VAULT_INVENTORY_LIMIT = 50;
23393
- var DEFAULT_VAULT_DEREFS_LIMIT = 50;
23394
- var MAX_VAULT_PAGE_LIMIT = 200;
23395
- var ListVaultInventoryQuery = external_exports.object({
23396
- limit: external_exports.coerce.number().int().min(1).max(MAX_VAULT_PAGE_LIMIT).optional(),
23397
- // Opaque; names the last row of the page just served.
23398
- cursor: external_exports.string().optional()
23399
- });
23400
- var ListVaultInventoryResponse = external_exports.object({
23401
- // Vaulted values across the whole store, not just this page — cursor-
23402
- // independent, so paging never changes what the count claims.
23403
- totals: external_exports.object({ values: external_exports.number().int().nonnegative() }),
23404
- items: external_exports.array(VaultInventoryEntry),
23405
- // `null` once the last page is reached.
23406
- nextCursor: external_exports.string().nullable()
23407
- });
23408
- var ListVaultReuseQuery = external_exports.object({
23409
- limit: external_exports.coerce.number().int().min(1).max(MAX_VAULT_PAGE_LIMIT).optional(),
23410
- cursor: external_exports.string().optional()
23411
- });
23412
- var ListVaultReuseResponse = external_exports.object({
23413
- // Reused values across the whole store — the number the section's claim
23414
- // ("values detected in more than one place") is about.
23415
- totals: external_exports.object({ reused: external_exports.number().int().nonnegative() }),
23416
- items: external_exports.array(VaultInventoryEntry),
23417
- nextCursor: external_exports.string().nullable()
23418
- });
23419
- var ListVaultDerefsQuery = external_exports.object({
23420
- // Include the batched, high-volume reasons (display, view-render). Omitted
23421
- // hides them and counts them into `hiddenBatched` instead, so the model
23422
- // crossings stay visible. A real boolean, not `z.stringbool()`: this arrives
23423
- // over a Server Action, which preserves the type, never as a URL param.
23424
- includeBatched: external_exports.boolean().optional(),
23425
- limit: external_exports.coerce.number().int().min(1).max(MAX_VAULT_PAGE_LIMIT).optional(),
23426
- cursor: external_exports.string().optional()
23427
- });
23428
- var ListVaultDerefsResponse = external_exports.object({
23429
- items: external_exports.array(VaultDeref),
23430
- nextCursor: external_exports.string().nullable(),
23431
- // Display/view-render rows the query hid, over the WHOLE trail rather than
23432
- // this page — it is the count the "N hidden" line and its toggle speak for.
23433
- // Always 0 when `includeBatched` was set, since nothing was hidden.
23434
- hiddenBatched: external_exports.number().int().nonnegative()
23435
- });
23436
- var VaultKeyCustody = external_exports.string();
23437
- var VaultInlineReveal = external_exports.enum(["masked", "full", "off"]);
23438
- var VAULT_CONSENT_VERSION = 1;
23439
- var VaultConsent = external_exports.object({
23440
- acknowledgedAt: external_exports.iso.datetime(),
23441
- version: external_exports.number().int().positive()
23442
- });
23443
-
23444
- // ../../packages/schema/src/zod/local.ts
23445
- var WORKSPACE_SETTINGS_SPEC_VERSION = 6;
23446
- var MODEL_JUDGE_PAYLOAD_VERSION = 1;
23447
- var HISTORY_SYNC_PAYLOAD_VERSION = 1;
23448
- var RunMode = external_exports.enum(["standalone", "attached"]);
23449
- var ControlPlaneConnection = external_exports.object({
23450
- endpoint: external_exports.string().min(1),
23451
- // Display name for the deployment, shown instead of the raw endpoint.
23452
- label: external_exports.string().min(1).optional(),
23453
- attachedAt: external_exports.iso.datetime()
23454
- }).meta({ id: "ControlPlaneConnection" });
23455
- var SimpleDetectionPolicy = external_exports.enum(["redact", "warn"]);
23456
- var HistoricalAccess = external_exports.enum(["full", "session-only"]);
23457
- var ModelJudgeConsent = external_exports.object({
23458
- acknowledgedAt: external_exports.iso.datetime(),
23459
- payloadVersion: external_exports.number().int().positive()
23460
- });
23461
- var HistorySyncConsent = external_exports.object({
23462
- acknowledgedAt: external_exports.iso.datetime(),
23463
- payloadVersion: external_exports.number().int().positive(),
23464
- endpoint: external_exports.string()
23465
- });
23466
- function isHistorySyncConsentValid(consent, endpoint) {
23467
- if (consent === void 0 || endpoint === void 0) return false;
23468
- return consent.payloadVersion === HISTORY_SYNC_PAYLOAD_VERSION && consent.endpoint === endpoint;
23469
- }
23470
- var WorkspaceSettings = external_exports.object({
23471
- specVersion: external_exports.number().int().positive().default(WORKSPACE_SETTINGS_SPEC_VERSION),
23472
- runMode: RunMode.default("standalone"),
23473
- // Present only while attached; a detach clears it. Its presence is what makes
23474
- // `runMode: 'attached'` mean anything — see isAttached.
23475
- controlPlane: ControlPlaneConnection.optional(),
23476
- policy: SimpleDetectionPolicy.default("redact"),
23477
- // Consent for scanning pre-install surfaces; opt-in (see HistoricalAccess).
23478
- historicalAccess: HistoricalAccess.default("session-only"),
23479
- // In-place egress extraction on the scan paths; disable to stop all Data
23480
- // Shares writes.
23481
- dataSharesInPlace: external_exports.boolean().default(true),
23482
- // Consent to keep a RECOVERABLE encrypted copy of detected values in the local
23483
- // vault, instead of destroying them. Absent by default: this is a custody
23484
- // change from one-way redaction, so it is never an assumed grant on upgrade.
23485
- // Revoking stops future vaulting; it does not erase what is already stored —
23486
- // purging the vault is the eraser.
23487
- vaultConsent: VaultConsent.optional(),
23488
- // Where the vault master key lives.
23489
- vaultKeyCustody: VaultKeyCustody.default("file"),
23490
- // How a pointer renders in assistant prose on screen (see VaultInlineReveal).
23491
- vaultInlineReveal: VaultInlineReveal.default("masked"),
23492
- // Absent until /aka:setup completes; its presence is what "onboarded" means.
23493
- onboardedAt: external_exports.iso.datetime().optional(),
23494
- // Records that the user consented to sending findings to the model API for
23495
- // the /aka:setup judge, along with the payload-shape version they agreed to.
23496
- // Absent until granted; a stale payloadVersion means the consent no longer
23497
- // covers the current payload and must be re-granted.
23498
- modelJudgeConsent: ModelJudgeConsent.optional(),
23499
- // Records that the user consented to sending the activity already recorded on
23500
- // this machine to the deployment it is attached to, along with the payload
23501
- // shape and the endpoint they agreed to. Absent until granted, and a grant for
23502
- // a different endpoint or an older payload no longer counts.
23503
- historySyncConsent: HistorySyncConsent.optional()
23504
- });
23505
- function defaultWorkspaceSettings() {
23506
- return WorkspaceSettings.parse({});
23507
- }
23508
- function isAttached(settings) {
23509
- return settings.runMode === "attached" && settings.controlPlane !== void 0;
23510
- }
23511
- function toInventoryRow(input2, id, now) {
23512
- return {
23513
- id,
23514
- objectType: input2.objectType,
23515
- location: input2.location ?? null,
23516
- title: input2.title ?? null,
23517
- hostId: input2.hostId ?? null,
23518
- attributes: JSON.stringify(input2.attributes),
23519
- firstSeen: now,
23520
- lastSeen: now
23521
- };
23522
- }
23523
- function toSourceProjectRow(input2, id, now) {
23524
- return {
23525
- id,
23526
- url: input2.url,
23527
- name: input2.name ?? null,
23528
- attributes: JSON.stringify(input2.attributes),
23529
- firstSeen: now,
23530
- lastSeen: now
23531
- };
23532
- }
23533
- function toAuditEventRow(input2) {
23534
- return {
23535
- id: input2.id,
23536
- parentId: input2.parentId ?? null,
23537
- rootSessionId: input2.rootSessionId ?? null,
23538
- eventType: input2.eventType,
23539
- hostId: input2.hostId ?? null,
23540
- harnessId: input2.harnessId ?? null,
23541
- sourceProjectId: input2.sourceProjectId ?? null,
23542
- startedAt: isoToEpochMillis(input2.startedAt),
23543
- endedAt: input2.endedAt ? isoToEpochMillis(input2.endedAt) : null,
23544
- severity: input2.severity ?? null,
23545
- priority: input2.priority ?? null,
23546
- content: input2.content ?? null,
23547
- contentHash: input2.contentHash ?? null,
23548
- attributes: input2.attributes ? JSON.stringify(input2.attributes) : null
23549
- };
23550
- }
23551
- function toClassifiedDataRow(input2, id) {
23552
- return {
23553
- id,
23554
- class: input2.class,
23555
- label: input2.label ?? null,
23556
- attributes: input2.attributes ? JSON.stringify(input2.attributes) : null
23557
- };
23558
- }
23559
- function toInspectionDefinitionRow(input2, id) {
23560
- return {
23561
- id,
23562
- ruleId: input2.ruleId,
23563
- name: input2.name,
23564
- category: input2.category,
23565
- severity: input2.severity,
23566
- definition: input2.definition,
23567
- version: input2.version
23568
- };
23569
- }
23570
- function toInspectionFindingRow(input2) {
23571
- return {
23572
- id: input2.id,
23573
- auditEventId: input2.auditEventId,
23574
- inspectionDefinitionId: input2.inspectionDefinitionId,
23575
- classifiedDataId: input2.classifiedDataId ?? null,
23576
- spanStart: input2.span.start,
23577
- spanEnd: input2.span.end,
23578
- maskedMatch: input2.maskedMatch,
23579
- actionTaken: input2.actionTaken,
23580
- confidence: input2.confidence,
23581
- findingKey: input2.findingKey ?? null,
23582
- firstDetectedAt: input2.firstDetectedAt ? isoToEpochMillis(input2.firstDetectedAt) : null
23583
- };
23584
- }
23585
- function toCaptureAttributes(event) {
23586
- const metadata = event.metadata;
23587
- return {
23588
- source_tool: event.sourceTool,
23589
- ...metadata?.repo !== void 0 ? { repo: metadata.repo } : {},
23590
- ...metadata?.filePath !== void 0 ? { file_path: metadata.filePath } : {},
23591
- ...metadata?.toolName !== void 0 ? { tool_name: metadata.toolName } : {},
23592
- ...metadata?.gitignored !== void 0 ? { gitignored: metadata.gitignored } : {},
23593
- ...metadata?.wholeFile !== void 0 ? { whole_file: metadata.wholeFile } : {},
23594
- ...metadata?.correlationId !== void 0 ? { correlation_id: metadata.correlationId } : {},
23595
- ...metadata?.traceId !== void 0 ? { trace_id: metadata.traceId } : {},
23596
- ...metadata?.exceptionIds !== void 0 ? { exception_ids: metadata.exceptionIds } : {},
23597
- ...metadata?.inspectionMs !== void 0 ? { inspection_ms: metadata.inspectionMs } : {},
23598
- // `model`/`turnIndex` have no dedicated CaptureAttributes field (no writer
23599
- // has ever populated either), but every legacy metadata key still rides
23600
- // the bag rather than being silently dropped — CaptureAttributes'
23601
- // `.catchall(z.unknown())` carries the long tail.
23602
- ...metadata?.model !== void 0 ? { model: metadata.model } : {},
23603
- ...metadata?.turnIndex !== void 0 ? { turn_index: metadata.turnIndex } : {}
23604
- };
23605
- }
23606
- function captureDefinitionVersion(finding2) {
23607
- return `capture/${finding2.category}/${finding2.severity}`;
23608
- }
23609
- function toCaptureDefinitionInput(finding2) {
23610
- return {
23611
- ruleId: finding2.ruleId,
23612
- version: captureDefinitionVersion(finding2),
23613
- name: finding2.ruleId,
23614
- category: finding2.category,
23615
- severity: finding2.severity,
23616
- definition: JSON.stringify({ ruleId: finding2.ruleId })
23617
- };
23618
- }
23619
-
23620
- // ../../packages/schema/src/zod/managed.ts
23621
- var MANAGED_SETTINGS_FILENAME = "managed-settings.json";
23622
- var MANAGED_SETTINGS_SPEC_VERSION = 1;
23623
- var ManagedSettingKey = external_exports.enum([
23624
- "runMode",
23625
- "historicalAccess",
23626
- "vaultConsent",
23627
- "vaultKeyCustody",
23628
- "vaultInlineReveal",
23629
- "modelJudgeConsent",
23630
- "dataSharesInPlace"
23631
- ]).meta({ id: "ManagedSettingKey" });
23632
- var ManagedSettingsValues = external_exports.object({
23633
- runMode: external_exports.enum(["standalone", "attached"]).optional(),
23634
- controlPlane: external_exports.object({
23635
- endpoint: external_exports.string().min(1),
23636
- label: external_exports.string().min(1).optional()
23637
- }).optional(),
23638
- historicalAccess: external_exports.enum(["full", "session-only"]).optional(),
23639
- vaultConsent: external_exports.boolean().optional(),
23640
- vaultKeyCustody: external_exports.enum(["file", "keychain"]).optional(),
23641
- vaultInlineReveal: external_exports.enum(["masked", "full", "off"]).optional(),
23642
- modelJudgeConsent: external_exports.boolean().optional(),
23643
- dataSharesInPlace: external_exports.boolean().optional()
23644
- }).meta({ id: "ManagedSettingsValues" });
23645
- var ManagedSettings = external_exports.object({
23646
- specVersion: external_exports.number().int().positive().default(MANAGED_SETTINGS_SPEC_VERSION),
23647
- // Shown on every locked control, so the user can tell an administrative
23648
- // decision from a bug. Absent renders as a generic "your organization".
23649
- organization: external_exports.string().min(1).optional(),
23650
- // What the administrator pinned.
23651
- values: ManagedSettingsValues.default({}),
23652
- // Which of those the user may not change. A key here with no matching value
23653
- // freezes whatever the user last chose; a value with no lock is a DEFAULT
23654
- // the user may still override. The two are separable on purpose.
23655
- lockedFields: external_exports.array(ManagedSettingKey).default([])
23656
- }).meta({ id: "ManagedSettings" });
23657
-
23658
23340
  // ../../packages/schema/src/zod/policy.ts
23659
23341
  var PolicyScope = external_exports.enum(["global", "repo", "user"]).meta({ id: "PolicyScope" });
23660
23342
  var PolicyTarget = external_exports.union([external_exports.object({ ruleId: external_exports.string() }), external_exports.object({ category: DetectionCategory })]).meta({ id: "PolicyTarget" });
23343
+ var PolicyKind = external_exports.enum(["builtin", "custom"]).meta({ id: "PolicyKind" });
23344
+ var PolicyProvenance = external_exports.enum(["builtin", "authored"]).meta({ id: "PolicyProvenance" });
23661
23345
  var Policy = external_exports.object({
23662
23346
  id: external_exports.guid(),
23663
23347
  scope: PolicyScope,
@@ -23667,7 +23351,27 @@ var Policy = external_exports.object({
23667
23351
  customKeywords: external_exports.array(external_exports.string()).optional(),
23668
23352
  // Display name — optional so older policy rows without name still parse.
23669
23353
  // Added for the findings API (policy.name column migration).
23670
- name: external_exports.string().optional()
23354
+ name: external_exports.string().optional(),
23355
+ // Whether an AUTHORED policy governs this row's target — not a claim about
23356
+ // which row this is. A producer that collapses several rows onto one target
23357
+ // must carry the marker onto whichever row survives, or the collapse decides
23358
+ // the answer; a survivor may therefore be a built-in expansion still marked
23359
+ // 'authored' because an authored sibling targeted the same thing.
23360
+ // Optional so an older producer — and an older on-disk cache — still parses;
23361
+ // absent reads as 'builtin', which is the behaviour that predates the field.
23362
+ //
23363
+ // Deliberately NOT `kind`/PolicyKind: that name and that enum answer which
23364
+ // built-in archetype catalog entry a policy is, which every catalog surface
23365
+ // reads and which a caller may state. This one is a statement the PRODUCER
23366
+ // of a bundle makes about a row, and only the bundle builder ever stamps it
23367
+ // — the CRUD routes neither accept nor set it.
23368
+ //
23369
+ // A device consumes this in exactly one direction: an 'authored' policy
23370
+ // arriving from a control plane marks the rules it targets as not
23371
+ // locally re-assignable. That can only ever ADD a refusal, never relax one,
23372
+ // which is what makes it safe to honour from an unsigned cache — the same
23373
+ // test `prohibitedModels` passes and `reversibleRuleIds` fails.
23374
+ provenance: PolicyProvenance.optional()
23671
23375
  }).meta({ id: "Policy" });
23672
23376
  var PolicyBundle = external_exports.object({
23673
23377
  version: external_exports.string(),
@@ -23719,6 +23423,12 @@ var PolicyBundle = external_exports.object({
23719
23423
  customKeywords: external_exports.array(external_exports.string()),
23720
23424
  fetchedAt: external_exports.iso.datetime()
23721
23425
  }).meta({ id: "PolicyBundle" });
23426
+ var POLICY_BUNDLE_SHAPE_ID = [
23427
+ ...Object.keys(PolicyBundle.shape),
23428
+ ...Object.keys(Policy.shape).map((key) => `policies.${key}`),
23429
+ ...PolicyTarget.options.flatMap((member) => "shape" in member ? Object.keys(member.shape) : []).map((key) => `policies.target.${key}`),
23430
+ ...Object.keys(ExceptionBundleEntry.shape).map((key) => `exceptions.${key}`)
23431
+ ].sort().join(",");
23722
23432
  var OBSERVE_ONLY_CATEGORIES = ["config"];
23723
23433
  var ENFORCEABLE_CATEGORIES = DetectionCategory.options.filter((c) => !OBSERVE_ONLY_CATEGORIES.includes(c));
23724
23434
  var CATEGORY_PEAK_SEVERITY = {
@@ -23739,9 +23449,11 @@ function severityFloorPolicy(category) {
23739
23449
  const peak = CATEGORY_PEAK_SEVERITY[category];
23740
23450
  return peak === "critical" || peak === "high" ? "warn" : "monitor";
23741
23451
  }
23742
- var PolicyKind = external_exports.enum(["builtin", "custom"]).meta({ id: "PolicyKind" });
23743
23452
  var KNOWN_BUILTIN_IDS = ["monitor", "warn", "redact", "vault", "block"];
23744
23453
  var BuiltinPolicyId = external_exports.enum(KNOWN_BUILTIN_IDS).meta({ id: "BuiltinPolicyId" });
23454
+ var RedactFallback = BuiltinPolicyId.extract(["monitor", "warn", "block"]).meta({
23455
+ id: "RedactFallback"
23456
+ });
23745
23457
  var BUILTIN_ORDER = KNOWN_BUILTIN_IDS;
23746
23458
  var BUILTIN_POLICY_SPECS = {
23747
23459
  monitor: {
@@ -23778,6 +23490,42 @@ var BUILTIN_POLICY_SPECS = {
23778
23490
  function builtinPolicyToAction(id) {
23779
23491
  return BUILTIN_POLICY_SPECS[id].action;
23780
23492
  }
23493
+ var PALETTE_WEAKEST_FIRST = [
23494
+ ...new Set(KNOWN_BUILTIN_IDS.map(builtinPolicyToAction))
23495
+ ];
23496
+ var BELOW_PALETTE = ACTION_TAKEN_KEYS.filter(
23497
+ (action) => !PALETTE_WEAKEST_FIRST.includes(action)
23498
+ );
23499
+ var ACTION_STRENGTH_ORDER = [
23500
+ ...BELOW_PALETTE,
23501
+ ...PALETTE_WEAKEST_FIRST
23502
+ ];
23503
+ function actionRank(action) {
23504
+ return ACTION_STRENGTH_ORDER.indexOf(action);
23505
+ }
23506
+ function isActionAtLeast(action, floor) {
23507
+ return actionRank(action) >= actionRank(floor);
23508
+ }
23509
+ function strongerAction(a, b) {
23510
+ return actionRank(a) >= actionRank(b) ? a : b;
23511
+ }
23512
+ function weakestBuiltinAtLeast(floor) {
23513
+ return KNOWN_BUILTIN_IDS.find((id) => isActionAtLeast(builtinPolicyToAction(id), floor)) ?? "block";
23514
+ }
23515
+ var PackPolicyFloor = external_exports.object({
23516
+ /**
23517
+ * The weakest archetype the device may assign. Stated as a BuiltinPolicyId
23518
+ * rather than a raw ActionTaken because that is the vocabulary the user
23519
+ * picks from — a floor a UI cannot name is one it cannot explain.
23520
+ */
23521
+ floor: BuiltinPolicyId,
23522
+ /**
23523
+ * True when the organization AUTHORED a policy governing this pack rather
23524
+ * than stating a minimum: it gave the answer, so the pack is not
23525
+ * re-assignable locally in either direction.
23526
+ */
23527
+ locked: external_exports.boolean()
23528
+ }).describe("PackPolicyFloor");
23781
23529
  var CATEGORY_EXPRESSIBLE_IDS = KNOWN_BUILTIN_IDS.filter(
23782
23530
  (id) => !BUILTIN_POLICY_SPECS[id].reversible
23783
23531
  );
@@ -23835,6 +23583,402 @@ var PolicyStatsResponse = external_exports.object({
23835
23583
  detectionsGoverned: external_exports.number().int().nonnegative()
23836
23584
  }).meta({ id: "PolicyStatsResponse" });
23837
23585
 
23586
+ // ../../packages/schema/src/zod/vault.ts
23587
+ var POINTER_FORMAT_VERSION = 2;
23588
+ var CATEGORY_ALTERNATION = DetectionCategory.options.join("|");
23589
+ var POINTER_TOKEN_PATTERN = new RegExp(
23590
+ `\\[\\[aka:(?:${CATEGORY_ALTERNATION}):[A-Z2-7]{2,7}\\.[A-Z2-7]{26}\\.[A-Z2-7]{16}\\]\\]`
23591
+ );
23592
+ var POINTER_TOKEN_ANCHORED = new RegExp(`^${POINTER_TOKEN_PATTERN.source}$`);
23593
+ function pointerTokenScanner() {
23594
+ return new RegExp(POINTER_TOKEN_PATTERN.source, "g");
23595
+ }
23596
+ var PointerToken = external_exports.string().regex(POINTER_TOKEN_ANCHORED);
23597
+ var ParsedPointer = external_exports.object({
23598
+ category: DetectionCategory,
23599
+ keyVersion: external_exports.number().int().positive(),
23600
+ pointerId: external_exports.string(),
23601
+ tag: external_exports.string()
23602
+ });
23603
+ var VaultEntry = external_exports.object({
23604
+ pointerId: external_exports.string(),
23605
+ // The keyed HMAC of the raw value under `exception.key`, and the epoch it was
23606
+ // derived under. This is what a reveal-to-model grant matches on, and it rotates
23607
+ // independently of the vault encryption key below.
23608
+ valueFingerprint: external_exports.string().regex(/^[0-9a-f]{64}$/),
23609
+ fingerprintKeyVersion: external_exports.number().int().positive(),
23610
+ // The vault-key epoch this row's ciphertext was sealed under.
23611
+ keyVersion: external_exports.number().int().positive(),
23612
+ // Fixed at first mint and never updated: the same value detected later under a
23613
+ // different rule's category keeps the category it was minted with, so one
23614
+ // value always produces exactly one wire token.
23615
+ category: DetectionCategory,
23616
+ ruleId: external_exports.string(),
23617
+ // Partial-reveal preview for badges and listings. Never the raw value.
23618
+ maskedMatch: external_exports.string(),
23619
+ provider: external_exports.string().optional(),
23620
+ ciphertext: external_exports.string(),
23621
+ nonce: external_exports.string(),
23622
+ authTag: external_exports.string(),
23623
+ // How many times this value has been detected on this machine — the reuse
23624
+ // signal the vault dashboard reads. Distinct from VaultDeref.pointerCount.
23625
+ occurrenceCount: external_exports.number().int().nonnegative(),
23626
+ // True when a PERSON asked for this value to be replaced — the surfaced-
23627
+ // secrets strike — rather than a pack enforcing its assignment. One value is
23628
+ // one row however many paths vault it, so this is what tells a policy sweep
23629
+ // that the row carries somebody's own instruction and not just an assignment
23630
+ // that has since been lowered. STICKY and MONOTONIC: a later automatic
23631
+ // vaulting of the same value must never clear it — what the user said about
23632
+ // the value does not expire.
23633
+ userAuthorized: external_exports.boolean(),
23634
+ firstSeen: external_exports.string(),
23635
+ lastSeen: external_exports.string()
23636
+ });
23637
+ var PointerDescriptor = external_exports.object({
23638
+ category: DetectionCategory,
23639
+ provider: external_exports.string().optional(),
23640
+ maskedMatch: external_exports.string(),
23641
+ occurrences: external_exports.number().int().nonnegative(),
23642
+ firstSeen: external_exports.string(),
23643
+ lastSeen: external_exports.string()
23644
+ });
23645
+ var PointerIdentity = external_exports.object({
23646
+ ruleId: external_exports.string(),
23647
+ valueFingerprint: external_exports.string().regex(/^[0-9a-f]{64}$/),
23648
+ fingerprintKeyVersion: external_exports.number().int().positive()
23649
+ });
23650
+ var DetokenizeTarget = external_exports.enum(["human", "model"]);
23651
+ var VaultDerefReason = external_exports.enum([
23652
+ "display",
23653
+ "explicit-reveal",
23654
+ "view-render",
23655
+ "model-input",
23656
+ "remediation",
23657
+ "purge"
23658
+ ]);
23659
+ var VaultDerefOutcome = external_exports.enum(["revealed", "refused", "unavailable"]);
23660
+ var VaultDeref = external_exports.object({
23661
+ id: external_exports.guid(),
23662
+ pointerId: external_exports.string(),
23663
+ at: external_exports.string(),
23664
+ target: DetokenizeTarget,
23665
+ reason: VaultDerefReason,
23666
+ outcome: VaultDerefOutcome,
23667
+ // Present only on a model-target crossing that a reveal grant authorized.
23668
+ grantId: external_exports.string().optional(),
23669
+ // How many pointers ONE batched render resolved. 1 for unbatched rows. Named
23670
+ // apart from VaultEntry.occurrenceCount, which counts detections of a value.
23671
+ pointerCount: external_exports.number().int().positive().default(1)
23672
+ });
23673
+ var VaultSightingKind = external_exports.enum([
23674
+ "prompt",
23675
+ "tool-input",
23676
+ "tool-output",
23677
+ "file",
23678
+ "transcript"
23679
+ ]);
23680
+ var VaultSighting = external_exports.object({
23681
+ location: external_exports.string(),
23682
+ kind: VaultSightingKind,
23683
+ firstSeen: external_exports.string(),
23684
+ lastSeen: external_exports.string()
23685
+ });
23686
+ var VaultInventoryEntry = external_exports.object({
23687
+ pointerId: external_exports.string(),
23688
+ category: DetectionCategory,
23689
+ provider: external_exports.string().optional(),
23690
+ maskedMatch: external_exports.string(),
23691
+ occurrences: external_exports.number().int().nonnegative(),
23692
+ firstSeen: external_exports.string(),
23693
+ lastSeen: external_exports.string(),
23694
+ // The active reveal-to-model grant covering this value, when one exists —
23695
+ // the inventory badges it, the row links to revocation.
23696
+ revealGrantId: external_exports.string().nullable(),
23697
+ sightings: external_exports.array(VaultSighting)
23698
+ });
23699
+ var DEFAULT_VAULT_INVENTORY_LIMIT = 50;
23700
+ var DEFAULT_VAULT_DEREFS_LIMIT = 50;
23701
+ var MAX_VAULT_PAGE_LIMIT = 200;
23702
+ var ListVaultInventoryQuery = external_exports.object({
23703
+ limit: external_exports.coerce.number().int().min(1).max(MAX_VAULT_PAGE_LIMIT).optional(),
23704
+ // Opaque; names the last row of the page just served.
23705
+ cursor: external_exports.string().optional()
23706
+ });
23707
+ var ListVaultInventoryResponse = external_exports.object({
23708
+ // Vaulted values across the whole store, not just this page — cursor-
23709
+ // independent, so paging never changes what the count claims.
23710
+ totals: external_exports.object({ values: external_exports.number().int().nonnegative() }),
23711
+ items: external_exports.array(VaultInventoryEntry),
23712
+ // `null` once the last page is reached.
23713
+ nextCursor: external_exports.string().nullable()
23714
+ });
23715
+ var ListVaultReuseQuery = external_exports.object({
23716
+ limit: external_exports.coerce.number().int().min(1).max(MAX_VAULT_PAGE_LIMIT).optional(),
23717
+ cursor: external_exports.string().optional()
23718
+ });
23719
+ var ListVaultReuseResponse = external_exports.object({
23720
+ // Reused values across the whole store — the number the section's claim
23721
+ // ("values detected in more than one place") is about.
23722
+ totals: external_exports.object({ reused: external_exports.number().int().nonnegative() }),
23723
+ items: external_exports.array(VaultInventoryEntry),
23724
+ nextCursor: external_exports.string().nullable()
23725
+ });
23726
+ var ListVaultDerefsQuery = external_exports.object({
23727
+ // Include the batched, high-volume reasons (display, view-render). Omitted
23728
+ // hides them and counts them into `hiddenBatched` instead, so the model
23729
+ // crossings stay visible. A real boolean, not `z.stringbool()`: this arrives
23730
+ // over a Server Action, which preserves the type, never as a URL param.
23731
+ includeBatched: external_exports.boolean().optional(),
23732
+ limit: external_exports.coerce.number().int().min(1).max(MAX_VAULT_PAGE_LIMIT).optional(),
23733
+ cursor: external_exports.string().optional()
23734
+ });
23735
+ var ListVaultDerefsResponse = external_exports.object({
23736
+ items: external_exports.array(VaultDeref),
23737
+ nextCursor: external_exports.string().nullable(),
23738
+ // Display/view-render rows the query hid, over the WHOLE trail rather than
23739
+ // this page — it is the count the "N hidden" line and its toggle speak for.
23740
+ // Always 0 when `includeBatched` was set, since nothing was hidden.
23741
+ hiddenBatched: external_exports.number().int().nonnegative()
23742
+ });
23743
+ var VaultKeyCustody = external_exports.string();
23744
+ var VaultInlineReveal = external_exports.enum(["masked", "full", "off"]);
23745
+ var VAULT_CONSENT_VERSION = 1;
23746
+ var VaultConsent = external_exports.object({
23747
+ acknowledgedAt: external_exports.iso.datetime(),
23748
+ version: external_exports.number().int().positive()
23749
+ });
23750
+
23751
+ // ../../packages/schema/src/zod/local.ts
23752
+ var WORKSPACE_SETTINGS_SPEC_VERSION = 7;
23753
+ var MODEL_JUDGE_PAYLOAD_VERSION = 1;
23754
+ var HISTORY_SYNC_PAYLOAD_VERSION = 2;
23755
+ var RunMode = external_exports.enum(["standalone", "attached"]);
23756
+ var ControlPlaneConnection = external_exports.object({
23757
+ endpoint: external_exports.string().min(1),
23758
+ // Display name for the deployment, shown instead of the raw endpoint.
23759
+ label: external_exports.string().min(1).optional(),
23760
+ attachedAt: external_exports.iso.datetime()
23761
+ }).meta({ id: "ControlPlaneConnection" });
23762
+ var SimpleDetectionPolicy = external_exports.enum(["redact", "warn"]);
23763
+ var HistoricalAccess = external_exports.enum(["full", "session-only"]);
23764
+ var ModelJudgeConsent = external_exports.object({
23765
+ acknowledgedAt: external_exports.iso.datetime(),
23766
+ payloadVersion: external_exports.number().int().positive()
23767
+ });
23768
+ var HistorySyncConsent = external_exports.object({
23769
+ acknowledgedAt: external_exports.iso.datetime(),
23770
+ payloadVersion: external_exports.number().int().positive(),
23771
+ endpoint: external_exports.string()
23772
+ });
23773
+ function isHistorySyncConsentValid(consent, endpoint) {
23774
+ if (consent === void 0 || endpoint === void 0) return false;
23775
+ return consent.payloadVersion === HISTORY_SYNC_PAYLOAD_VERSION && consent.endpoint === endpoint;
23776
+ }
23777
+ var WorkspaceSettings = external_exports.object({
23778
+ specVersion: external_exports.number().int().positive().default(WORKSPACE_SETTINGS_SPEC_VERSION),
23779
+ runMode: RunMode.default("standalone"),
23780
+ // Present only while attached; a detach clears it. Its presence is what makes
23781
+ // `runMode: 'attached'` mean anything — see isAttached.
23782
+ controlPlane: ControlPlaneConnection.optional(),
23783
+ policy: SimpleDetectionPolicy.default("redact"),
23784
+ // Consent for scanning pre-install surfaces; opt-in (see HistoricalAccess).
23785
+ historicalAccess: HistoricalAccess.default("session-only"),
23786
+ // In-place egress extraction on the scan paths; disable to stop all Data
23787
+ // Shares writes.
23788
+ dataSharesInPlace: external_exports.boolean().default(true),
23789
+ // Consent to keep a RECOVERABLE encrypted copy of detected values in the local
23790
+ // vault, instead of destroying them. Absent by default: this is a custody
23791
+ // change from one-way redaction, so it is never an assumed grant on upgrade.
23792
+ // Revoking stops future vaulting; it does not erase what is already stored —
23793
+ // purging the vault is the eraser.
23794
+ vaultConsent: VaultConsent.optional(),
23795
+ // Where the vault master key lives.
23796
+ vaultKeyCustody: VaultKeyCustody.default("file"),
23797
+ // How a pointer renders in assistant prose on screen (see VaultInlineReveal).
23798
+ vaultInlineReveal: VaultInlineReveal.default("masked"),
23799
+ // What a `redact` policy degrades to on a FIELD the host cannot rewrite in
23800
+ // place. Not a handling policy: the policy has already resolved to redact,
23801
+ // and this only says what happens when the host offers no channel to carry it
23802
+ // out — Antigravity's PreToolUse has no updatedInput at all, and Codex and
23803
+ // Claude Code decline to mask a field that EXECUTES because masking would
23804
+ // change what runs. Per FIELD rather than per host, so a host that can
23805
+ // rewrite some inputs keeps true redaction on those.
23806
+ //
23807
+ // Spelled in the built-in policy vocabulary rather than as a fresh enum, so
23808
+ // an attached machine's merge is `strongerAction` over the one action ladder
23809
+ // and no second rank order exists to drift from it. 'deny' is a host wire
23810
+ // word and stays out of the stored value.
23811
+ redactFallback: RedactFallback.default("warn"),
23812
+ // Absent until /aka:setup completes; its presence is what "onboarded" means.
23813
+ onboardedAt: external_exports.iso.datetime().optional(),
23814
+ // Records that the user consented to sending findings to the model API for
23815
+ // the /aka:setup judge, along with the payload-shape version they agreed to.
23816
+ // Absent until granted; a stale payloadVersion means the consent no longer
23817
+ // covers the current payload and must be re-granted.
23818
+ modelJudgeConsent: ModelJudgeConsent.optional(),
23819
+ // Records that the user consented to the DEFERRED send — the outbox — along
23820
+ // with the payload shape and the endpoint they agreed to. Since payload v2
23821
+ // that covers both the pre-attach backlog and undelivered captures (which
23822
+ // carry prompt/reply text in `content`); the key name predates the widening.
23823
+ // Absent until granted, and a grant for a different endpoint or an older
23824
+ // payload no longer counts.
23825
+ historySyncConsent: HistorySyncConsent.optional()
23826
+ });
23827
+ function defaultWorkspaceSettings() {
23828
+ return WorkspaceSettings.parse({});
23829
+ }
23830
+ function isAttached(settings) {
23831
+ return settings.runMode === "attached" && settings.controlPlane !== void 0;
23832
+ }
23833
+ function toInventoryRow(input2, id, now) {
23834
+ return {
23835
+ id,
23836
+ objectType: input2.objectType,
23837
+ location: input2.location ?? null,
23838
+ title: input2.title ?? null,
23839
+ hostId: input2.hostId ?? null,
23840
+ attributes: JSON.stringify(input2.attributes),
23841
+ firstSeen: now,
23842
+ lastSeen: now
23843
+ };
23844
+ }
23845
+ function toSourceProjectRow(input2, id, now) {
23846
+ return {
23847
+ id,
23848
+ url: input2.url,
23849
+ name: input2.name ?? null,
23850
+ attributes: JSON.stringify(input2.attributes),
23851
+ firstSeen: now,
23852
+ lastSeen: now
23853
+ };
23854
+ }
23855
+ function toAuditEventRow(input2) {
23856
+ return {
23857
+ id: input2.id,
23858
+ parentId: input2.parentId ?? null,
23859
+ rootSessionId: input2.rootSessionId ?? null,
23860
+ eventType: input2.eventType,
23861
+ hostId: input2.hostId ?? null,
23862
+ harnessId: input2.harnessId ?? null,
23863
+ sourceProjectId: input2.sourceProjectId ?? null,
23864
+ startedAt: isoToEpochMillis(input2.startedAt),
23865
+ endedAt: input2.endedAt ? isoToEpochMillis(input2.endedAt) : null,
23866
+ severity: input2.severity ?? null,
23867
+ priority: input2.priority ?? null,
23868
+ content: input2.content ?? null,
23869
+ contentHash: input2.contentHash ?? null,
23870
+ attributes: input2.attributes ? JSON.stringify(input2.attributes) : null
23871
+ };
23872
+ }
23873
+ function toClassifiedDataRow(input2, id) {
23874
+ return {
23875
+ id,
23876
+ class: input2.class,
23877
+ label: input2.label ?? null,
23878
+ attributes: input2.attributes ? JSON.stringify(input2.attributes) : null
23879
+ };
23880
+ }
23881
+ function toInspectionDefinitionRow(input2, id) {
23882
+ return {
23883
+ id,
23884
+ ruleId: input2.ruleId,
23885
+ name: input2.name,
23886
+ category: input2.category,
23887
+ severity: input2.severity,
23888
+ definition: input2.definition,
23889
+ version: input2.version
23890
+ };
23891
+ }
23892
+ function toInspectionFindingRow(input2) {
23893
+ return {
23894
+ id: input2.id,
23895
+ auditEventId: input2.auditEventId,
23896
+ inspectionDefinitionId: input2.inspectionDefinitionId,
23897
+ classifiedDataId: input2.classifiedDataId ?? null,
23898
+ spanStart: input2.span.start,
23899
+ spanEnd: input2.span.end,
23900
+ maskedMatch: input2.maskedMatch,
23901
+ actionTaken: input2.actionTaken,
23902
+ confidence: input2.confidence,
23903
+ findingKey: input2.findingKey ?? null,
23904
+ firstDetectedAt: input2.firstDetectedAt ? isoToEpochMillis(input2.firstDetectedAt) : null
23905
+ };
23906
+ }
23907
+ function toCaptureAttributes(event) {
23908
+ const metadata = event.metadata;
23909
+ return {
23910
+ source_tool: event.sourceTool,
23911
+ ...metadata?.repo !== void 0 ? { repo: metadata.repo } : {},
23912
+ ...metadata?.filePath !== void 0 ? { file_path: metadata.filePath } : {},
23913
+ ...metadata?.toolName !== void 0 ? { tool_name: metadata.toolName } : {},
23914
+ ...metadata?.gitignored !== void 0 ? { gitignored: metadata.gitignored } : {},
23915
+ ...metadata?.wholeFile !== void 0 ? { whole_file: metadata.wholeFile } : {},
23916
+ ...metadata?.correlationId !== void 0 ? { correlation_id: metadata.correlationId } : {},
23917
+ ...metadata?.traceId !== void 0 ? { trace_id: metadata.traceId } : {},
23918
+ ...metadata?.exceptionIds !== void 0 ? { exception_ids: metadata.exceptionIds } : {},
23919
+ ...metadata?.inspectionMs !== void 0 ? { inspection_ms: metadata.inspectionMs } : {},
23920
+ // `model`/`turnIndex` have no dedicated CaptureAttributes field (no writer
23921
+ // has ever populated either), but every legacy metadata key still rides
23922
+ // the bag rather than being silently dropped — CaptureAttributes'
23923
+ // `.catchall(z.unknown())` carries the long tail.
23924
+ ...metadata?.model !== void 0 ? { model: metadata.model } : {},
23925
+ ...metadata?.turnIndex !== void 0 ? { turn_index: metadata.turnIndex } : {}
23926
+ };
23927
+ }
23928
+ function captureDefinitionVersion(finding2) {
23929
+ return `capture/${finding2.category}/${finding2.severity}`;
23930
+ }
23931
+ function toCaptureDefinitionInput(finding2) {
23932
+ return {
23933
+ ruleId: finding2.ruleId,
23934
+ version: captureDefinitionVersion(finding2),
23935
+ name: finding2.ruleId,
23936
+ category: finding2.category,
23937
+ severity: finding2.severity,
23938
+ definition: JSON.stringify({ ruleId: finding2.ruleId })
23939
+ };
23940
+ }
23941
+
23942
+ // ../../packages/schema/src/zod/managed.ts
23943
+ var MANAGED_SETTINGS_FILENAME = "managed-settings.json";
23944
+ var MANAGED_SETTINGS_SPEC_VERSION = 1;
23945
+ var ManagedSettingKey = external_exports.enum([
23946
+ "runMode",
23947
+ "historicalAccess",
23948
+ "vaultConsent",
23949
+ "vaultKeyCustody",
23950
+ "vaultInlineReveal",
23951
+ "modelJudgeConsent",
23952
+ "dataSharesInPlace",
23953
+ "redactFallback"
23954
+ ]).meta({ id: "ManagedSettingKey" });
23955
+ var ManagedSettingsValues = external_exports.object({
23956
+ runMode: external_exports.enum(["standalone", "attached"]).optional(),
23957
+ controlPlane: external_exports.object({
23958
+ endpoint: external_exports.string().min(1),
23959
+ label: external_exports.string().min(1).optional()
23960
+ }).optional(),
23961
+ historicalAccess: external_exports.enum(["full", "session-only"]).optional(),
23962
+ vaultConsent: external_exports.boolean().optional(),
23963
+ vaultKeyCustody: external_exports.enum(["file", "keychain"]).optional(),
23964
+ vaultInlineReveal: external_exports.enum(["masked", "full", "off"]).optional(),
23965
+ modelJudgeConsent: external_exports.boolean().optional(),
23966
+ dataSharesInPlace: external_exports.boolean().optional(),
23967
+ redactFallback: RedactFallback.optional()
23968
+ }).meta({ id: "ManagedSettingsValues" });
23969
+ var ManagedSettings = external_exports.object({
23970
+ specVersion: external_exports.number().int().positive().default(MANAGED_SETTINGS_SPEC_VERSION),
23971
+ // Shown on every locked control, so the user can tell an administrative
23972
+ // decision from a bug. Absent renders as a generic "your organization".
23973
+ organization: external_exports.string().min(1).optional(),
23974
+ // What the administrator pinned.
23975
+ values: ManagedSettingsValues.default({}),
23976
+ // Which of those the user may not change. A key here with no matching value
23977
+ // freezes whatever the user last chose; a value with no lock is a DEFAULT
23978
+ // the user may still override. The two are separable on purpose.
23979
+ lockedFields: external_exports.array(ManagedSettingKey).default([])
23980
+ }).meta({ id: "ManagedSettings" });
23981
+
23838
23982
  // ../../packages/schema/src/zod/project-files.ts
23839
23983
  var ProjectFileInput = external_exports.object({
23840
23984
  path: external_exports.string().min(1),
@@ -24080,10 +24224,12 @@ var DismissRecommendedActionResponse = external_exports.object({ id: external_ex
24080
24224
  var RecommendedActionIdParam = external_exports.object({ id: external_exports.string() });
24081
24225
 
24082
24226
  // ../../packages/schema/src/zod/settings-action.ts
24227
+ var HistorySyncConsentChoice = external_exports.enum(["granted", "revoked", "unchanged"]).meta({ id: "HistorySyncConsentChoice" });
24228
+ var ModelJudgeConsentChoice = external_exports.enum(["granted", "revoked", "unchanged"]).meta({ id: "ModelJudgeConsentChoice" });
24083
24229
  var SaveSettingsInput = external_exports.object({
24084
24230
  historicalAccess: external_exports.string(),
24085
- modelJudgeConsent: external_exports.boolean(),
24086
- historySyncConsent: external_exports.boolean(),
24231
+ modelJudgeConsent: ModelJudgeConsentChoice,
24232
+ historySyncConsent: HistorySyncConsentChoice,
24087
24233
  vaultConsent: external_exports.string(),
24088
24234
  vaultInlineReveal: external_exports.string()
24089
24235
  });
@@ -24233,9 +24379,9 @@ function deriveReviewReasons(trust, transports) {
24233
24379
  if (transports.includes("http") || transports.includes("ws")) reasons.push("plaintext_transport");
24234
24380
  return reasons;
24235
24381
  }
24236
- function buildReviewInfo(trust, transports) {
24382
+ function buildReviewInfo(trust, transports, decided) {
24237
24383
  const reasons = deriveReviewReasons(trust, transports);
24238
- return { needsReview: reasons.length > 0, reasons };
24384
+ return { needsReview: reasons.length > 0 && !decided, reasons };
24239
24385
  }
24240
24386
  function distinctTransports(transports) {
24241
24387
  return Array.from(new Set(transports));
@@ -24437,8 +24583,8 @@ function readControlPlaneCredential(settingsDir2, connection) {
24437
24583
  }
24438
24584
 
24439
24585
  // ../../packages/persistence/src/database.ts
24440
- import { randomUUID as randomUUID10 } from "crypto";
24441
- import { join as join4, sep } from "path";
24586
+ import { randomUUID as randomUUID11 } from "crypto";
24587
+ import { dirname as dirname2, join as join7, sep } from "path";
24442
24588
  import { DatabaseSync } from "node:sqlite";
24443
24589
 
24444
24590
  // ../../packages/persistence/src/ids.ts
@@ -24693,6 +24839,10 @@ function allRows(stmt, params) {
24693
24839
  if (Array.isArray(params)) return stmt.all(...params);
24694
24840
  return stmt.all(params);
24695
24841
  }
24842
+ function* iterateRows(stmt, params) {
24843
+ const rows = params === void 0 ? stmt.iterate() : Array.isArray(params) ? stmt.iterate(...params) : stmt.iterate(params);
24844
+ for (const row of rows) yield row;
24845
+ }
24696
24846
  function getRow(stmt, params) {
24697
24847
  if (params === void 0) return stmt.get();
24698
24848
  if (Array.isArray(params)) return stmt.get(...params);
@@ -25161,10 +25311,17 @@ function ensureSyncedAtColumn(db, table) {
25161
25311
  if (!columns.includes("sync_claimed_at")) {
25162
25312
  db.exec(`ALTER TABLE ${table} ADD COLUMN sync_claimed_at integer`);
25163
25313
  }
25314
+ if (!columns.includes("outbox_owed")) {
25315
+ db.exec(`ALTER TABLE ${table} ADD COLUMN outbox_owed integer`);
25316
+ }
25164
25317
  db.exec(
25165
25318
  `CREATE INDEX IF NOT EXISTS idx_audit_events_sync
25166
25319
  ON audit_events (event_type, synced_at, sync_claimed_at, started_at)`
25167
25320
  );
25321
+ db.exec(
25322
+ `CREATE INDEX IF NOT EXISTS idx_audit_outbox_owed
25323
+ ON audit_events (event_type, synced_at, sync_claimed_at, started_at) WHERE outbox_owed = 1`
25324
+ );
25168
25325
  db.exec(
25169
25326
  `CREATE INDEX IF NOT EXISTS idx_audit_claimed
25170
25327
  ON audit_events (sync_claimed_at) WHERE sync_claimed_at IS NOT NULL`
@@ -25269,7 +25426,6 @@ function decodeKeysetCursor(cursor) {
25269
25426
  // ../../packages/persistence/src/repositories/activity.ts
25270
25427
  var DAY_MS = 864e5;
25271
25428
  var LIVE_ACTIVITY_WINDOW_MS = 30 * 6e4;
25272
- var LAST_ACTIVITY_EXPR = `max(started_at, coalesce(ended_at, started_at))`;
25273
25429
  function defaultTimeZone() {
25274
25430
  try {
25275
25431
  return Intl.DateTimeFormat().resolvedOptions().timeZone;
@@ -25324,6 +25480,7 @@ var DB_EVENT_TYPE_TO_KIND = {
25324
25480
  error: "error",
25325
25481
  active: "active"
25326
25482
  };
25483
+ var TIMELINE_EVENT_TYPES = Object.keys(DB_EVENT_TYPE_TO_KIND).map((kind) => `'${kind}'`).join(", ");
25327
25484
  function safeParseStringArray(raw) {
25328
25485
  if (!raw) return [];
25329
25486
  const parsed2 = safeJson(raw, null);
@@ -25397,6 +25554,37 @@ var TIMELINE_COLUMNS = `
25397
25554
  json_extract(attributes, '$.targetId') AS target_id,
25398
25555
  json_extract(attributes, '$.internal') AS internal,
25399
25556
  json_extract(attributes, '$.flagged') AS flagged`;
25557
+ var LLM_USAGE_SELECT = `
25558
+ SELECT root_session_id AS sessionId,
25559
+ provider,
25560
+ model,
25561
+ service_tier AS serviceTier,
25562
+ coalesce(sum(input_tokens), 0) AS inputTokens,
25563
+ coalesce(sum(output_tokens), 0) AS outputTokens,
25564
+ coalesce(sum(cache_creation_input_tokens), 0) AS cacheCreationTokens,
25565
+ coalesce(sum(cache_read_input_tokens), 0) AS cacheReadTokens,
25566
+ coalesce(sum(ephemeral_1h_input_tokens), 0) AS ephemeral1hTokens,
25567
+ coalesce(sum(ephemeral_5m_input_tokens), 0) AS ephemeral5mTokens,
25568
+ coalesce(sum(web_search_requests), 0) AS webSearchRequests`;
25569
+ var LLM_USAGE_SCOPE = `event_type = 'llm_call' AND attributes IS NOT NULL AND root_session_id IS NOT NULL`;
25570
+ var LLM_USAGE_GROUP = `GROUP BY root_session_id, provider, model, service_tier`;
25571
+ function usageLeaves(rows) {
25572
+ return rows.map((row) => {
25573
+ const attributes = {
25574
+ input_tokens: row.inputTokens,
25575
+ output_tokens: row.outputTokens,
25576
+ cache_creation_input_tokens: row.cacheCreationTokens,
25577
+ cache_read_input_tokens: row.cacheReadTokens,
25578
+ ephemeral_1h_input_tokens: row.ephemeral1hTokens,
25579
+ ephemeral_5m_input_tokens: row.ephemeral5mTokens,
25580
+ web_search_requests: row.webSearchRequests
25581
+ };
25582
+ if (row.provider !== null) attributes.provider = row.provider;
25583
+ if (row.model !== null) attributes.model = row.model;
25584
+ if (row.serviceTier !== null) attributes.service_tier = row.serviceTier;
25585
+ return { sessionId: row.sessionId, attributes };
25586
+ });
25587
+ }
25400
25588
  var SESSION_ROOT = `event_type = 'session'`;
25401
25589
  var HAS_ACTIVITY = `EXISTS (
25402
25590
  SELECT 1 FROM audit_events c
@@ -25422,16 +25610,17 @@ var SqliteActivityRepository = class {
25422
25610
  const liveThreshold = this.now() - LIVE_ACTIVITY_WINDOW_MS;
25423
25611
  const liveNow = countScalar(
25424
25612
  this.db,
25425
- `SELECT count(*) AS n FROM audit_events s
25613
+ `SELECT count(*) AS n FROM audit_events s INDEXED BY sqlite_autoindex_audit_events_1
25426
25614
  WHERE s.event_type = 'session' AND s.ended_at IS NULL
25427
- AND max(
25428
- s.started_at,
25429
- coalesce(
25430
- (SELECT max(${LAST_ACTIVITY_EXPR}) FROM audit_events e WHERE e.root_session_id = s.id),
25431
- s.started_at
25432
- )
25433
- ) >= ?`,
25434
- [liveThreshold]
25615
+ AND s.id IN (
25616
+ SELECT id FROM audit_events WHERE event_type = 'session' AND started_at >= ?
25617
+ UNION
25618
+ SELECT root_session_id FROM audit_events INDEXED BY idx_audit_started_at
25619
+ WHERE started_at >= ?
25620
+ UNION
25621
+ SELECT root_session_id FROM audit_events INDEXED BY idx_audit_ended_at
25622
+ WHERE ended_at >= ?)`,
25623
+ [liveThreshold, liveThreshold, liveThreshold]
25435
25624
  );
25436
25625
  const toolCallsToday = countScalar(
25437
25626
  this.db,
@@ -25561,7 +25750,7 @@ var SqliteActivityRepository = class {
25561
25750
  this.db.prepare(
25562
25751
  `SELECT ${TIMELINE_COLUMNS}
25563
25752
  FROM audit_events
25564
- WHERE id = ? OR root_session_id = ?
25753
+ WHERE (id = ? OR root_session_id = ?) AND event_type IN (${TIMELINE_EVENT_TYPES})
25565
25754
  ORDER BY started_at ASC, id ASC`
25566
25755
  ),
25567
25756
  [sessionId, sessionId]
@@ -25574,14 +25763,14 @@ var SqliteActivityRepository = class {
25574
25763
  coalesce(sum(output_tokens), 0) AS output,
25575
25764
  coalesce(sum(cache_creation_input_tokens), 0) AS cache_creation,
25576
25765
  coalesce(sum(cache_read_input_tokens), 0) AS cache_read
25577
- FROM audit_events
25766
+ FROM audit_events INDEXED BY idx_audit_session_type
25578
25767
  WHERE root_session_id = ? AND event_type = 'llm_call'`
25579
25768
  ),
25580
25769
  [sessionId]
25581
25770
  ) ?? { input: 0, output: 0, cache_creation: 0, cache_read: 0 };
25582
25771
  const primaryModel = getRow(
25583
25772
  this.db.prepare(
25584
- `SELECT model, provider FROM audit_events
25773
+ `SELECT model, provider FROM audit_events INDEXED BY idx_audit_session_type
25585
25774
  WHERE root_session_id = ? AND event_type = 'llm_call'
25586
25775
  ORDER BY started_at ASC, id ASC
25587
25776
  LIMIT 1`
@@ -25592,7 +25781,7 @@ var SqliteActivityRepository = class {
25592
25781
  this.db.prepare(
25593
25782
  `SELECT coalesce(json_extract(attributes, '$.tool_name'), json_extract(attributes, '$.tool')) AS tool,
25594
25783
  count(*) AS n
25595
- FROM audit_events
25784
+ FROM audit_events INDEXED BY idx_audit_session
25596
25785
  WHERE root_session_id = ? AND event_type = 'tool_call'
25597
25786
  GROUP BY coalesce(json_extract(attributes, '$.tool_name'), json_extract(attributes, '$.tool'))`
25598
25787
  ),
@@ -25600,7 +25789,7 @@ var SqliteActivityRepository = class {
25600
25789
  );
25601
25790
  const modelRows = allRows(
25602
25791
  this.db.prepare(
25603
- `SELECT DISTINCT model FROM audit_events
25792
+ `SELECT DISTINCT model FROM audit_events INDEXED BY idx_audit_session_type
25604
25793
  WHERE root_session_id = ? AND event_type = 'llm_call' AND model IS NOT NULL AND model <> ''
25605
25794
  ORDER BY model`
25606
25795
  ),
@@ -25609,7 +25798,7 @@ var SqliteActivityRepository = class {
25609
25798
  const derivedModels = modelRows.map((r) => r.model);
25610
25799
  const commits = countScalar(
25611
25800
  this.db,
25612
- `SELECT count(*) AS n FROM audit_events
25801
+ `SELECT count(*) AS n FROM audit_events INDEXED BY idx_audit_session
25613
25802
  WHERE root_session_id = ? AND event_type = 'commit'`,
25614
25803
  [sessionId]
25615
25804
  );
@@ -25645,25 +25834,57 @@ var SqliteActivityRepository = class {
25645
25834
  return Promise.resolve(session);
25646
25835
  }
25647
25836
  /**
25648
- * Cross-session token report — every `llm_call` leaf (optionally windowed to
25649
- * `started_at >= fromMs`) grouped into per-session `SessionTokenReport`s, with
25650
- * USD cost DERIVED at read time via the shared `defaultCostModel` (never
25651
- * stored). `fromMs` lets the Activity page scope the usage panel to its
25652
- * selected time range; omit it for all-time (the CLI/TUI overview). The
25653
- * caller collapses these onto per-model rows with `aggregateTokenUsage`.
25837
+ * Cross-session token report — every `llm_call` in the store (or in a
25838
+ * `started_at >= fromMs` window, the Activity page's range) grouped per
25839
+ * session, with USD cost DERIVED at read time via the shared
25840
+ * `defaultCostModel` (never stored). The caller collapses these onto
25841
+ * per-model rows with `aggregateTokenUsage`.
25842
+ *
25843
+ * Grouped in SQL over `idx_audit_llm_usage` — one entry per call carrying
25844
+ * the members the rollup sums — and priced once per group, which is exact
25845
+ * (see LlmUsageRow). Reading the bags and folding them in JS measured 31 ms
25846
+ * for a seven-day window at 50k calls, and naming the VIRTUAL columns
25847
+ * against the table 40 ms, since each is a json_extract recomputed per row;
25848
+ * the index stores the values once, at write, and answers the same window in
25849
+ * 8.5 ms. `INDEXED BY` is deliberate: with or without ANALYZE statistics the
25850
+ * planner prefers the general event-type index and fetches every row to
25851
+ * recompute the columns it could have read. The index is one every open
25852
+ * store carries, since opening runs the migrations, so the hard requirement
25853
+ * `INDEXED BY` introduces is already met; token-rollup-plans.test.ts pins
25854
+ * the plan. All-time is a scan of the whole index — still one narrow entry
25855
+ * per call, no bag parsed.
25654
25856
  */
25655
25857
  tokenReports(fromMs) {
25656
- const leaves = this.readLlmCallLeaves(fromMs === void 0 ? {} : { fromMs });
25657
- return Promise.resolve(buildTokenReports(leaves, defaultCostModel));
25858
+ const rows = allRows(
25859
+ this.db.prepare(
25860
+ `${LLM_USAGE_SELECT}
25861
+ FROM audit_events INDEXED BY idx_audit_llm_usage
25862
+ WHERE ${LLM_USAGE_SCOPE}${fromMs === void 0 ? "" : " AND started_at >= ?"}
25863
+ ${LLM_USAGE_GROUP}`
25864
+ ),
25865
+ fromMs === void 0 ? void 0 : [fromMs]
25866
+ );
25867
+ return Promise.resolve(buildTokenReports(usageLeaves(rows), defaultCostModel));
25658
25868
  }
25659
25869
  /**
25660
- * One session's token report — its `llm_call` leaves grouped per (provider,
25661
- * model) with derived cost, or `null` when the session made no `llm_call`s
25662
- * (an empty/tool-only session). Feeds the session-detail pane's per-model
25663
- * breakdown + estimated cost.
25870
+ * One session's token report — its `llm_call`s grouped per (provider,
25871
+ * model, tier) with derived cost, or `null` when the session made no
25872
+ * `llm_call`s (an empty/tool-only session). Feeds the session-detail pane's
25873
+ * per-model breakdown + estimated cost. The same rollup as `tokenReports`,
25874
+ * seeking one root through a root-led `llm_call` index; the bag-reading fold
25875
+ * it replaces walked every `llm_call` in the store to find one session's.
25664
25876
  */
25665
25877
  tokenReportForSession(sessionId) {
25666
- const reports = buildTokenReports(this.readLlmCallLeaves({ sessionId }), defaultCostModel);
25878
+ const rows = allRows(
25879
+ this.db.prepare(
25880
+ `${LLM_USAGE_SELECT}
25881
+ FROM audit_events
25882
+ WHERE ${LLM_USAGE_SCOPE} AND root_session_id = ?
25883
+ ${LLM_USAGE_GROUP}`
25884
+ ),
25885
+ [sessionId]
25886
+ );
25887
+ const reports = buildTokenReports(usageLeaves(rows), defaultCostModel);
25667
25888
  return Promise.resolve(reports[0] ?? null);
25668
25889
  }
25669
25890
  /**
@@ -25687,42 +25908,6 @@ var SqliteActivityRepository = class {
25687
25908
  for (const row of rows) seen.add(toHarness(row.harness));
25688
25909
  return Promise.resolve([...seen]);
25689
25910
  }
25690
- /**
25691
- * The raw `llm_call` leaves (session id + parsed attribute bag) for the token
25692
- * rollups, optionally narrowed to one session and/or a `started_at >= fromMs`
25693
- * window. A leaf whose attributes blob is NULL or unparseable is skipped
25694
- * (best-effort read — a corrupt bag never breaks the report). `root_session_id`
25695
- * is the leaf's session (the reconciler sets parent_id = root_session_id).
25696
- */
25697
- readLlmCallLeaves(opts = {}) {
25698
- const conditions = ["event_type = 'llm_call'", "attributes IS NOT NULL"];
25699
- const params = [];
25700
- if (opts.sessionId !== void 0) {
25701
- conditions.push("root_session_id = ?");
25702
- params.push(opts.sessionId);
25703
- }
25704
- if (opts.fromMs !== void 0) {
25705
- conditions.push("started_at >= ?");
25706
- params.push(opts.fromMs);
25707
- }
25708
- const rows = allRows(
25709
- this.db.prepare(
25710
- `SELECT root_session_id AS sessionId, attributes
25711
- FROM audit_events
25712
- WHERE ${conditions.join(" AND ")}`
25713
- ),
25714
- params
25715
- );
25716
- return mapRowsTolerant(
25717
- rows.filter(
25718
- (row) => row.sessionId !== null
25719
- ),
25720
- (row) => ({
25721
- sessionId: row.sessionId,
25722
- attributes: JSON.parse(row.attributes)
25723
- })
25724
- );
25725
- }
25726
25911
  /**
25727
25912
  * Per-session turns/findings/shares + last-activity for a page of session ids,
25728
25913
  * in grouped queries (not one per row). An id with no matching rows still
@@ -25737,20 +25922,23 @@ var SqliteActivityRepository = class {
25737
25922
  const inClause = placeholders(sessionIds.length);
25738
25923
  const lastActivityRows = allRows(
25739
25924
  this.db.prepare(
25740
- `SELECT root_session_id AS id, max(${LAST_ACTIVITY_EXPR}) AS m FROM audit_events
25741
- WHERE root_session_id IN (${inClause})
25742
- GROUP BY root_session_id`
25925
+ `SELECT ids.value AS id,
25926
+ (SELECT max(started_at) FROM audit_events e WHERE e.root_session_id = ids.value) AS ms,
25927
+ (SELECT max(ended_at) FROM audit_events e
25928
+ WHERE e.root_session_id = ids.value AND e.ended_at IS NOT NULL) AS me
25929
+ FROM json_each(?) AS ids`
25743
25930
  ),
25744
- sessionIds
25931
+ [JSON.stringify(sessionIds)]
25745
25932
  );
25746
25933
  for (const row of lastActivityRows) {
25747
- if (row.id === null) continue;
25748
25934
  const entry = result.get(row.id);
25749
- if (entry && row.m !== null) entry.lastActivityMs = row.m;
25935
+ const last = Math.max(row.ms ?? 0, row.me ?? 0);
25936
+ if (entry && last > 0) entry.lastActivityMs = last;
25750
25937
  }
25751
25938
  const turnsRows = allRows(
25752
25939
  this.db.prepare(
25753
- `SELECT root_session_id AS id, count(*) AS n FROM audit_events
25940
+ `SELECT root_session_id AS id, count(*) AS n
25941
+ FROM audit_events INDEXED BY idx_audit_session_prompt
25754
25942
  WHERE root_session_id IN (${inClause}) AND event_type = 'prompt'
25755
25943
  GROUP BY root_session_id`
25756
25944
  ),
@@ -25765,7 +25953,7 @@ var SqliteActivityRepository = class {
25765
25953
  this.db.prepare(
25766
25954
  `SELECT root_session_id AS id,
25767
25955
  count(DISTINCT json_extract(attributes, '$.run_key')) AS n
25768
- FROM audit_events
25956
+ FROM audit_events INDEXED BY idx_audit_session_run_key
25769
25957
  WHERE root_session_id IN (${inClause}) AND event_type = 'llm_call'
25770
25958
  AND json_extract(attributes, '$.run_key') IS NOT NULL
25771
25959
  GROUP BY root_session_id`
@@ -25795,7 +25983,7 @@ var SqliteActivityRepository = class {
25795
25983
  this.db.prepare(
25796
25984
  `SELECT root_session_id AS id,
25797
25985
  count(DISTINCT json_extract(attributes, '$.destination')) AS n
25798
- FROM audit_events
25986
+ FROM audit_events INDEXED BY idx_audit_session_share
25799
25987
  WHERE root_session_id IN (${inClause}) AND event_type = 'share'
25800
25988
  GROUP BY root_session_id`
25801
25989
  ),
@@ -26824,7 +27012,6 @@ var LATEST_RESOLUTION_BY_KEY_SQL = `(
26824
27012
 
26825
27013
  // ../../packages/persistence/src/repositories/findings.ts
26826
27014
  var PREVIEW_INSTANCES_PER_GROUP = 200;
26827
- var SCAN_BATCH_ROWS = 1e3;
26828
27015
  var DEFAULT_LOCATIONS_LIMIT = 100;
26829
27016
  var LOCATION_RULE_IDS_CAP = 20;
26830
27017
  function compareLocationOrder(a, b) {
@@ -26853,6 +27040,25 @@ function deriveInstanceStatus(row) {
26853
27040
  latestResolutionStatus: row.latest_status
26854
27041
  });
26855
27042
  }
27043
+ function toFlatFindingRow(r) {
27044
+ return {
27045
+ id: r.id,
27046
+ ruleId: r.rule_id,
27047
+ category: r.category,
27048
+ severity: r.severity,
27049
+ maskedMatch: r.masked_match,
27050
+ actionTaken: r.action_taken,
27051
+ confidence: r.confidence,
27052
+ occurredAt: epochMillisToIso(r.occurred_at),
27053
+ sourceTool: r.source_tool,
27054
+ repo: r.repo ?? "",
27055
+ file: r.file ?? "",
27056
+ ...r.tool_name === null ? {} : { toolName: r.tool_name },
27057
+ eventId: r.event_id,
27058
+ ...r.session_id === null ? {} : { sessionId: r.session_id },
27059
+ status: deriveInstanceStatus(r)
27060
+ };
27061
+ }
26856
27062
  function encodeGroupCursor(group) {
26857
27063
  const payload = {
26858
27064
  sev: group.severity,
@@ -26928,7 +27134,7 @@ var SqliteFindingsRepository = class {
26928
27134
  this.db.prepare(
26929
27135
  `SELECT f.id, f.audit_event_id AS event_id, d.rule_id, d.category, d.severity,
26930
27136
  f.masked_match, f.action_taken, f.confidence, e.started_at AS occurred_at,
26931
- json_extract(e.attributes, '$.source_tool') AS source_tool,
27137
+ e.source_tool AS source_tool,
26932
27138
  e.event_type AS kind
26933
27139
  FROM audit_events e
26934
27140
  CROSS JOIN inspection_findings f ON f.audit_event_id = e.id
@@ -27036,56 +27242,11 @@ var SqliteFindingsRepository = class {
27036
27242
  predicate,
27037
27243
  params: sessionParams
27038
27244
  });
27039
- const rows = allRows(
27040
- this.db.prepare(
27041
- `SELECT id, rule_id, category, severity, masked_match, action_taken, confidence,
27042
- occurred_at, source_tool, repo, file, tool_name, event_id, session_id,
27043
- kind, finding_key, latest_status
27044
- FROM (
27045
- SELECT f.id AS id, d.rule_id AS rule_id, d.category AS category,
27046
- d.severity AS severity, f.masked_match AS masked_match,
27047
- f.action_taken AS action_taken, f.confidence AS confidence,
27048
- e.started_at AS occurred_at,
27049
- json_extract(e.attributes, '$.source_tool') AS source_tool,
27050
- json_extract(e.attributes, '$.repo') AS repo,
27051
- json_extract(e.attributes, '$.file_path') AS file,
27052
- json_extract(e.attributes, '$.tool_name') AS tool_name,
27053
- f.audit_event_id AS event_id, e.root_session_id AS session_id,
27054
- e.event_type AS kind, f.finding_key AS finding_key,
27055
- latest.status AS latest_status,
27056
- ROW_NUMBER() OVER (
27057
- PARTITION BY d.rule_id
27058
- ORDER BY e.started_at DESC, f.id DESC
27059
- ) AS rn
27060
- FROM inspection_findings f
27061
- JOIN audit_events e ON e.id = f.audit_event_id
27062
- JOIN inspection_definitions d ON d.id = f.inspection_definition_id
27063
- LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
27064
- ON latest.finding_key = f.finding_key
27065
- ${predicate}
27066
- )
27067
- WHERE rn <= :cap
27068
- ORDER BY occurred_at DESC, id DESC`
27069
- ),
27070
- { cap: PREVIEW_INSTANCES_PER_GROUP, ...sessionParams }
27071
- );
27072
- const groupable = rows.map((r) => ({
27073
- id: r.id,
27074
- ruleId: r.rule_id,
27075
- category: r.category,
27076
- severity: r.severity,
27077
- maskedMatch: r.masked_match,
27078
- actionTaken: r.action_taken,
27079
- confidence: r.confidence,
27080
- occurredAt: epochMillisToIso(r.occurred_at),
27081
- sourceTool: r.source_tool,
27082
- repo: r.repo ?? "",
27083
- file: r.file ?? "",
27084
- ...r.tool_name === null ? {} : { toolName: r.tool_name },
27085
- eventId: r.event_id,
27086
- ...r.session_id === null ? {} : { sessionId: r.session_id },
27087
- status: deriveInstanceStatus(r)
27088
- }));
27245
+ const rows = this.previewRows(aggregates, {
27246
+ sessionId: query.sessionId,
27247
+ from: query.from
27248
+ });
27249
+ const groupable = rows.map(toFlatFindingRow);
27089
27250
  const allGroups = buildFindingGroups(groupable, { aggregates });
27090
27251
  const filterOpts = {
27091
27252
  severity: query.severity,
@@ -27171,8 +27332,10 @@ var SqliteFindingsRepository = class {
27171
27332
  *
27172
27333
  * The scan runs from the top of the scope on every request, not from the
27173
27334
  * cursor: `totals` and `facets` describe the whole filtered scope and must not
27174
- * move as the caller pages. Rows are pulled in batches so memory stays flat
27175
- * while the counting runs, and only the page itself is retained.
27335
+ * move as the caller pages. Rows come off ONE statement, iterated rather
27336
+ * than materialized (`scanFindingRows`), so memory stays flat while the
27337
+ * counting runs — a generator streaming the index order, not a sequence of
27338
+ * fetched batches; only the page itself is retained.
27176
27339
  */
27177
27340
  listFindingInstances(query) {
27178
27341
  const opts = {
@@ -27188,6 +27351,10 @@ var SqliteFindingsRepository = class {
27188
27351
  };
27189
27352
  const limit = query.limit ?? DEFAULT_FLAT_FINDINGS_LIMIT;
27190
27353
  const cursor = query.cursor === void 0 ? null : decodeKeysetCursor(query.cursor);
27354
+ const isPastCursor = cursor === null ? () => true : (row) => {
27355
+ const rowMs = isoToEpochMillis(row.occurredAt);
27356
+ return rowMs <= cursor.startedAtMs && (rowMs < cursor.startedAtMs || row.id < cursor.id);
27357
+ };
27191
27358
  const accumulator = createInstanceFacetAccumulator(opts);
27192
27359
  const items = [];
27193
27360
  let total = 0;
@@ -27200,6 +27367,7 @@ var SqliteFindingsRepository = class {
27200
27367
  accumulator.add(row);
27201
27368
  if (!matchesInstanceFilters(row, opts)) continue;
27202
27369
  total += 1;
27370
+ if (!isPastCursor(row)) continue;
27203
27371
  if (items.length < limit) {
27204
27372
  items.push(toInstanceDetail(row));
27205
27373
  last = row;
@@ -27208,15 +27376,6 @@ var SqliteFindingsRepository = class {
27208
27376
  }
27209
27377
  }
27210
27378
  const nextCursor = hasMore && last ? encodeKeysetCursor({ startedAtMs: isoToEpochMillis(last.occurredAt), id: last.id }) : null;
27211
- if (cursor !== null) {
27212
- const resumed = this.pageAfter(cursor, opts, limit, query);
27213
- return Promise.resolve({
27214
- totals: { findings: total },
27215
- facets: accumulator.facets(),
27216
- items: resumed.items,
27217
- nextCursor: resumed.nextCursor
27218
- });
27219
- }
27220
27379
  return Promise.resolve({
27221
27380
  totals: { findings: total },
27222
27381
  facets: accumulator.facets(),
@@ -27224,35 +27383,6 @@ var SqliteFindingsRepository = class {
27224
27383
  nextCursor
27225
27384
  });
27226
27385
  }
27227
- /**
27228
- * The page of matching rows strictly after `cursor`. Separate from the
27229
- * counting pass because that one starts at the top of the scope by design;
27230
- * this one narrows the scan with the same keyset predicate the activity list
27231
- * uses, so a later page costs less than the first rather than more.
27232
- */
27233
- pageAfter(cursor, opts, limit, query) {
27234
- const items = [];
27235
- let last;
27236
- let hasMore = false;
27237
- for (const row of this.scanFindingRows({
27238
- sessionId: query.sessionId,
27239
- from: query.from,
27240
- after: cursor
27241
- })) {
27242
- if (!matchesInstanceFilters(row, opts)) continue;
27243
- if (items.length < limit) {
27244
- items.push(toInstanceDetail(row));
27245
- last = row;
27246
- } else {
27247
- hasMore = true;
27248
- break;
27249
- }
27250
- }
27251
- return {
27252
- items,
27253
- nextCursor: hasMore && last ? encodeKeysetCursor({ startedAtMs: isoToEpochMillis(last.occurredAt), id: last.id }) : null
27254
- };
27255
- }
27256
27386
  /**
27257
27387
  * The same findings folded by location: repository, then file within it.
27258
27388
  *
@@ -27335,25 +27465,111 @@ var SqliteFindingsRepository = class {
27335
27465
  });
27336
27466
  }
27337
27467
  /**
27338
- * Every finding in scope as a FlatFindingRow, newest first, pulled in batches.
27468
+ * Each group's newest instances, for the table's expanded rows.
27469
+ *
27470
+ * ONE index-ordered scan with early termination, and the shape is the point.
27471
+ * The natural spelling — `ROW_NUMBER() OVER (PARTITION BY rule_id ORDER BY
27472
+ * started_at DESC)` then `WHERE rn <= cap` — sorts EVERY finding in scope
27473
+ * through a temp B-tree to keep a bounded preview of each group, and then
27474
+ * sorts the survivors again for the page order. Both sorts grow with the
27475
+ * store while the answer does not.
27476
+ *
27477
+ * Instead the scan walks `audit_events` newest-first off `idx_audit_started_at`
27478
+ * (or the session or window index the scope names — see `findingScanSql`),
27479
+ * which is already the order the page wants, and keeps rows per rule until
27480
+ * each rule has as many as it can show. The aggregate the caller already holds
27481
+ * says how many that is: `min(instanceCount, PREVIEW_INSTANCES_PER_GROUP)`
27482
+ * per rule, summed, is the number of rows this scan has to find, and it stops
27483
+ * on the last one. That sum is bounded by `rules * PREVIEW_INSTANCES_PER_GROUP`
27484
+ * (8,000 at this repo's 40-rule bench corpus), not by a fixed row count — a
27485
+ * store with many firing rules widens it. The bound that DOES hold
27486
+ * unconditionally is the sorted form's floor: this scan visits at most as
27487
+ * many rows as `ROW_NUMBER() OVER (PARTITION BY rule_id …)` would have
27488
+ * sorted, and stops the moment every rule has its cap, where the sorted form
27489
+ * sorts the whole scope regardless. The true worst case — the rarest rule's
27490
+ * wanted instances sitting at the tail of the scope — is one pass over
27491
+ * everything in scope with a block sort of the id tie-break only, never a
27492
+ * sort of the scope, which is still that floor.
27493
+ *
27494
+ * A row whose rule the aggregate did not see is skipped: the two statements
27495
+ * run without a shared snapshot, so a capture landing between them can add a
27496
+ * rule here that has no counts there, and the counts are what the group is
27497
+ * built from.
27498
+ */
27499
+ previewRows(aggregates, scope) {
27500
+ const wanted = /* @__PURE__ */ new Map();
27501
+ let remaining = 0;
27502
+ for (const [ruleId, agg] of aggregates) {
27503
+ const n = Math.min(agg.instanceCount, PREVIEW_INSTANCES_PER_GROUP);
27504
+ wanted.set(ruleId, n);
27505
+ remaining += n;
27506
+ }
27507
+ const rows = [];
27508
+ if (remaining === 0) return rows;
27509
+ const { sql, params } = this.findingScanSql(scope);
27510
+ const taken = /* @__PURE__ */ new Map();
27511
+ for (const r of iterateRows(this.db.prepare(sql), params)) {
27512
+ const want = wanted.get(r.rule_id);
27513
+ if (want === void 0) continue;
27514
+ const have = taken.get(r.rule_id) ?? 0;
27515
+ if (have >= want) continue;
27516
+ taken.set(r.rule_id, have + 1);
27517
+ rows.push(r);
27518
+ remaining -= 1;
27519
+ if (remaining === 0) break;
27520
+ }
27521
+ return rows;
27522
+ }
27523
+ /**
27524
+ * Every finding in scope as a FlatFindingRow, newest first, streamed.
27339
27525
  *
27340
27526
  * A generator so a caller streams the scope without it ever being an array:
27341
27527
  * the flat list counts and facets the whole filtered scope, which on a large
27342
- * store is far more rows than any page. Each batch advances the same keyset
27343
- * predicate the page read uses, so the scan is a sequence of bounded reads
27344
- * rather than one unbounded result set.
27345
- *
27346
- * The latest-resolution lookup is the CORRELATED form, not the derived table
27347
- * the grouped path joins: only `status` is needed, idx_finding_resolution_key
27348
- * makes it a point lookup per row, and the derived table would re-materialize
27349
- * a window over the whole resolution table once per batch.
27528
+ * store is far more rows than any page. The rows come off ONE statement,
27529
+ * iterated rather than materialized, in the index order `findingScanSql`
27530
+ * arranges — so the scan is a single pass with a block sort of the id
27531
+ * tie-break only, never a sort of the scope, where a sequence of
27532
+ * keyset-bounded batches re-sorted everything below the cursor on every
27533
+ * batch and cost the square of the scope.
27350
27534
  *
27351
- * `scope` carries ONLY what no facet counts. A filter dimension narrowed here
27352
- * would be missing from its own facet, which is computed by excluding that
27353
- * dimension — see listFindingInstances.
27535
+ * `sessionId` and `from` carry ONLY what no facet counts — a filter
27536
+ * dimension narrowed here would be missing from its own facet, which is
27537
+ * computed by excluding that dimension (see listFindingInstances). There is
27538
+ * no `after`/cursor parameter: a keyset page is collected inline from this
27539
+ * same pass (`listFindingInstances`' `isPastCursor`) rather than by a second,
27540
+ * narrower statement, since the counting pass already visits every row a
27541
+ * page-2+ request would otherwise re-seek for.
27354
27542
  */
27355
27543
  *scanFindingRows(scope) {
27356
- const conditions = [`e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})`];
27544
+ const { sql, params } = this.findingScanSql(scope);
27545
+ for (const r of iterateRows(this.db.prepare(sql), params)) {
27546
+ yield toFlatFindingRow(r);
27547
+ }
27548
+ }
27549
+ /**
27550
+ * The one statement both instance-level scans run: every finding in scope,
27551
+ * joined to its event and definition, newest first.
27552
+ *
27553
+ * THE PLAN IS THE POINT, and two things in the SQL exist only to pin it —
27554
+ * the same two `recentFindings` documents at length, for the same reason:
27555
+ *
27556
+ * - **`+e.event_type`** makes the capture-kind predicate non-indexable, so
27557
+ * the planner cannot pick `idx_audit_type_t` and then sort. That index
27558
+ * yields `started_at` order per event type, not across the four, so
27559
+ * satisfying the ORDER BY from it would need a merge SQLite does not do.
27560
+ * Freed of it, the planner walks `idx_audit_started_at` backwards — or
27561
+ * `idx_audit_session` for a session scope, which is also `started_at`
27562
+ * ordered within the session — and the order falls out of the index.
27563
+ * - **`CROSS JOIN`** pins `audit_events` as the driving table. With plain
27564
+ * JOINs the planner drives from the findings and sorts everything.
27565
+ *
27566
+ * The latest-resolution lookup is the CORRELATED form: only `status` is
27567
+ * needed, `idx_finding_resolution_key_created` answers it with one backward
27568
+ * index probe per keyed row, and a derived table over the whole resolution
27569
+ * table would be materialized before the first row streamed.
27570
+ */
27571
+ findingScanSql(scope) {
27572
+ const conditions = [`+e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})`];
27357
27573
  const params = [];
27358
27574
  if (scope.sessionId !== void 0 && scope.sessionId !== "") {
27359
27575
  conditions.push("e.root_session_id = ?");
@@ -27367,58 +27583,24 @@ var SqliteFindingsRepository = class {
27367
27583
  d.severity AS severity, f.masked_match AS masked_match,
27368
27584
  f.action_taken AS action_taken, f.confidence AS confidence,
27369
27585
  e.started_at AS occurred_at,
27370
- json_extract(e.attributes, '$.source_tool') AS source_tool,
27371
- json_extract(e.attributes, '$.repo') AS repo,
27372
- json_extract(e.attributes, '$.file_path') AS file,
27373
- json_extract(e.attributes, '$.tool_name') AS tool_name,
27586
+ e.source_tool AS source_tool,
27587
+ e.repo AS repo,
27588
+ e.file_path AS file,
27589
+ e.tool_name AS tool_name,
27374
27590
  f.audit_event_id AS event_id, e.root_session_id AS session_id,
27375
27591
  e.event_type AS kind, f.finding_key AS finding_key,
27376
27592
  ${latestResolutionStatusSql("f")} AS latest_status
27377
- FROM inspection_findings f
27378
- JOIN audit_events e ON e.id = f.audit_event_id
27379
- JOIN inspection_definitions d ON d.id = f.inspection_definition_id
27593
+ FROM audit_events e
27594
+ CROSS JOIN inspection_findings f ON f.audit_event_id = e.id
27595
+ CROSS JOIN inspection_definitions d ON d.id = f.inspection_definition_id
27380
27596
  WHERE ${conditions.join(" AND ")}
27381
- AND (e.started_at < ? OR (e.started_at = ? AND f.id < ?))
27382
- ORDER BY e.started_at DESC, f.id DESC
27383
- LIMIT ?`;
27384
- let after = scope.after ?? { startedAtMs: Number.MAX_SAFE_INTEGER, id: "\uFFFF" };
27385
- for (; ; ) {
27386
- const rows = allRows(this.db.prepare(sql), [
27387
- ...params,
27388
- after.startedAtMs,
27389
- after.startedAtMs,
27390
- after.id,
27391
- SCAN_BATCH_ROWS
27392
- ]);
27393
- for (const r of rows) {
27394
- yield {
27395
- id: r.id,
27396
- ruleId: r.rule_id,
27397
- category: r.category,
27398
- severity: r.severity,
27399
- maskedMatch: r.masked_match,
27400
- actionTaken: r.action_taken,
27401
- confidence: r.confidence,
27402
- occurredAt: epochMillisToIso(r.occurred_at),
27403
- sourceTool: r.source_tool,
27404
- repo: r.repo ?? "",
27405
- file: r.file ?? "",
27406
- ...r.tool_name === null ? {} : { toolName: r.tool_name },
27407
- eventId: r.event_id,
27408
- ...r.session_id === null ? {} : { sessionId: r.session_id },
27409
- status: deriveInstanceStatus(r)
27410
- };
27411
- }
27412
- if (rows.length < SCAN_BATCH_ROWS) return;
27413
- const lastRow = rows[rows.length - 1];
27414
- if (lastRow === void 0) return;
27415
- after = { startedAtMs: lastRow.occurred_at, id: lastRow.id };
27416
- }
27597
+ ORDER BY e.started_at DESC, f.id DESC`;
27598
+ return { sql, params };
27417
27599
  }
27418
27600
  groupAggregates(withSearchText, scope) {
27419
- const innerSearchColumns = withSearchText ? `, group_concat(DISTINCT json_extract(e.attributes, '$.repo')) AS repos,
27420
- group_concat(DISTINCT json_extract(e.attributes, '$.file_path')) AS files,
27421
- group_concat(DISTINCT 'via ' || json_extract(e.attributes, '$.tool_name')) AS tool_names` : `, NULL AS repos, NULL AS files, NULL AS tool_names`;
27601
+ const innerSearchColumns = withSearchText ? `, group_concat(DISTINCT e.repo) AS repos,
27602
+ group_concat(DISTINCT e.file_path) AS files,
27603
+ group_concat(DISTINCT 'via ' || e.tool_name) AS tool_names` : `, NULL AS repos, NULL AS files, NULL AS tool_names`;
27422
27604
  const rows = this.db.prepare(
27423
27605
  `SELECT rule_id,
27424
27606
  sum(tuple_count) AS instance_count,
@@ -27436,7 +27618,7 @@ var SqliteFindingsRepository = class {
27436
27618
  coalesce(latest.status, '') AS status_tuple,
27437
27619
  count(*) AS tuple_count,
27438
27620
  max(e.started_at) AS latest_at,
27439
- group_concat(DISTINCT json_extract(e.attributes, '$.source_tool')) AS source_tools,
27621
+ group_concat(DISTINCT e.source_tool) AS source_tools,
27440
27622
  group_concat(DISTINCT f.action_taken) AS actions_taken
27441
27623
  ${innerSearchColumns}
27442
27624
  FROM inspection_findings f
@@ -27567,6 +27749,8 @@ function isoDay(ms) {
27567
27749
  // ../../packages/persistence/src/repositories/history-sync.ts
27568
27750
  var STRUCTURAL_EVENT_TYPES = ["session", "llm_call", "tool_call"];
27569
27751
  var TYPE_LIST = STRUCTURAL_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
27752
+ var OUTBOX_CAPTURE_EVENT_TYPES = ["prompt", "response", "tool_use"];
27753
+ var CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
27570
27754
  var SKIPPED = -1;
27571
27755
  var ROW_COLUMNS = `id,
27572
27756
  parent_id AS parentId,
@@ -27606,6 +27790,20 @@ var SqliteHistorySyncRepository = class {
27606
27790
  ORDER BY (event_type = 'session') DESC, started_at
27607
27791
  LIMIT :limit`
27608
27792
  );
27793
+ this.captureRowsStmt = db.prepare(
27794
+ `SELECT ${ROW_COLUMNS}
27795
+ FROM audit_events
27796
+ WHERE synced_at IS NULL
27797
+ AND sync_claimed_at IS NULL
27798
+ AND outbox_owed = 1
27799
+ AND event_type IN (${CAPTURE_TYPE_LIST})
27800
+ AND started_at < :before
27801
+ ORDER BY started_at
27802
+ LIMIT :limit`
27803
+ );
27804
+ this.markOwedStmt = db.prepare(
27805
+ `UPDATE audit_events SET outbox_owed = 1 WHERE id = :id AND synced_at IS NULL`
27806
+ );
27609
27807
  this.stampStmt = db.prepare(
27610
27808
  `UPDATE audit_events SET synced_at = :at, sync_claimed_at = NULL WHERE id = :id`
27611
27809
  );
@@ -27637,6 +27835,12 @@ var SqliteHistorySyncRepository = class {
27637
27835
  FROM audit_events
27638
27836
  WHERE event_type IN (${TYPE_LIST})`
27639
27837
  );
27838
+ this.captureSkipCountStmt = db.prepare(
27839
+ `SELECT COUNT(*) AS skipped
27840
+ FROM audit_events
27841
+ WHERE synced_at = ${String(SKIPPED)}
27842
+ AND event_type IN (${CAPTURE_TYPE_LIST})`
27843
+ );
27640
27844
  this.fingerprintStmt = db.prepare(
27641
27845
  `SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
27642
27846
  FROM history_sync WHERE id = 1`
@@ -27646,6 +27850,10 @@ var SqliteHistorySyncRepository = class {
27646
27850
  SET endpoint_fingerprint = :fingerprint, backlog_before = :backlogBefore
27647
27851
  WHERE id = 1`
27648
27852
  );
27853
+ this.disownCapturesStmt = db.prepare(
27854
+ `UPDATE audit_events SET outbox_owed = NULL
27855
+ WHERE outbox_owed IS NOT NULL AND event_type IN (${CAPTURE_TYPE_LIST})`
27856
+ );
27649
27857
  this.rearmStmt = db.prepare(
27650
27858
  `UPDATE audit_events SET synced_at = NULL
27651
27859
  WHERE synced_at > 0 AND event_type IN (${TYPE_LIST})`
@@ -27718,6 +27926,10 @@ var SqliteHistorySyncRepository = class {
27718
27926
  closeWindowStmt;
27719
27927
  releaseBoundaryStmt;
27720
27928
  freezeBoundaryStmt;
27929
+ captureRowsStmt;
27930
+ markOwedStmt;
27931
+ captureSkipCountStmt;
27932
+ disownCapturesStmt;
27721
27933
  partitionStmt;
27722
27934
  claimRowStmt;
27723
27935
  releaseRowStmt;
@@ -27751,6 +27963,34 @@ var SqliteHistorySyncRepository = class {
27751
27963
  pendingRows(sessionId, limit, before) {
27752
27964
  return allRows(this.rowsStmt, { sessionId, limit, before });
27753
27965
  }
27966
+ /**
27967
+ * Captures this machine still owes the deployment, oldest first.
27968
+ *
27969
+ * Selected by the `outbox_owed` marker the attached forward path writes, not
27970
+ * by a time window — see captureRowsStmt for why a window could not express
27971
+ * this. `before` is the grace window that leaves a just-recorded capture to
27972
+ * the live path.
27973
+ */
27974
+ pendingCaptureRows(limit, before) {
27975
+ return allRows(this.captureRowsStmt, { limit, before });
27976
+ }
27977
+ /**
27978
+ * Record that a capture is OWED to the deployment.
27979
+ *
27980
+ * Written by the attached forward path when a live send did not confirm
27981
+ * delivery, and read by the drain as the whole of its eligibility test. It is
27982
+ * a fact rather than an inference: the machine was attached, the send did not
27983
+ * land, so the row is owed — which no time window can state, because the same
27984
+ * window that holds the rows a past attachment left owed also holds every
27985
+ * capture recorded while the machine was DETACHED, and those were never
27986
+ * offered to anyone.
27987
+ *
27988
+ * Idempotent, and never un-set: `markSynced` settling the row is what takes it
27989
+ * out of the drain's read.
27990
+ */
27991
+ markCaptureOwed(id) {
27992
+ this.markOwedStmt.run({ id });
27993
+ }
27754
27994
  /** Record delivery. Called only AFTER the far side has accepted the rows. */
27755
27995
  markSynced(ids, atMs) {
27756
27996
  this.stampAll(ids, atMs);
@@ -27834,10 +28074,12 @@ var SqliteHistorySyncRepository = class {
27834
28074
  this.countsStmt,
27835
28075
  { before }
27836
28076
  );
28077
+ const captures = getRow(this.captureSkipCountStmt);
27837
28078
  return {
27838
28079
  pending: row?.pending ?? 0,
27839
28080
  sent: row?.sent ?? 0,
27840
- skipped: row?.skipped ?? 0
28081
+ skipped: row?.skipped ?? 0,
28082
+ capturesSkipped: captures?.skipped ?? 0
27841
28083
  };
27842
28084
  }
27843
28085
  /**
@@ -27878,7 +28120,11 @@ var SqliteHistorySyncRepository = class {
27878
28120
  withTransaction(
27879
28121
  this.db,
27880
28122
  () => {
28123
+ const previous = getRow(this.fingerprintStmt)?.fingerprint;
27881
28124
  this.rearmStmt.run();
28125
+ if (previous !== null && previous !== void 0 && previous !== fingerprint) {
28126
+ this.disownCapturesStmt.run();
28127
+ }
27882
28128
  this.setFingerprintStmt.run({ fingerprint, backlogBefore });
27883
28129
  },
27884
28130
  "IMMEDIATE"
@@ -28075,7 +28321,259 @@ var SqliteInspectionFindingsRepository = class {
28075
28321
  };
28076
28322
 
28077
28323
  // ../../packages/persistence/src/repositories/installed-packs.ts
28078
- import { createHash as createHash2, randomUUID as randomUUID3 } from "crypto";
28324
+ import { createHash as createHash2, randomUUID as randomUUID4 } from "crypto";
28325
+
28326
+ // ../../packages/persistence/src/policy-floor.ts
28327
+ import { readFileSync as readFileSync5 } from "fs";
28328
+ import { join as join6 } from "path";
28329
+
28330
+ // ../../packages/persistence/src/local-layout.ts
28331
+ import { renameSync as renameSync3 } from "fs";
28332
+ import { mkdir } from "fs/promises";
28333
+ import { homedir } from "os";
28334
+ import { join as join4 } from "path";
28335
+ function defaultDataDir() {
28336
+ return join4(homedir(), ".aka");
28337
+ }
28338
+ function settingsDir(base = defaultDataDir()) {
28339
+ return join4(base, "settings");
28340
+ }
28341
+ function dataDir(base = defaultDataDir()) {
28342
+ return join4(base, "data");
28343
+ }
28344
+ function dbPath(base = defaultDataDir()) {
28345
+ return join4(dataDir(base), "aka.db");
28346
+ }
28347
+ function keysDir(base = defaultDataDir()) {
28348
+ return join4(base, "keys");
28349
+ }
28350
+ async function ensureDataDir(dir = defaultDataDir()) {
28351
+ await mkdir(dir, { recursive: true, mode: DATA_DIR_MODE });
28352
+ tightenDir(dir);
28353
+ }
28354
+ function ensureLayoutDirSync(dir = defaultDataDir()) {
28355
+ ensureDataDirSync(dir);
28356
+ }
28357
+ function migrateLegacyLayout(base = defaultDataDir()) {
28358
+ const moves = [
28359
+ { name: "config.json", dest: settingsDir(base) },
28360
+ { name: "policy-cache.json", dest: dataDir(base) }
28361
+ ];
28362
+ for (const { name, dest } of moves) {
28363
+ try {
28364
+ ensureDataDirSync(dest);
28365
+ const moved = join4(dest, name);
28366
+ renameSync3(join4(base, name), moved);
28367
+ tightenFile(moved);
28368
+ } catch {
28369
+ }
28370
+ }
28371
+ }
28372
+
28373
+ // ../../packages/persistence/src/settings.ts
28374
+ import { readFileSync as readFileSync4 } from "fs";
28375
+ import { join as join5 } from "path";
28376
+
28377
+ // ../../packages/persistence/src/file-lock.ts
28378
+ import { randomUUID as randomUUID3 } from "crypto";
28379
+ import {
28380
+ closeSync,
28381
+ existsSync as existsSync2,
28382
+ openSync,
28383
+ readFileSync as readFileSync2,
28384
+ rmSync as rmSync5,
28385
+ statSync as statSync3,
28386
+ writeFileSync as writeFileSync2
28387
+ } from "fs";
28388
+ import { hostname as hostname3 } from "os";
28389
+ var PARK = new Int32Array(new SharedArrayBuffer(4));
28390
+
28391
+ // ../../packages/persistence/src/managed-settings.ts
28392
+ import { readFileSync as readFileSync3 } from "fs";
28393
+ import { posix, win32 } from "path";
28394
+ function managedSettingsPaths(platform2 = process.platform) {
28395
+ if (platform2 === "darwin") {
28396
+ return [
28397
+ posix.join("/Library", "Application Support", "AKASecurity", MANAGED_SETTINGS_FILENAME),
28398
+ posix.join("/Library", "Managed Preferences", MANAGED_SETTINGS_FILENAME)
28399
+ ];
28400
+ }
28401
+ if (platform2 === "win32") {
28402
+ return [win32.join("C:\\", "ProgramData", "AKASecurity", MANAGED_SETTINGS_FILENAME)];
28403
+ }
28404
+ return [posix.join("/etc", "aka", MANAGED_SETTINGS_FILENAME)];
28405
+ }
28406
+ function readManagedSettings(paths = managedSettingsPaths()) {
28407
+ for (const path of paths) {
28408
+ let text;
28409
+ try {
28410
+ text = readFileSync3(path, "utf8");
28411
+ } catch {
28412
+ continue;
28413
+ }
28414
+ const record2 = parseJsonObject(text);
28415
+ if (!record2) continue;
28416
+ const parsed2 = ManagedSettings.safeParse(record2);
28417
+ if (parsed2.success) return parsed2.data;
28418
+ }
28419
+ return null;
28420
+ }
28421
+ function overlayManagedSettings(settings, managed, now = () => /* @__PURE__ */ new Date()) {
28422
+ if (!managed) return settings;
28423
+ const { values } = managed;
28424
+ const merged = { ...settings };
28425
+ if (values.runMode !== void 0) merged.runMode = values.runMode;
28426
+ if (values.controlPlane !== void 0) {
28427
+ merged.controlPlane = {
28428
+ ...values.controlPlane,
28429
+ // The administrator pinned WHICH deployment, not WHEN this machine
28430
+ // joined it. Keep the user's own attach time when the endpoint is
28431
+ // unchanged, so a managed machine does not appear to re-attach on every
28432
+ // read; stamp a fresh one when the administrator moved it.
28433
+ attachedAt: settings.controlPlane?.endpoint === values.controlPlane.endpoint ? settings.controlPlane.attachedAt : now().toISOString()
28434
+ };
28435
+ }
28436
+ if (values.historicalAccess !== void 0) merged.historicalAccess = values.historicalAccess;
28437
+ if (values.vaultKeyCustody !== void 0) merged.vaultKeyCustody = values.vaultKeyCustody;
28438
+ if (values.vaultInlineReveal !== void 0) merged.vaultInlineReveal = values.vaultInlineReveal;
28439
+ if (values.dataSharesInPlace !== void 0) merged.dataSharesInPlace = values.dataSharesInPlace;
28440
+ if (values.redactFallback !== void 0) merged.redactFallback = values.redactFallback;
28441
+ if (values.vaultConsent !== void 0) {
28442
+ merged.vaultConsent = values.vaultConsent ? (
28443
+ // Keep an existing valid grant so its acknowledgedAt survives; mint one
28444
+ // at the current version otherwise.
28445
+ settings.vaultConsent?.version === VAULT_CONSENT_VERSION ? settings.vaultConsent : { acknowledgedAt: now().toISOString(), version: VAULT_CONSENT_VERSION }
28446
+ ) : void 0;
28447
+ }
28448
+ if (values.modelJudgeConsent !== void 0) {
28449
+ merged.modelJudgeConsent = values.modelJudgeConsent ? settings.modelJudgeConsent?.payloadVersion === MODEL_JUDGE_PAYLOAD_VERSION ? settings.modelJudgeConsent : {
28450
+ acknowledgedAt: now().toISOString(),
28451
+ payloadVersion: MODEL_JUDGE_PAYLOAD_VERSION
28452
+ } : void 0;
28453
+ }
28454
+ return merged;
28455
+ }
28456
+
28457
+ // ../../packages/persistence/src/settings.ts
28458
+ var SETTINGS_FILENAME = "settings.json";
28459
+ function readWorkspaceSettings(base = defaultDataDir()) {
28460
+ return overlayManagedSettings(readUserSettings(base), readManagedSettings());
28461
+ }
28462
+ function readUserSettings(base) {
28463
+ const record2 = readJson(join5(settingsDir(base), SETTINGS_FILENAME));
28464
+ if (!record2) return defaultWorkspaceSettings();
28465
+ try {
28466
+ return WorkspaceSettings.parse(record2);
28467
+ } catch {
28468
+ return defaultWorkspaceSettings();
28469
+ }
28470
+ }
28471
+ function readJson(file2) {
28472
+ let text;
28473
+ try {
28474
+ text = readFileSync4(file2, "utf8");
28475
+ } catch {
28476
+ return null;
28477
+ }
28478
+ return parseJsonObject(text) ?? null;
28479
+ }
28480
+
28481
+ // ../../packages/persistence/src/policy-floor.ts
28482
+ function refusalMessage(pack, attempted, floor, refusal) {
28483
+ switch (refusal) {
28484
+ case "lock":
28485
+ return `refusing to re-assign '${pack}': its policy is set by the connected control plane`;
28486
+ case "disable":
28487
+ return `refusing to disable '${pack}': it is governed by the connected control plane`;
28488
+ case "floor":
28489
+ return `refusing to set '${pack}' to '${attempted ?? "unassigned"}': the connected control plane requires at least '${floor}'`;
28490
+ }
28491
+ }
28492
+ var PolicyFloorError = class extends Error {
28493
+ /** `namespace/packId` of the detection whose write was refused. */
28494
+ pack;
28495
+ /**
28496
+ * The archetype the caller asked for, or null when the write named none —
28497
+ * clearing the assignment, or switching the detection off.
28498
+ */
28499
+ attempted;
28500
+ /** The weakest archetype the control plane permits for this pack. */
28501
+ floor;
28502
+ refusal;
28503
+ constructor(pack, attempted, floor, refusal) {
28504
+ super(refusalMessage(pack, attempted, floor, refusal));
28505
+ this.name = "PolicyFloorError";
28506
+ this.pack = pack;
28507
+ this.attempted = attempted;
28508
+ this.floor = floor;
28509
+ this.refusal = refusal;
28510
+ }
28511
+ };
28512
+ function readCachedPolicyBundle(base = defaultDataDir()) {
28513
+ try {
28514
+ const raw = readFileSync5(join6(dataDir(base), POLICY_CACHE_FILENAME), "utf8");
28515
+ const parsed2 = JSON.parse(raw);
28516
+ if (typeof parsed2 !== "object" || parsed2 === null) return null;
28517
+ return PolicyBundle.parse(parsed2.bundle);
28518
+ } catch {
28519
+ return null;
28520
+ }
28521
+ }
28522
+ function indexEnabled(policies) {
28523
+ const byRuleId = /* @__PURE__ */ new Map();
28524
+ const byCategory = /* @__PURE__ */ new Map();
28525
+ for (const policy of policies) {
28526
+ if (!policy.enabled) continue;
28527
+ if ("ruleId" in policy.target) {
28528
+ if (!byRuleId.has(policy.target.ruleId)) byRuleId.set(policy.target.ruleId, policy.action);
28529
+ } else if (!byCategory.has(policy.target.category)) {
28530
+ byCategory.set(policy.target.category, policy.action);
28531
+ }
28532
+ }
28533
+ return { byRuleId, byCategory };
28534
+ }
28535
+ function hasAuthoredPolicy(policies, rules, byRuleId) {
28536
+ const ruleIds = new Set(rules.map((rule) => rule.id));
28537
+ const categories = new Set(rules.map((rule) => rule.category));
28538
+ const bundleNamesPack = rules.some((rule) => byRuleId.has(rule.id));
28539
+ return policies.some((policy) => {
28540
+ if (!policy.enabled || policy.provenance !== "authored") return false;
28541
+ return "ruleId" in policy.target ? ruleIds.has(policy.target.ruleId) : bundleNamesPack && categories.has(policy.target.category);
28542
+ });
28543
+ }
28544
+ function controlPlanePolicyFloor(rules, base = defaultDataDir()) {
28545
+ const floors = openControlPlaneFloors(base);
28546
+ return floors === null ? null : floors.floorFor(rules);
28547
+ }
28548
+ function openControlPlaneFloors(base = defaultDataDir()) {
28549
+ if (!isAttached(readWorkspaceSettings(base))) return null;
28550
+ const bundle = readCachedPolicyBundle(base);
28551
+ if (bundle === null) return null;
28552
+ const indexes = indexEnabled(bundle.policies);
28553
+ return { floorFor: (rules) => resolveFloor(rules, bundle.policies, indexes) };
28554
+ }
28555
+ function resolveFloor(rules, policies, { byRuleId, byCategory }) {
28556
+ let action = null;
28557
+ for (const rule of rules) {
28558
+ const resolved = byRuleId.get(rule.id) ?? byCategory.get(rule.category);
28559
+ if (resolved === void 0) continue;
28560
+ action = action === null ? resolved : strongerAction(action, resolved);
28561
+ }
28562
+ if (action === null) return null;
28563
+ return {
28564
+ floor: weakestBuiltinAtLeast(action),
28565
+ locked: hasAuthoredPolicy(policies, rules, byRuleId)
28566
+ };
28567
+ }
28568
+ function policyAssignmentRefusal(policyId, floor) {
28569
+ if (floor.locked) return "lock";
28570
+ const effective = policyId ?? DEFAULT_PACK_POLICY_ID;
28571
+ return isActionAtLeast(builtinPolicyToAction(effective), builtinPolicyToAction(floor.floor)) ? null : "floor";
28572
+ }
28573
+ function packEnablementRefusal(enabled, floor) {
28574
+ if (floor === null || enabled) return null;
28575
+ return "disable";
28576
+ }
28079
28577
 
28080
28578
  // ../../packages/persistence/src/semver.ts
28081
28579
  function parse3(version2) {
@@ -28169,8 +28667,19 @@ function ruleIdsOf(rulesJson) {
28169
28667
  return ids;
28170
28668
  }
28171
28669
  var SqliteInstalledPacksRepository = class {
28172
- constructor(db) {
28670
+ /**
28671
+ * `baseDir` is the `~/.aka` LAYOUT BASE, not the data dir — the control-plane
28672
+ * floor needs both halves of it (settings/ says whether this machine is
28673
+ * attached, data/ holds the cached bundle). It is optional because a caller
28674
+ * holding only a DatabaseSync — every test construction site, and any embedder
28675
+ * that opens the store itself — has no layout to point at, and such a caller
28676
+ * gets the pre-existing behaviour: no floor, no lock. Production threads it in
28677
+ * from `openLocalDatabase`, which is the single construction site that owns a
28678
+ * real `~/.aka`.
28679
+ */
28680
+ constructor(db, baseDir) {
28173
28681
  this.db = db;
28682
+ this.baseDir = baseDir;
28174
28683
  this.insertMissingStmt = db.prepare(
28175
28684
  `INSERT INTO installed_packs (id, namespace, pack_id, version, name, rules_json, enabled, created_at, updated_at)
28176
28685
  VALUES (:id, :namespace, :packId, :version, :name, :rulesJson, 1, :now, :now)
@@ -28192,11 +28701,17 @@ var SqliteInstalledPacksRepository = class {
28192
28701
  this.signatureStmt = db.prepare(
28193
28702
  `SELECT namespace, pack_id AS packId, version, rules_json AS rulesJson FROM available_packs`
28194
28703
  );
28704
+ this.packRulesStmt = db.prepare(
28705
+ `SELECT rules_json AS rulesJson FROM installed_packs
28706
+ WHERE namespace = ? AND pack_id = ?`
28707
+ );
28195
28708
  }
28196
28709
  db;
28710
+ baseDir;
28197
28711
  insertMissingStmt;
28198
28712
  upsertAvailableStmt;
28199
28713
  signatureStmt;
28714
+ packRulesStmt;
28200
28715
  /**
28201
28716
  * Record the running binary's detection inventory. Refreshes the
28202
28717
  * available_packs mirror (pruning packs the binary no longer ships) and
@@ -28238,7 +28753,7 @@ var SqliteInstalledPacksRepository = class {
28238
28753
  let behind = false;
28239
28754
  for (const row of rows) {
28240
28755
  const params = {
28241
- id: randomUUID3(),
28756
+ id: randomUUID4(),
28242
28757
  namespace: row.namespace,
28243
28758
  packId: row.packId,
28244
28759
  version: row.version,
@@ -28250,7 +28765,7 @@ var SqliteInstalledPacksRepository = class {
28250
28765
  if (stored === void 0 || !isMirrorDowngrade(row, stored)) {
28251
28766
  this.upsertAvailableStmt.run({
28252
28767
  ...params,
28253
- id: randomUUID3(),
28768
+ id: randomUUID4(),
28254
28769
  recordedBy: meta4?.recordedBy ?? null
28255
28770
  });
28256
28771
  } else {
@@ -28496,9 +29011,65 @@ var SqliteInstalledPacksRepository = class {
28496
29011
  // NOT on the hook path — so, unlike recordInventory, these surface errors to the
28497
29012
  // caller rather than swallowing them. Each returns whether a row matched, so the
28498
29013
  // caller can tell an edit from a no-such-detection.
29014
+ /**
29015
+ * The rules one installed pack owns, reduced to what a floor computation
29016
+ * reads. Display-tolerant parsing on purpose: a pack whose snapshot is
29017
+ * unreadable contributes no rules to a scan either, so it is not a detection
29018
+ * the control plane can be governing, and an empty list correctly imposes no
29019
+ * floor. Enabled state is deliberately not filtered — a disabled pack is one
29020
+ * the user can re-enable, and its assignment stays governed meanwhile.
29021
+ */
29022
+ packFloorRules(namespace, packId) {
29023
+ const row = getRow(this.packRulesStmt, [namespace, packId]);
29024
+ if (!row) return [];
29025
+ return parseRules(row.rulesJson).map((rule) => ({ id: rule.id, category: rule.category }));
29026
+ }
29027
+ /**
29028
+ * What the connected control plane imposes on one installed pack, or null on a
29029
+ * machine that is its own authority (standalone, no cached bundle, or a
29030
+ * repository constructed without a layout base).
29031
+ *
29032
+ * Exposed as a READ so a surface can render the constraint — grey out the
29033
+ * choices below the floor, mark a locked detection as locked — rather than
29034
+ * offer the user a picker whose selections it will then be told it may not
29035
+ * make. The refusal in `setPolicy` does not depend on any surface calling this.
29036
+ */
29037
+ policyFloor(namespace, packId) {
29038
+ if (this.baseDir === void 0) return null;
29039
+ return controlPlanePolicyFloor(this.packFloorRules(namespace, packId), this.baseDir);
29040
+ }
29041
+ /**
29042
+ * The same answer for several packs, keyed `namespace/packId` and carrying an
29043
+ * entry only for a pack the control plane actually governs.
29044
+ *
29045
+ * A surface listing every detection asks per pack, and asking through
29046
+ * `policyFloor` re-reads the settings, re-reads and re-parses the whole cached
29047
+ * bundle and rebuilds its indexes once per pack — the entire cost of one
29048
+ * answer, repeated for each row, on every render. This reads all of that once.
29049
+ * Packs whose rules the snapshot cannot produce simply contribute no entry,
29050
+ * exactly as the single-pack read returns null for them.
29051
+ */
29052
+ policyFloors(packs2) {
29053
+ const floors = /* @__PURE__ */ new Map();
29054
+ if (this.baseDir === void 0) return floors;
29055
+ const source = openControlPlaneFloors(this.baseDir);
29056
+ if (source === null) return floors;
29057
+ for (const pack of packs2) {
29058
+ const floor = source.floorFor(this.packFloorRules(pack.namespace, pack.packId));
29059
+ if (floor !== null) floors.set(`${pack.namespace}/${pack.packId}`, floor);
29060
+ }
29061
+ return floors;
29062
+ }
28499
29063
  /**
28500
29064
  * Assign (or clear, with null) the enforcement policy for one installed pack.
28501
- * `policyId` must be a known built-in id (monitor/warn/redact/block).
29065
+ * `policyId` must be a known built-in id (monitor/warn/redact/block/vault).
29066
+ *
29067
+ * On an ATTACHED machine the organization's bundle is a floor this refuses to
29068
+ * write below, and a detection the organization has authored a policy for is
29069
+ * refused outright — see policy-floor.ts for both, and for why the refusal is
29070
+ * a throw rather than a silently substituted value. This is the one device-local
29071
+ * write path for the assignment, so the check belongs here rather than on any
29072
+ * surface that offers the choice.
28502
29073
  */
28503
29074
  setPolicy(namespace, packId, policyId) {
28504
29075
  if (policyId !== null && !BuiltinPolicyId.safeParse(policyId).success) {
@@ -28506,14 +29077,38 @@ var SqliteInstalledPacksRepository = class {
28506
29077
  `Unknown policy '${policyId}'. Must be one of: ${KNOWN_BUILTIN_IDS.join(", ")}.`
28507
29078
  );
28508
29079
  }
29080
+ const requested = policyId;
29081
+ const floor = this.policyFloor(namespace, packId);
29082
+ if (floor !== null) {
29083
+ const refusal = policyAssignmentRefusal(requested, floor);
29084
+ if (refusal !== null) {
29085
+ throw new PolicyFloorError(`${namespace}/${packId}`, requested, floor.floor, refusal);
29086
+ }
29087
+ }
28509
29088
  const res = this.db.prepare(
28510
29089
  `UPDATE installed_packs SET policy_id = :policyId, updated_at = :now
28511
29090
  WHERE namespace = :namespace AND pack_id = :packId`
28512
29091
  ).run({ policyId, now: Date.now(), namespace, packId });
28513
29092
  return Number(res.changes) > 0;
28514
29093
  }
28515
- /** Enable or disable one installed pack. */
29094
+ /**
29095
+ * Enable or disable one installed pack.
29096
+ *
29097
+ * On an ATTACHED machine a detection the organization's bundle governs at all
29098
+ * may not be switched OFF here — see packEnablementRefusal for why that is not
29099
+ * merely another point below the floor, and why re-enabling stays open. Like
29100
+ * the assignment above, the check belongs at this write path rather than on a
29101
+ * surface: this is the one device-local writer of the column, and a refusal
29102
+ * that lived in a page would leave the CLI free.
29103
+ */
28516
29104
  setEnabled(namespace, packId, enabled) {
29105
+ const floor = this.policyFloor(namespace, packId);
29106
+ if (floor !== null) {
29107
+ const refusal = packEnablementRefusal(enabled, floor);
29108
+ if (refusal !== null) {
29109
+ throw new PolicyFloorError(`${namespace}/${packId}`, null, floor.floor, refusal);
29110
+ }
29111
+ }
28517
29112
  const res = this.db.prepare(
28518
29113
  `UPDATE installed_packs SET enabled = :enabled, updated_at = :now
28519
29114
  WHERE namespace = :namespace AND pack_id = :packId`
@@ -28599,7 +29194,7 @@ var SqliteInventoryRepository = class {
28599
29194
  };
28600
29195
 
28601
29196
  // ../../packages/persistence/src/repositories/inventory-assets.ts
28602
- import { randomUUID as randomUUID4 } from "crypto";
29197
+ import { randomUUID as randomUUID5 } from "crypto";
28603
29198
  var CATEGORY_ORDER = ["config", "skill", "mcp", "hook"];
28604
29199
  var VALID_HARNESS_IDS = new Set(HarnessId.options);
28605
29200
  var WORKTREE_CHECKOUT_FILTER = "(url IS NULL OR (url NOT LIKE '%/.claude/worktrees/%' AND url NOT LIKE '%\\.claude\\worktrees\\%'))";
@@ -29088,7 +29683,7 @@ var SqliteInventoryAssetsRepository = class {
29088
29683
  `INSERT INTO file_access_override (id, project_id, path, access, created_at, updated_at)
29089
29684
  VALUES (:id, :projectId, :path, :access, :now, :now)
29090
29685
  ON CONFLICT (project_id, path) DO UPDATE SET access = excluded.access, updated_at = excluded.updated_at`
29091
- ).run({ id: randomUUID4(), projectId, path, access, now: Date.now() });
29686
+ ).run({ id: randomUUID5(), projectId, path, access, now: Date.now() });
29092
29687
  }
29093
29688
  return true;
29094
29689
  }
@@ -29109,7 +29704,7 @@ var SqliteInventoryAssetsRepository = class {
29109
29704
  `INSERT INTO mcp_trust_override (id, asset_id, trust, created_at, updated_at)
29110
29705
  VALUES (:id, :assetId, :trust, :now, :now)
29111
29706
  ON CONFLICT (asset_id) DO UPDATE SET trust = excluded.trust, updated_at = excluded.updated_at`
29112
- ).run({ id: randomUUID4(), assetId, trust, now: Date.now() });
29707
+ ).run({ id: randomUUID5(), assetId, trust, now: Date.now() });
29113
29708
  }
29114
29709
  this.configRowsCache = void 0;
29115
29710
  return "ok";
@@ -29406,7 +30001,7 @@ var SqliteInventoryAssetsRepository = class {
29406
30001
  };
29407
30002
 
29408
30003
  // ../../packages/persistence/src/repositories/policies.ts
29409
- import { randomUUID as randomUUID5 } from "crypto";
30004
+ import { randomUUID as randomUUID6 } from "crypto";
29410
30005
  var SqlitePoliciesRepository = class {
29411
30006
  constructor(db) {
29412
30007
  this.db = db;
@@ -29441,7 +30036,7 @@ var SqlitePoliciesRepository = class {
29441
30036
  failOpenTransaction(this.db, () => {
29442
30037
  for (const [category, action] of Object.entries(DEFAULT_ACTIONS)) {
29443
30038
  stmt.run({
29444
- id: randomUUID5(),
30039
+ id: randomUUID6(),
29445
30040
  target: JSON.stringify({ category }),
29446
30041
  action,
29447
30042
  now: Date.now()
@@ -29461,7 +30056,7 @@ var SqlitePoliciesRepository = class {
29461
30056
  `INSERT INTO policies (id, scope, target, action, enabled, created_at, updated_at)
29462
30057
  VALUES (:id, 'global', :target, :action, 1, :now, :now)
29463
30058
  ON CONFLICT(scope, target) DO UPDATE SET action = excluded.action, enabled = 1, updated_at = excluded.updated_at`
29464
- ).run({ id: randomUUID5(), target: JSON.stringify({ category }), action, now });
30059
+ ).run({ id: randomUUID6(), target: JSON.stringify({ category }), action, now });
29465
30060
  }
29466
30061
  // Caps every global per-category policy currently set to block/redact down
29467
30062
  // to warn (see warn-era-cap.ts). Rule-targeted policies are untouched.
@@ -29529,7 +30124,7 @@ var SqlitePolicyCatalogRepository = class {
29529
30124
  };
29530
30125
 
29531
30126
  // ../../packages/persistence/src/repositories/project-files.ts
29532
- import { randomUUID as randomUUID6 } from "crypto";
30127
+ import { randomUUID as randomUUID7 } from "crypto";
29533
30128
  var SqliteProjectFilesRepository = class {
29534
30129
  constructor(db) {
29535
30130
  this.db = db;
@@ -29561,7 +30156,7 @@ var SqliteProjectFilesRepository = class {
29561
30156
  const stamp = Math.max(now, maxStamp + 1);
29562
30157
  for (const file2 of scan2.files) {
29563
30158
  this.upsertStmt.run({
29564
- id: randomUUID6(),
30159
+ id: randomUUID7(),
29565
30160
  projectId,
29566
30161
  path: file2.path,
29567
30162
  name: file2.name,
@@ -29575,9 +30170,9 @@ var SqliteProjectFilesRepository = class {
29575
30170
  };
29576
30171
 
29577
30172
  // ../../packages/persistence/src/repositories/resolutions.ts
29578
- import { randomUUID as randomUUID7 } from "crypto";
30173
+ import { randomUUID as randomUUID8 } from "crypto";
29579
30174
  var SqliteResolutionsRepository = class {
29580
- constructor(db, now = () => Date.now(), newId = () => randomUUID7()) {
30175
+ constructor(db, now = () => Date.now(), newId = () => randomUUID8()) {
29581
30176
  this.db = db;
29582
30177
  this.now = now;
29583
30178
  this.newId = newId;
@@ -29790,7 +30385,7 @@ var SqliteScanLedgerRepository = class {
29790
30385
  };
29791
30386
 
29792
30387
  // ../../packages/persistence/src/repositories/secret-vault.ts
29793
- import { randomUUID as randomUUID8 } from "crypto";
30388
+ import { randomUUID as randomUUID9 } from "crypto";
29794
30389
  function pageLimit(requested, fallback) {
29795
30390
  if (requested === void 0) return fallback;
29796
30391
  return Math.min(Math.max(1, Math.trunc(requested)), MAX_VAULT_PAGE_LIMIT);
@@ -29836,12 +30431,14 @@ var SELECT_COLUMNS = `
29836
30431
  ciphertext,
29837
30432
  nonce,
29838
30433
  auth_tag AS authTag,
30434
+ user_authorized AS userAuthorized,
29839
30435
  occurrence_count AS occurrenceCount,
29840
30436
  first_seen AS firstSeen,
29841
30437
  last_seen AS lastSeen`;
29842
30438
  function toRow(raw) {
29843
- const { provider, ...rest } = raw;
29844
- return provider === null ? rest : { ...rest, provider };
30439
+ const { provider, userAuthorized, ...rest } = raw;
30440
+ const row = { ...rest, userAuthorized: userAuthorized !== 0 };
30441
+ return provider === null ? row : { ...row, provider };
29845
30442
  }
29846
30443
  var SqliteSecretVaultRepository = class {
29847
30444
  constructor(db) {
@@ -29851,17 +30448,18 @@ var SqliteSecretVaultRepository = class {
29851
30448
  pointer_id, value_fingerprint, fingerprint_key_version, key_version,
29852
30449
  format_version, category, rule_id, masked_match, provider,
29853
30450
  ciphertext, nonce, auth_tag,
29854
- occurrence_count, first_seen, last_seen
30451
+ user_authorized, occurrence_count, first_seen, last_seen
29855
30452
  ) VALUES (
29856
30453
  :pointerId, :valueFingerprint, :fingerprintKeyVersion, :keyVersion,
29857
30454
  :formatVersion, :category, :ruleId, :maskedMatch, :provider,
29858
30455
  :ciphertext, :nonce, :authTag,
29859
- 1, :now, :now
30456
+ :userAuthorized, 1, :now, :now
29860
30457
  )`
29861
30458
  );
29862
30459
  this.bumpStmt = db.prepare(
29863
30460
  `UPDATE secret_vault
29864
- SET occurrence_count = occurrence_count + 1, last_seen = :now
30461
+ SET occurrence_count = occurrence_count + 1, last_seen = :now,
30462
+ user_authorized = max(user_authorized, :userAuthorized)
29865
30463
  WHERE value_fingerprint = :valueFingerprint`
29866
30464
  );
29867
30465
  this.byPointerStmt = db.prepare(
@@ -29881,6 +30479,7 @@ var SqliteSecretVaultRepository = class {
29881
30479
  SET value_fingerprint = :valueFingerprint, fingerprint_key_version = :fingerprintKeyVersion
29882
30480
  WHERE pointer_id = :pointerId`
29883
30481
  );
30482
+ this.deleteByPointerStmt = db.prepare(`DELETE FROM secret_vault WHERE pointer_id = :pointerId`);
29884
30483
  this.derefStmt = db.prepare(
29885
30484
  `INSERT INTO secret_vault_deref (id, pointer_id, at, target, reason, outcome, grant_id, pointer_count)
29886
30485
  VALUES (:id, :pointerId, :at, :target, :reason, :outcome, :grantId, :pointerCount)`
@@ -29894,6 +30493,7 @@ var SqliteSecretVaultRepository = class {
29894
30493
  listStmt;
29895
30494
  replaceCiphertextStmt;
29896
30495
  refreshFingerprintStmt;
30496
+ deleteByPointerStmt;
29897
30497
  derefStmt;
29898
30498
  /**
29899
30499
  * Vault a value, or record another sighting of one already vaulted. Keyed on
@@ -29902,6 +30502,11 @@ var SqliteSecretVaultRepository = class {
29902
30502
  * pointer, category and ciphertext, so the same secret always resolves to one
29903
30503
  * wire token. `minted` is true only when this call created the row.
29904
30504
  *
30505
+ * `userAuthorized` is the one field a repeat call may still change, and only
30506
+ * upwards: it records that a PERSON asked for this value to be replaced, and
30507
+ * the row is shared with every automatic path that vaults the same value. See
30508
+ * `bumpStmt` for why clearing it is the defect this shape exists to refuse.
30509
+ *
29905
30510
  * The read-then-write runs in one IMMEDIATE transaction so two concurrent
29906
30511
  * writers cannot both decide they are minting.
29907
30512
  */
@@ -29928,13 +30533,18 @@ var SqliteSecretVaultRepository = class {
29928
30533
  ciphertext: input2.ciphertext,
29929
30534
  nonce: input2.nonce,
29930
30535
  authTag: input2.authTag,
30536
+ userAuthorized: input2.userAuthorized === true ? 1 : 0,
29931
30537
  now
29932
30538
  })
29933
30539
  );
29934
30540
  minted = true;
29935
30541
  return;
29936
30542
  }
29937
- this.bumpStmt.run({ valueFingerprint: input2.valueFingerprint, now });
30543
+ this.bumpStmt.run({
30544
+ valueFingerprint: input2.valueFingerprint,
30545
+ userAuthorized: input2.userAuthorized === true ? 1 : 0,
30546
+ now
30547
+ });
29938
30548
  },
29939
30549
  "IMMEDIATE"
29940
30550
  );
@@ -29994,6 +30604,42 @@ var SqliteSecretVaultRepository = class {
29994
30604
  );
29995
30605
  return destroyed;
29996
30606
  }
30607
+ /**
30608
+ * Destroy the named entries and report WHICH ones went — the scoped
30609
+ * counterpart to `purgeAll`, for a caller that has already put those specific
30610
+ * values back where they came from. Ids the store does not hold are absent
30611
+ * from the answer rather than an error, so a set assembled from a stale read
30612
+ * is not a fault. The deref audit is left alone, exactly as the purge leaves
30613
+ * it.
30614
+ *
30615
+ * The ids come back rather than a count because the caller's next act is to
30616
+ * write a purge row per destroyed entry, and a record of destruction has to
30617
+ * be a record of what was really destroyed: a selection is a claim about a
30618
+ * read that has since gone stale, and auditing from it invents a purge for an
30619
+ * entry still sitting in the vault.
30620
+ *
30621
+ * One transaction over the whole set rather than a statement per id: the
30622
+ * caller hands this the result of a restore pass it has completed, and a
30623
+ * fault partway through must leave the vault as it was found rather than
30624
+ * destroying a prefix of it. The vault holds the only copy of what a pointer
30625
+ * stands for, so half a delete is not a state anything can recover from.
30626
+ */
30627
+ deleteByPointerIds(pointerIds) {
30628
+ if (pointerIds.length === 0) return [];
30629
+ const deleted = [];
30630
+ withTransaction(
30631
+ this.db,
30632
+ () => {
30633
+ for (const pointerId of pointerIds) {
30634
+ if (Number(this.deleteByPointerStmt.run({ pointerId }).changes) > 0) {
30635
+ deleted.push(pointerId);
30636
+ }
30637
+ }
30638
+ },
30639
+ "IMMEDIATE"
30640
+ );
30641
+ return deleted;
30642
+ }
29997
30643
  /**
29998
30644
  * Record (or re-stamp) one place a pointer has been written. One row per
29999
30645
  * (pointer, location); a re-sighting bumps last_seen. Best-effort bookkeeping
@@ -30006,7 +30652,7 @@ var SqliteSecretVaultRepository = class {
30006
30652
  VALUES (:id, :pointerId, :location, :kind, :now, :now)
30007
30653
  ON CONFLICT (pointer_id, location) DO UPDATE SET last_seen = :now`
30008
30654
  ).run({
30009
- id: randomUUID8(),
30655
+ id: randomUUID9(),
30010
30656
  pointerId: entry.pointerId,
30011
30657
  location: entry.location,
30012
30658
  kind: entry.kind,
@@ -30519,15 +31165,15 @@ var SqliteSecurityRepository = class {
30519
31165
  const from = now - RANGE_DAYS[range] * DAY_MS4;
30520
31166
  const rows = allRows(
30521
31167
  this.db.prepare(
30522
- `SELECT json_extract(e.attributes, '$.repo') AS repo, count(*) AS c
31168
+ `SELECT e.repo AS repo, count(*) AS c
30523
31169
  FROM inspection_findings f
30524
31170
  JOIN audit_events e ON e.id = f.audit_event_id
30525
31171
  WHERE e.started_at >= :from AND e.started_at < :to
30526
31172
  AND e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
30527
- AND json_extract(e.attributes, '$.repo') IS NOT NULL
30528
- AND json_extract(e.attributes, '$.repo') != ''
30529
- GROUP BY repo
30530
- ORDER BY c DESC, repo
31173
+ AND e.repo IS NOT NULL
31174
+ AND e.repo != ''
31175
+ GROUP BY e.repo
31176
+ ORDER BY c DESC, e.repo
30531
31177
  LIMIT :limit`
30532
31178
  ),
30533
31179
  { from, to: now, limit }
@@ -30589,7 +31235,7 @@ var SqliteSecurityRepository = class {
30589
31235
  `SELECT f.finding_key AS finding_key,
30590
31236
  d.rule_id AS rule_id,
30591
31237
  d.severity AS severity,
30592
- json_extract(e.attributes, '$.file_path') AS path,
31238
+ e.file_path AS path,
30593
31239
  COALESCE(f.first_detected_at, e.started_at) AS first_detected_at,
30594
31240
  latest.resolved_at AS latest_resolved_at
30595
31241
  FROM ${LATEST_RESOLUTION_BY_KEY_SQL} latest
@@ -30642,7 +31288,7 @@ var SqliteSecurityRepository = class {
30642
31288
  };
30643
31289
 
30644
31290
  // ../../packages/persistence/src/repositories/shares.ts
30645
- import { randomUUID as randomUUID9 } from "crypto";
31291
+ import { randomUUID as randomUUID10 } from "crypto";
30646
31292
  var MAX_EGRESS_CALL_SITES_PER_PROJECT = 5e3;
30647
31293
  var IN_CHUNK = 500;
30648
31294
  var KIND_ORDER = ["provider", "internal", "external", "ip"];
@@ -30730,7 +31376,7 @@ function buildSummary(dest, endpoints) {
30730
31376
  callSiteCount,
30731
31377
  transports: distinctTransports(transports),
30732
31378
  dataClasses: distinctDataClasses(dataClasses),
30733
- review: buildReviewInfo(dest.trust, transports),
31379
+ review: buildReviewInfo(dest.trust, transports, dest.overrideDecision !== null),
30734
31380
  network: dest.kind === "provider" ? null : parseNetwork(dest.networkJson),
30735
31381
  endpoints: endpoints.map(toEndpointSummary)
30736
31382
  };
@@ -30757,7 +31403,7 @@ function buildDetail(dest, endpoints, callSites) {
30757
31403
  lastSeen: new Date(lastSeenMs).toISOString(),
30758
31404
  transports: distinctTransports(transports),
30759
31405
  dataClasses: distinctDataClasses(endpoints.map((e) => e.dataClass)),
30760
- review: buildReviewInfo(dest.trust, transports),
31406
+ review: buildReviewInfo(dest.trust, transports, dest.overrideDecision !== null),
30761
31407
  network: dest.kind === "provider" ? null : parseNetwork(dest.networkJson),
30762
31408
  note: dest.note,
30763
31409
  endpoints: endpoints.map((ep) => ({
@@ -30786,7 +31432,11 @@ var SqliteSharesRepository = class {
30786
31432
  FROM share_destination d
30787
31433
  LEFT JOIN share_endpoint e ON e.destination_id = d.id
30788
31434
  AND e.transport IN ${PLAINTEXT_TRANSPORT_SQL}
30789
- WHERE d.trust IN ('unverified', 'ip') OR e.id IS NOT NULL`
31435
+ WHERE (d.trust IN ('unverified', 'ip') OR e.id IS NOT NULL)
31436
+ AND NOT EXISTS (
31437
+ SELECT 1 FROM egress_decision_override o
31438
+ WHERE o.host = d.host OR (o.destination_id = d.id AND o.host IS NULL)
31439
+ )`
30790
31440
  );
30791
31441
  const kindCounts = countBy(
30792
31442
  this.db,
@@ -30898,7 +31548,7 @@ var SqliteSharesRepository = class {
30898
31548
  (id, destination_id, host, decision, created_at, updated_at)
30899
31549
  VALUES (:id, :destinationId, :host, :decision, :now, :now)`
30900
31550
  ).run({
30901
- id: randomUUID9(),
31551
+ id: randomUUID10(),
30902
31552
  destinationId,
30903
31553
  host: dest.host,
30904
31554
  decision,
@@ -31047,7 +31697,7 @@ var SqliteSharesRepository = class {
31047
31697
  let destinationId = destIds.get(hit.host);
31048
31698
  if (destinationId === void 0) {
31049
31699
  destStmt.run({
31050
- id: randomUUID9(),
31700
+ id: randomUUID10(),
31051
31701
  kind: hit.kind,
31052
31702
  name: hit.name,
31053
31703
  host: hit.host,
@@ -31063,7 +31713,7 @@ var SqliteSharesRepository = class {
31063
31713
  let endpointId = endpointIds.get(endpointKey);
31064
31714
  if (endpointId === void 0) {
31065
31715
  endpointStmt.run({
31066
- id: randomUUID9(),
31716
+ id: randomUUID10(),
31067
31717
  destinationId,
31068
31718
  method: hit.method,
31069
31719
  transport: hit.transport,
@@ -31076,7 +31726,7 @@ var SqliteSharesRepository = class {
31076
31726
  endpointIds.set(endpointKey, endpointId);
31077
31727
  }
31078
31728
  siteStmt.run({
31079
- id: randomUUID9(),
31729
+ id: randomUUID10(),
31080
31730
  endpointId,
31081
31731
  project: input2.project,
31082
31732
  projectKey: input2.projectKey,
@@ -31441,6 +32091,7 @@ function purgeSampleData(db) {
31441
32091
  }
31442
32092
 
31443
32093
  // ../../packages/persistence/src/database.ts
32094
+ var CAPTURE_GRAIN = new Set(EventKind.options);
31444
32095
  var UNSAFE_TEST_ONLY_RAW_HANDLE = /* @__PURE__ */ Symbol(
31445
32096
  "aka.persistence.unsafeTestOnlyRawHandle"
31446
32097
  );
@@ -31488,7 +32139,7 @@ function backupLegacyStore(db, file2) {
31488
32139
  discardStore(file2, backup);
31489
32140
  return backup;
31490
32141
  }
31491
- function openAndInitialize(file2) {
32142
+ function openAndInitialize(file2, base) {
31492
32143
  let db = openWithPragmas(file2);
31493
32144
  try {
31494
32145
  if (isForeignSqliteLineage(db)) {
@@ -31501,7 +32152,7 @@ function openAndInitialize(file2) {
31501
32152
  applyMigrations(db, file2);
31502
32153
  tightenPerms(file2);
31503
32154
  const policies = new SqlitePoliciesRepository(db);
31504
- const installedPacks = new SqliteInstalledPacksRepository(db);
32155
+ const installedPacks = new SqliteInstalledPacksRepository(db, base);
31505
32156
  const repositories = {
31506
32157
  events: new SqliteEventsRepository(db),
31507
32158
  findings: new SqliteFindingsRepository(db),
@@ -31537,7 +32188,7 @@ function openAndInitialize(file2) {
31537
32188
  }
31538
32189
  function openLocalDatabase(dir) {
31539
32190
  ensureDataDirSync(dir);
31540
- const file2 = join4(dir, DB_FILENAME);
32191
+ const file2 = join7(dir, DB_FILENAME);
31541
32192
  reapStalePartials(file2);
31542
32193
  const {
31543
32194
  db,
@@ -31565,7 +32216,13 @@ function openLocalDatabase(dir) {
31565
32216
  inspectionDefinitions,
31566
32217
  inspectionFindings,
31567
32218
  configInventory
31568
- } = openAndInitialize(file2);
32219
+ } = openAndInitialize(
32220
+ file2,
32221
+ // `dir` is always `<base>/data` — every caller resolves it through
32222
+ // `dataDir()` — so its parent is the `~/.aka` base the layout splits into
32223
+ // settings/ and data/, and the pack-policy floor needs both halves.
32224
+ dirname2(dir)
32225
+ );
31569
32226
  function captureRowId(event) {
31570
32227
  return captureId(
31571
32228
  event.metadata?.sessionId ?? null,
@@ -31578,6 +32235,21 @@ function openLocalDatabase(dir) {
31578
32235
  historySync.markSynced([captureRowId(event)], atMs);
31579
32236
  });
31580
32237
  }
32238
+ function markCaptureOwed(event) {
32239
+ failOpenTransaction(db, () => {
32240
+ historySync.markCaptureOwed(captureRowId(event));
32241
+ });
32242
+ }
32243
+ function markAuditEventsDelivered(events2, atMs) {
32244
+ const stampable = events2.filter((event) => !CAPTURE_GRAIN.has(event.eventType));
32245
+ if (stampable.length === 0) return;
32246
+ failOpenTransaction(db, () => {
32247
+ historySync.markSynced(
32248
+ stampable.map((event) => event.id),
32249
+ atMs
32250
+ );
32251
+ });
32252
+ }
31581
32253
  function recordCapture(event, detected) {
31582
32254
  failOpenTransaction(db, () => {
31583
32255
  const sessionId = event.metadata?.sessionId;
@@ -31664,7 +32336,7 @@ function openLocalDatabase(dir) {
31664
32336
  const definitionId = definitionIds.get(`${finding2.ruleId}@${finding2.version}`);
31665
32337
  if (!definitionId) continue;
31666
32338
  inspectionFindings.insertFinding({
31667
- id: randomUUID10(),
32339
+ id: randomUUID11(),
31668
32340
  auditEventId: record2.scanEvent.id,
31669
32341
  inspectionDefinitionId: definitionId,
31670
32342
  span: finding2.span,
@@ -31760,6 +32432,8 @@ function openLocalDatabase(dir) {
31760
32432
  inspectionFindings,
31761
32433
  recordCapture,
31762
32434
  markCaptureDelivered,
32435
+ markCaptureOwed,
32436
+ markAuditEventsDelivered,
31763
32437
  ensureInventory,
31764
32438
  recordConfigScan,
31765
32439
  recordProjectFiles,
@@ -31778,32 +32452,18 @@ function openLocalDatabase(dir) {
31778
32452
  };
31779
32453
  }
31780
32454
 
31781
- // ../../packages/persistence/src/file-lock.ts
31782
- import { randomUUID as randomUUID11 } from "crypto";
31783
- import {
31784
- closeSync,
31785
- existsSync as existsSync2,
31786
- openSync,
31787
- readFileSync as readFileSync2,
31788
- rmSync as rmSync5,
31789
- statSync as statSync3,
31790
- writeFileSync as writeFileSync2
31791
- } from "fs";
31792
- import { hostname as hostname3 } from "os";
31793
- var PARK = new Int32Array(new SharedArrayBuffer(4));
31794
-
31795
32455
  // ../../packages/persistence/src/finding-key.ts
31796
32456
  import { createHash as createHash3 } from "crypto";
31797
32457
 
31798
32458
  // ../../packages/persistence/src/fingerprint.ts
31799
32459
  import { createHmac, randomBytes } from "crypto";
31800
- import { existsSync as existsSync3, readFileSync as readFileSync3 } from "fs";
31801
- import { join as join5 } from "path";
32460
+ import { existsSync as existsSync3, readFileSync as readFileSync6 } from "fs";
32461
+ import { join as join8 } from "path";
31802
32462
  import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
31803
32463
  var EXCEPTION_KEY_FILENAME = "exception.key";
31804
32464
  var KEY_MATERIAL_BYTES = 32;
31805
32465
  function keyFilePath(dataDir2) {
31806
- return join5(dataDir2, EXCEPTION_KEY_FILENAME);
32466
+ return join8(dataDir2, EXCEPTION_KEY_FILENAME);
31807
32467
  }
31808
32468
  function parseKeyFile(raw) {
31809
32469
  const parsed2 = JSON.parse(raw);
@@ -31826,7 +32486,7 @@ function parseKeyFile(raw) {
31826
32486
  function readFingerprintKey(dataDir2) {
31827
32487
  let raw;
31828
32488
  try {
31829
- raw = readFileSync3(keyFilePath(dataDir2), "utf8");
32489
+ raw = readFileSync6(keyFilePath(dataDir2), "utf8");
31830
32490
  } catch (err) {
31831
32491
  if (err.code === "ENOENT") return null;
31832
32492
  throw err instanceof Error ? err : new Error(String(err));
@@ -31836,146 +32496,12 @@ function readFingerprintKey(dataDir2) {
31836
32496
 
31837
32497
  // ../../packages/persistence/src/history-preview.ts
31838
32498
  import { existsSync as existsSync4 } from "fs";
31839
- import { join as join6 } from "path";
32499
+ import { join as join9 } from "path";
31840
32500
  import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
31841
32501
 
31842
- // ../../packages/persistence/src/local-layout.ts
31843
- import { renameSync as renameSync3 } from "fs";
31844
- import { mkdir } from "fs/promises";
31845
- import { homedir } from "os";
31846
- import { join as join7 } from "path";
31847
- function defaultDataDir() {
31848
- return join7(homedir(), ".aka");
31849
- }
31850
- function settingsDir(base = defaultDataDir()) {
31851
- return join7(base, "settings");
31852
- }
31853
- function dataDir(base = defaultDataDir()) {
31854
- return join7(base, "data");
31855
- }
31856
- function dbPath(base = defaultDataDir()) {
31857
- return join7(dataDir(base), "aka.db");
31858
- }
31859
- function keysDir(base = defaultDataDir()) {
31860
- return join7(base, "keys");
31861
- }
31862
- async function ensureDataDir(dir = defaultDataDir()) {
31863
- await mkdir(dir, { recursive: true, mode: DATA_DIR_MODE });
31864
- tightenDir(dir);
31865
- }
31866
- function ensureLayoutDirSync(dir = defaultDataDir()) {
31867
- ensureDataDirSync(dir);
31868
- }
31869
- function migrateLegacyLayout(base = defaultDataDir()) {
31870
- const moves = [
31871
- { name: "config.json", dest: settingsDir(base) },
31872
- { name: "policy-cache.json", dest: dataDir(base) }
31873
- ];
31874
- for (const { name, dest } of moves) {
31875
- try {
31876
- ensureDataDirSync(dest);
31877
- const moved = join7(dest, name);
31878
- renameSync3(join7(base, name), moved);
31879
- tightenFile(moved);
31880
- } catch {
31881
- }
31882
- }
31883
- }
31884
-
31885
- // ../../packages/persistence/src/managed-settings.ts
31886
- import { readFileSync as readFileSync4 } from "fs";
31887
- import { posix, win32 } from "path";
31888
- function managedSettingsPaths(platform2 = process.platform) {
31889
- if (platform2 === "darwin") {
31890
- return [
31891
- posix.join("/Library", "Application Support", "AKASecurity", MANAGED_SETTINGS_FILENAME),
31892
- posix.join("/Library", "Managed Preferences", MANAGED_SETTINGS_FILENAME)
31893
- ];
31894
- }
31895
- if (platform2 === "win32") {
31896
- return [win32.join("C:\\", "ProgramData", "AKASecurity", MANAGED_SETTINGS_FILENAME)];
31897
- }
31898
- return [posix.join("/etc", "aka", MANAGED_SETTINGS_FILENAME)];
31899
- }
31900
- function readManagedSettings(paths = managedSettingsPaths()) {
31901
- for (const path of paths) {
31902
- let text;
31903
- try {
31904
- text = readFileSync4(path, "utf8");
31905
- } catch {
31906
- continue;
31907
- }
31908
- const record2 = parseJsonObject(text);
31909
- if (!record2) continue;
31910
- const parsed2 = ManagedSettings.safeParse(record2);
31911
- if (parsed2.success) return parsed2.data;
31912
- }
31913
- return null;
31914
- }
31915
- function overlayManagedSettings(settings, managed, now = () => /* @__PURE__ */ new Date()) {
31916
- if (!managed) return settings;
31917
- const { values } = managed;
31918
- const merged = { ...settings };
31919
- if (values.runMode !== void 0) merged.runMode = values.runMode;
31920
- if (values.controlPlane !== void 0) {
31921
- merged.controlPlane = {
31922
- ...values.controlPlane,
31923
- // The administrator pinned WHICH deployment, not WHEN this machine
31924
- // joined it. Keep the user's own attach time when the endpoint is
31925
- // unchanged, so a managed machine does not appear to re-attach on every
31926
- // read; stamp a fresh one when the administrator moved it.
31927
- attachedAt: settings.controlPlane?.endpoint === values.controlPlane.endpoint ? settings.controlPlane.attachedAt : now().toISOString()
31928
- };
31929
- }
31930
- if (values.historicalAccess !== void 0) merged.historicalAccess = values.historicalAccess;
31931
- if (values.vaultKeyCustody !== void 0) merged.vaultKeyCustody = values.vaultKeyCustody;
31932
- if (values.vaultInlineReveal !== void 0) merged.vaultInlineReveal = values.vaultInlineReveal;
31933
- if (values.dataSharesInPlace !== void 0) merged.dataSharesInPlace = values.dataSharesInPlace;
31934
- if (values.vaultConsent !== void 0) {
31935
- merged.vaultConsent = values.vaultConsent ? (
31936
- // Keep an existing valid grant so its acknowledgedAt survives; mint one
31937
- // at the current version otherwise.
31938
- settings.vaultConsent?.version === VAULT_CONSENT_VERSION ? settings.vaultConsent : { acknowledgedAt: now().toISOString(), version: VAULT_CONSENT_VERSION }
31939
- ) : void 0;
31940
- }
31941
- if (values.modelJudgeConsent !== void 0) {
31942
- merged.modelJudgeConsent = values.modelJudgeConsent ? settings.modelJudgeConsent?.payloadVersion === MODEL_JUDGE_PAYLOAD_VERSION ? settings.modelJudgeConsent : {
31943
- acknowledgedAt: now().toISOString(),
31944
- payloadVersion: MODEL_JUDGE_PAYLOAD_VERSION
31945
- } : void 0;
31946
- }
31947
- return merged;
31948
- }
31949
-
31950
- // ../../packages/persistence/src/settings.ts
31951
- import { readFileSync as readFileSync5 } from "fs";
31952
- import { join as join8 } from "path";
31953
- var SETTINGS_FILENAME = "settings.json";
31954
- function readWorkspaceSettings(base = defaultDataDir()) {
31955
- return overlayManagedSettings(readUserSettings(base), readManagedSettings());
31956
- }
31957
- function readUserSettings(base) {
31958
- const record2 = readJson(join8(settingsDir(base), SETTINGS_FILENAME));
31959
- if (!record2) return defaultWorkspaceSettings();
31960
- try {
31961
- return WorkspaceSettings.parse(record2);
31962
- } catch {
31963
- return defaultWorkspaceSettings();
31964
- }
31965
- }
31966
- function readJson(file2) {
31967
- let text;
31968
- try {
31969
- text = readFileSync5(file2, "utf8");
31970
- } catch {
31971
- return null;
31972
- }
31973
- return parseJsonObject(text) ?? null;
31974
- }
31975
-
31976
32502
  // ../../packages/persistence/src/store-symlinks.ts
31977
32503
  import { existsSync as existsSync5, lstatSync as lstatSync3, readlinkSync, realpathSync, statSync as statSync4 } from "fs";
31978
- import { dirname as dirname2, join as join9, resolve } from "path";
32504
+ import { dirname as dirname3, join as join10, resolve } from "path";
31979
32505
  var STORE_DB = "the store database (including the prompt corpus)";
31980
32506
  var STORE_SETTINGS = "your settings file";
31981
32507
  function storeContents(home) {
@@ -31984,7 +32510,7 @@ function storeContents(home) {
31984
32510
  [settingsDir(home), STORE_SETTINGS],
31985
32511
  [dataDir(home), STORE_DB],
31986
32512
  [keysDir(home), "the vault key"],
31987
- [join9(settingsDir(home), "settings.json"), STORE_SETTINGS],
32513
+ [join10(settingsDir(home), "settings.json"), STORE_SETTINGS],
31988
32514
  [dbPath(home), STORE_DB]
31989
32515
  ]);
31990
32516
  }
@@ -32012,7 +32538,7 @@ function linkTarget(path) {
32012
32538
  try {
32013
32539
  return realpathSync(path);
32014
32540
  } catch {
32015
- return resolve(dirname2(path), readlinkSync(path));
32541
+ return resolve(dirname3(path), readlinkSync(path));
32016
32542
  }
32017
32543
  }
32018
32544
  function targetMode(path, platform2) {
@@ -32036,19 +32562,19 @@ import {
32036
32562
  // ../../packages/persistence/src/vault/key-provider.ts
32037
32563
  import { execFileSync } from "child_process";
32038
32564
  import { randomBytes as randomBytes2 } from "crypto";
32039
- import { chmodSync as chmodSync3, readFileSync as readFileSync6, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
32040
- import { join as join10 } from "path";
32565
+ import { chmodSync as chmodSync3, readFileSync as readFileSync7, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
32566
+ import { join as join11 } from "path";
32041
32567
 
32042
32568
  // ../../packages/persistence/src/vault/vault.ts
32043
32569
  import { randomBytes as randomBytes3, randomUUID as randomUUID12 } from "crypto";
32044
32570
 
32045
32571
  // ../../packages/persistence/src/warn-era-cap.ts
32046
32572
  import { existsSync as existsSync6, writeFileSync as writeFileSync4 } from "fs";
32047
- import { join as join11 } from "path";
32573
+ import { join as join12 } from "path";
32048
32574
  var MARKER = "warn-era-capped";
32049
32575
  function capWarnEraEnforcementOnce(db, policyMode, dataDir2) {
32050
32576
  if (policyMode !== "warn") return { capped: 0, skipped: "not-warn" };
32051
- const marker = join11(dataDir2, MARKER);
32577
+ const marker = join12(dataDir2, MARKER);
32052
32578
  if (existsSync6(marker)) return { capped: 0, skipped: "already-run" };
32053
32579
  const capped = db.policies.capCategoryActions();
32054
32580
  writeFileSync4(marker, `${new Date(Date.now()).toISOString()}
@@ -32092,6 +32618,307 @@ function toEgressIngestRequest(input2) {
32092
32618
  };
32093
32619
  }
32094
32620
 
32621
+ // ../../packages/remote/src/http.ts
32622
+ import { request as httpRequest } from "http";
32623
+ import { request as httpsRequest } from "https";
32624
+ var DEFAULT_TIMEOUT_MS = 1e4;
32625
+ var MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
32626
+ var RemoteRequestError = class extends Error {
32627
+ constructor(status) {
32628
+ super(`control-plane request failed with status ${String(status)}`);
32629
+ this.status = status;
32630
+ this.name = "RemoteRequestError";
32631
+ }
32632
+ status;
32633
+ };
32634
+ var RemoteRouteAbsent = class extends Error {
32635
+ constructor(route) {
32636
+ super(`control plane does not serve ${route}`);
32637
+ this.route = route;
32638
+ this.name = "RemoteRouteAbsent";
32639
+ }
32640
+ route;
32641
+ };
32642
+ var RemoteRequestInvalid = class extends Error {
32643
+ constructor(route, cause) {
32644
+ super(`refusing to send a malformed body to ${route}`);
32645
+ this.cause = cause;
32646
+ this.name = "RemoteRequestInvalid";
32647
+ }
32648
+ cause;
32649
+ };
32650
+ var RemoteResponseInvalid = class extends Error {
32651
+ constructor(route, detail) {
32652
+ super(`control plane answered ${route} with ${detail}`);
32653
+ this.name = "RemoteResponseInvalid";
32654
+ }
32655
+ };
32656
+ var RemoteTransportError = class extends Error {
32657
+ /**
32658
+ * The status the peer sent, when headers arrived and only the BODY was
32659
+ * refused.
32660
+ *
32661
+ * Undefined for the ordinary case this class was written for — no answer at
32662
+ * all. It exists because two paths reject after a status has already been
32663
+ * delivered: an oversized body and an aborted response. Discarding it there
32664
+ * reported a deployment answering 401 with a verbose body as a network
32665
+ * outage, which sends the reader to look at their network instead of their
32666
+ * credential.
32667
+ */
32668
+ constructor(reason, status) {
32669
+ super(`control-plane request did not complete: ${reason}`);
32670
+ this.status = status;
32671
+ this.name = "RemoteTransportError";
32672
+ }
32673
+ status;
32674
+ };
32675
+ async function send(options) {
32676
+ const url2 = new URL(options.url);
32677
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
32678
+ const send_ = url2.protocol === "http:" ? httpRequest : httpsRequest;
32679
+ const requestOptions = {
32680
+ method: options.method,
32681
+ headers: {
32682
+ // CALLER HEADERS FIRST, so this module's own are not overridable. Spread
32683
+ // last they win, and two of the values below are ones no caller may
32684
+ // replace: `x-api-key` is the credential, and `content-length` is the
32685
+ // byte count that stops a multi-byte body being truncated by the
32686
+ // receiver. `SendOptions.headers` is a free-form record on an exported
32687
+ // function, so "no caller does that today" is not the guarantee to rely
32688
+ // on. The one header any caller actually passes — `if-none-match` on the
32689
+ // conditional GET — is untouched by this order.
32690
+ ...options.headers,
32691
+ // The credential. One header, matching what the deployment authenticates
32692
+ // on; a second copy in an `Authorization` header would be one more place
32693
+ // it can be logged by an intermediary for no gain.
32694
+ //
32695
+ // Spread conditionally rather than assigned as `undefined`: Node's header
32696
+ // handling and `content-length` bookkeeping treat a present-but-undefined
32697
+ // key differently from an absent one, and "the header is not there" is
32698
+ // the property the attach flow needs.
32699
+ ...options.apiKey === void 0 ? {} : { "x-api-key": options.apiKey },
32700
+ accept: "application/json",
32701
+ ...options.body === void 0 ? {} : {
32702
+ "content-type": "application/json",
32703
+ // Byte length, not string length: a multi-byte body sent with a
32704
+ // character count is truncated by the receiver.
32705
+ "content-length": String(Buffer.byteLength(options.body))
32706
+ }
32707
+ }
32708
+ };
32709
+ return new Promise((resolve2, reject) => {
32710
+ let settled = false;
32711
+ const fail = (reason, status) => {
32712
+ if (settled) return;
32713
+ settled = true;
32714
+ reject(new RemoteTransportError(reason, status));
32715
+ };
32716
+ const req = send_(url2, requestOptions, (res) => {
32717
+ const chunks = [];
32718
+ let size = 0;
32719
+ res.on("data", (chunk) => {
32720
+ size += chunk.length;
32721
+ if (size > MAX_RESPONSE_BYTES) {
32722
+ fail(`response exceeded ${String(MAX_RESPONSE_BYTES)} bytes`, res.statusCode);
32723
+ res.destroy();
32724
+ req.destroy();
32725
+ return;
32726
+ }
32727
+ chunks.push(chunk);
32728
+ });
32729
+ res.on("aborted", () => {
32730
+ fail("the response was aborted", res.statusCode);
32731
+ });
32732
+ res.on("end", () => {
32733
+ if (settled) return;
32734
+ settled = true;
32735
+ resolve2({
32736
+ status: res.statusCode ?? 0,
32737
+ headers: res.headers,
32738
+ body: Buffer.concat(chunks).toString("utf8")
32739
+ });
32740
+ });
32741
+ });
32742
+ const deadline = setTimeout(() => {
32743
+ fail(`no response within ${String(timeoutMs)}ms`);
32744
+ req.destroy();
32745
+ }, timeoutMs);
32746
+ deadline.unref();
32747
+ req.on("upgrade", (_res, socket) => {
32748
+ fail("the deployment answered with a protocol upgrade");
32749
+ socket.destroy();
32750
+ });
32751
+ req.on("close", () => {
32752
+ fail("the connection closed before a response was read");
32753
+ clearTimeout(deadline);
32754
+ });
32755
+ req.on("error", (err) => {
32756
+ fail(err.message);
32757
+ });
32758
+ if (options.body !== void 0) req.write(options.body);
32759
+ req.end();
32760
+ });
32761
+ }
32762
+
32763
+ // ../../packages/remote/src/client.ts
32764
+ var ROUTES = {
32765
+ events: "/v1/events",
32766
+ auditEvents: "/v1/audit-events",
32767
+ auditEventsBatch: "/v1/audit-events/batch",
32768
+ inventory: "/v1/inventory",
32769
+ storePosture: "/v1/store-posture",
32770
+ policyBundle: "/v1/policy-bundle",
32771
+ whoami: "/v1/plugin/whoami",
32772
+ shares: "/v1/shares",
32773
+ commands: "/v1/plugin/commands"
32774
+ };
32775
+ function ackRoute(id) {
32776
+ return `${ROUTES.commands}/${encodeURIComponent(id)}/ack`;
32777
+ }
32778
+ function headerValue(response, name) {
32779
+ const raw = response.headers[name];
32780
+ if (raw === void 0) return void 0;
32781
+ return Array.isArray(raw) ? raw[0] : raw;
32782
+ }
32783
+ function okBody(response) {
32784
+ if (response.status < 200 || response.status >= 300) {
32785
+ throw new RemoteRequestError(response.status);
32786
+ }
32787
+ return response.body;
32788
+ }
32789
+ function parsed(schema, body, route) {
32790
+ let json2;
32791
+ try {
32792
+ json2 = JSON.parse(body);
32793
+ } catch {
32794
+ throw new RemoteResponseInvalid(route, "a body that is not JSON");
32795
+ }
32796
+ const result = schema.safeParse(json2);
32797
+ if (!result.success) {
32798
+ throw new RemoteResponseInvalid(route, "a body this client cannot read");
32799
+ }
32800
+ return result.data;
32801
+ }
32802
+ function withoutTrailingSlashes(endpoint) {
32803
+ let end = endpoint.length;
32804
+ while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH) end -= 1;
32805
+ return endpoint.slice(0, end);
32806
+ }
32807
+ var SLASH = "/".charCodeAt(0);
32808
+ function createRemoteClient(options) {
32809
+ const base = withoutTrailingSlashes(options.endpoint);
32810
+ const url2 = (route) => `${base}${route}`;
32811
+ const common = { apiKey: options.apiKey, timeoutMs: options.timeoutMs };
32812
+ const sendOne = async (event) => {
32813
+ const validated = RecordAuditEventRequest.safeParse(event);
32814
+ if (!validated.success) throw new RemoteRequestInvalid(ROUTES.auditEvents, validated.error);
32815
+ const response = await send({
32816
+ ...common,
32817
+ method: "POST",
32818
+ url: url2(ROUTES.auditEvents),
32819
+ body: JSON.stringify(validated.data)
32820
+ });
32821
+ okBody(response);
32822
+ };
32823
+ return {
32824
+ async ingestEvents(batch) {
32825
+ const response = await send({
32826
+ ...common,
32827
+ method: "POST",
32828
+ url: url2(ROUTES.events),
32829
+ body: JSON.stringify(batch)
32830
+ });
32831
+ return parsed(IngestAck, okBody(response), ROUTES.events);
32832
+ },
32833
+ async ingestInventory(context) {
32834
+ const response = await send({
32835
+ ...common,
32836
+ method: "POST",
32837
+ url: url2(ROUTES.inventory),
32838
+ body: JSON.stringify(context)
32839
+ });
32840
+ return parsed(ResolvedInventory, okBody(response), ROUTES.inventory);
32841
+ },
32842
+ async recordAuditEvent(event) {
32843
+ await sendOne(event);
32844
+ },
32845
+ async recordAuditEvents(events, opts) {
32846
+ const validated = RecordAuditEventBatch.safeParse({ events });
32847
+ if (!validated.success) {
32848
+ throw new RemoteRequestInvalid(ROUTES.auditEventsBatch, validated.error);
32849
+ }
32850
+ const response = await send({
32851
+ ...common,
32852
+ method: "POST",
32853
+ url: url2(ROUTES.auditEventsBatch),
32854
+ body: JSON.stringify(validated.data)
32855
+ });
32856
+ if (response.status === 404) {
32857
+ if (opts?.fallbackToSingleEvents !== true) {
32858
+ throw new RemoteRouteAbsent(ROUTES.auditEventsBatch);
32859
+ }
32860
+ for (const event of validated.data.events) await sendOne(event);
32861
+ return { accepted: validated.data.events.length };
32862
+ }
32863
+ return parsed(AuditEventBatchAck, okBody(response), ROUTES.auditEventsBatch);
32864
+ },
32865
+ async reportStorePosture(snapshot) {
32866
+ const response = await send({
32867
+ ...common,
32868
+ method: "POST",
32869
+ url: url2(ROUTES.storePosture),
32870
+ body: JSON.stringify(snapshot)
32871
+ });
32872
+ okBody(response);
32873
+ },
32874
+ async getPolicyBundle(etag) {
32875
+ const response = await send({
32876
+ ...common,
32877
+ method: "GET",
32878
+ url: url2(ROUTES.policyBundle),
32879
+ ...etag === void 0 ? {} : { headers: { "if-none-match": etag } }
32880
+ });
32881
+ if (response.status === 304) {
32882
+ return { changed: false, etag: headerValue(response, "etag") ?? etag };
32883
+ }
32884
+ const bundle = parsed(PolicyBundle, okBody(response), ROUTES.policyBundle);
32885
+ return { changed: true, bundle, etag: headerValue(response, "etag") };
32886
+ },
32887
+ async whoami() {
32888
+ const response = await send({ ...common, method: "GET", url: url2(ROUTES.whoami) });
32889
+ return parsed(PluginWhoami, okBody(response), ROUTES.whoami);
32890
+ },
32891
+ async recordProjectEgress(request) {
32892
+ const validated = EgressIngestRequest.safeParse(request);
32893
+ if (!validated.success) throw new RemoteRequestInvalid(ROUTES.shares, validated.error);
32894
+ const response = await send({
32895
+ ...common,
32896
+ method: "POST",
32897
+ url: url2(ROUTES.shares),
32898
+ body: JSON.stringify(validated.data)
32899
+ });
32900
+ okBody(response);
32901
+ },
32902
+ async pollCommand() {
32903
+ const response = await send({ ...common, method: "GET", url: url2(ROUTES.commands) });
32904
+ if (response.status === 404) return null;
32905
+ return parsed(DeviceCommandPollResponse, okBody(response), ROUTES.commands).command;
32906
+ },
32907
+ async ackCommand(id, body) {
32908
+ const validated = DeviceCommandAckBody.safeParse(body);
32909
+ const route = ackRoute(id);
32910
+ if (!validated.success) throw new RemoteRequestInvalid(route, validated.error);
32911
+ const response = await send({
32912
+ ...common,
32913
+ method: "POST",
32914
+ url: url2(route),
32915
+ body: JSON.stringify(validated.data)
32916
+ });
32917
+ okBody(response);
32918
+ }
32919
+ };
32920
+ }
32921
+
32095
32922
  // ../../packages/plugin-runtime/src/attached/failure.ts
32096
32923
  function statusOf(err) {
32097
32924
  if (typeof err !== "object" || err === null || !("status" in err)) return null;
@@ -32110,12 +32937,27 @@ function classifyFailure(err) {
32110
32937
  }
32111
32938
  }
32112
32939
 
32940
+ // ../../packages/plugin-runtime/src/attached/with-timeout.ts
32941
+ var REQUEST_TIMEOUT_MS = 2e3;
32942
+ function withTimeout(promise2, ms) {
32943
+ let timer;
32944
+ const timeout = new Promise((_, reject) => {
32945
+ timer = setTimeout(() => {
32946
+ reject(new Error("attached gateway request timed out"));
32947
+ }, ms);
32948
+ });
32949
+ promise2.catch(() => void 0);
32950
+ return Promise.race([promise2, timeout]).finally(() => {
32951
+ clearTimeout(timer);
32952
+ });
32953
+ }
32954
+
32113
32955
  // ../../packages/plugin-runtime/src/attached/forward-drops.ts
32114
- import { readFileSync as readFileSync7 } from "fs";
32115
- import { join as join12 } from "path";
32956
+ import { readFileSync as readFileSync8 } from "fs";
32957
+ import { join as join13 } from "path";
32116
32958
  var FORWARD_DROPS_FILENAME = ATTACHED_FORWARD_DROPS_FILENAME;
32117
32959
  function forwardDropsPath(dataDir2) {
32118
- return join12(dataDir2, FORWARD_DROPS_FILENAME);
32960
+ return join13(dataDir2, FORWARD_DROPS_FILENAME);
32119
32961
  }
32120
32962
  function recordForwardDrops(dataDir2, count, nowMs) {
32121
32963
  if (count <= 0) return;
@@ -32133,7 +32975,7 @@ function recordForwardDrops(dataDir2, count, nowMs) {
32133
32975
  }
32134
32976
  function readForwardDrops(dataDir2) {
32135
32977
  try {
32136
- const parsed2 = JSON.parse(readFileSync7(forwardDropsPath(dataDir2), "utf8"));
32978
+ const parsed2 = JSON.parse(readFileSync8(forwardDropsPath(dataDir2), "utf8"));
32137
32979
  if (typeof parsed2 !== "object" || parsed2 === null) return null;
32138
32980
  const record2 = parsed2;
32139
32981
  if (typeof record2.droppedForwards !== "number" || !Number.isFinite(record2.droppedForwards)) {
@@ -32151,13 +32993,13 @@ function readForwardDrops(dataDir2) {
32151
32993
 
32152
32994
  // ../../packages/plugin-runtime/src/attached/forward-policy.ts
32153
32995
  import { randomUUID as randomUUID15 } from "crypto";
32154
- import { readFileSync as readFileSync13 } from "fs";
32996
+ import { readFileSync as readFileSync14 } from "fs";
32155
32997
  import { readFile, rename, writeFile } from "fs/promises";
32156
- import { join as join21 } from "path";
32998
+ import { join as join22 } from "path";
32157
32999
 
32158
33000
  // ../../packages/plugin-sdk/src/config.ts
32159
33001
  import { existsSync as existsSync7 } from "fs";
32160
- import { join as join13 } from "path";
33002
+ import { join as join14 } from "path";
32161
33003
 
32162
33004
  // ../../packages/plugin-sdk/src/provider-env.ts
32163
33005
  var DEFAULT_ANTHROPIC_HOST = "api.anthropic.com";
@@ -32211,7 +33053,7 @@ function resolveProvider() {
32211
33053
  function loadConfig(base = defaultDataDir(), resolveProviderFn = resolveProvider) {
32212
33054
  try {
32213
33055
  ensureLayoutDirSync(base);
32214
- const settingsFile = join13(settingsDir(base), "settings.json");
33056
+ const settingsFile = join14(settingsDir(base), "settings.json");
32215
33057
  if (existsSync7(settingsFile)) tightenFile(settingsFile);
32216
33058
  } catch {
32217
33059
  }
@@ -32235,9 +33077,9 @@ function resolveProviderSafe(resolveProviderFn) {
32235
33077
  }
32236
33078
 
32237
33079
  // ../../packages/plugin-sdk/src/config-inventory.ts
32238
- import { readdirSync as readdirSync2, readFileSync as readFileSync9, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
33080
+ import { readdirSync as readdirSync2, readFileSync as readFileSync10, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
32239
33081
  import { homedir as homedir2 } from "os";
32240
- import { basename as basename4, join as join15 } from "path";
33082
+ import { basename as basename4, join as join16 } from "path";
32241
33083
 
32242
33084
  // ../../packages/detections/src/egress/registry.ts
32243
33085
  var EXTRACTOR_VERSION = "1";
@@ -35366,8 +36208,8 @@ function maskText(text) {
35366
36208
  }
35367
36209
 
35368
36210
  // ../../packages/plugin-sdk/src/repo.ts
35369
- import { existsSync as existsSync8, readFileSync as readFileSync8, statSync as statSync6 } from "fs";
35370
- import { basename as basename3, dirname as dirname3, isAbsolute, join as join14, sep as sep2 } from "path";
36211
+ import { existsSync as existsSync8, readFileSync as readFileSync9, statSync as statSync6 } from "fs";
36212
+ import { basename as basename3, dirname as dirname4, isAbsolute, join as join15, sep as sep2 } from "path";
35371
36213
  function resolveRepoIdentity(cwd) {
35372
36214
  try {
35373
36215
  const root = findGitRoot(cwd);
@@ -35417,7 +36259,7 @@ function resolveGitBranch(cwd) {
35417
36259
  try {
35418
36260
  const root = findGitRoot(cwd);
35419
36261
  if (!root) return void 0;
35420
- const dotGit = join14(root, ".git");
36262
+ const dotGit = join15(root, ".git");
35421
36263
  let gitdir;
35422
36264
  try {
35423
36265
  gitdir = statSync6(dotGit).isDirectory() ? dotGit : resolveWorktreeGitdir(root, dotGit);
@@ -35425,7 +36267,7 @@ function resolveGitBranch(cwd) {
35425
36267
  return void 0;
35426
36268
  }
35427
36269
  if (gitdir === void 0) return void 0;
35428
- const head = safeRead(join14(gitdir, "HEAD"));
36270
+ const head = safeRead(join15(gitdir, "HEAD"));
35429
36271
  if (!head) return void 0;
35430
36272
  return /^ref:\s*refs\/heads\/(.+?)\s*$/m.exec(head)?.[1];
35431
36273
  } catch {
@@ -35435,41 +36277,41 @@ function resolveGitBranch(cwd) {
35435
36277
  function resolveWorktreeGitdir(root, dotGitFile) {
35436
36278
  const target = /^gitdir:\s*(.+?)\s*$/m.exec(safeRead(dotGitFile) ?? "")?.[1];
35437
36279
  if (!target) return void 0;
35438
- return isAbsolute(target) ? target : join14(root, target);
36280
+ return isAbsolute(target) ? target : join15(root, target);
35439
36281
  }
35440
36282
  function findGitRoot(start) {
35441
36283
  let dir = start;
35442
36284
  for (; ; ) {
35443
- if (existsSync8(join14(dir, ".git"))) return dir;
35444
- const parent = dirname3(dir);
36285
+ if (existsSync8(join15(dir, ".git"))) return dir;
36286
+ const parent = dirname4(dir);
35445
36287
  if (parent === dir) return void 0;
35446
36288
  dir = parent;
35447
36289
  }
35448
36290
  }
35449
36291
  function resolveGitContext(root) {
35450
- const dotGit = join14(root, ".git");
36292
+ const dotGit = join15(root, ".git");
35451
36293
  try {
35452
36294
  if (statSync6(dotGit).isDirectory()) {
35453
- return { configPath: join14(dotGit, "config"), headRoot: root };
36295
+ return { configPath: join15(dotGit, "config"), headRoot: root };
35454
36296
  }
35455
36297
  } catch {
35456
36298
  return void 0;
35457
36299
  }
35458
36300
  const target = /^gitdir:\s*(.+?)\s*$/m.exec(safeRead(dotGit) ?? "")?.[1];
35459
36301
  if (!target) return void 0;
35460
- const gitdir = isAbsolute(target) ? target : join14(root, target);
35461
- if (existsSync8(join14(gitdir, "config"))) {
35462
- return { configPath: join14(gitdir, "config"), headRoot: root };
36302
+ const gitdir = isAbsolute(target) ? target : join15(root, target);
36303
+ if (existsSync8(join15(gitdir, "config"))) {
36304
+ return { configPath: join15(gitdir, "config"), headRoot: root };
35463
36305
  }
35464
- const commonRaw = safeRead(join14(gitdir, "commondir"))?.trim();
36306
+ const commonRaw = safeRead(join15(gitdir, "commondir"))?.trim();
35465
36307
  if (!commonRaw) return void 0;
35466
- const commonGitDir = isAbsolute(commonRaw) ? commonRaw : join14(gitdir, commonRaw);
35467
- const headRoot = basename3(commonGitDir) === ".git" ? dirname3(commonGitDir) : root;
35468
- return { configPath: join14(commonGitDir, "config"), headRoot };
36308
+ const commonGitDir = isAbsolute(commonRaw) ? commonRaw : join15(gitdir, commonRaw);
36309
+ const headRoot = basename3(commonGitDir) === ".git" ? dirname4(commonGitDir) : root;
36310
+ return { configPath: join15(commonGitDir, "config"), headRoot };
35469
36311
  }
35470
36312
  function safeRead(path) {
35471
36313
  try {
35472
- return readFileSync8(path, "utf8");
36314
+ return readFileSync9(path, "utf8");
35473
36315
  } catch {
35474
36316
  return void 0;
35475
36317
  }
@@ -35531,31 +36373,31 @@ function resolveConfigInventory(input2) {
35531
36373
  };
35532
36374
  try {
35533
36375
  const home = input2.homeDir ?? homedir2();
35534
- const claudeDir = join15(home, ".claude");
36376
+ const claudeDir = join16(home, ".claude");
35535
36377
  const repo = resolveRepoIdentity(input2.cwd);
35536
36378
  const repoIdentity = repo?.url ?? input2.cwd;
35537
36379
  const projectSource = `project:${repoIdentity}`;
35538
- collectSettingsHooks(scan2, join15(claudeDir, "settings.json"), "user");
35539
- collectSettingsHooks(scan2, join15(input2.cwd, ".claude", "settings.json"), "project");
35540
- collectSettingsHooks(scan2, join15(input2.cwd, ".claude", "settings.local.json"), "local");
36380
+ collectSettingsHooks(scan2, join16(claudeDir, "settings.json"), "user");
36381
+ collectSettingsHooks(scan2, join16(input2.cwd, ".claude", "settings.json"), "project");
36382
+ collectSettingsHooks(scan2, join16(input2.cwd, ".claude", "settings.local.json"), "local");
35541
36383
  const projectOrigin = { scope: "project", project: repoIdentity };
35542
- collectMcpFile(scan2, join15(input2.cwd, ".mcp.json"), projectOrigin, { recordErrors: true });
35543
- collectUserClaudeJson(scan2, join15(home, ".claude.json"), input2.cwd, repoIdentity);
35544
- collectMcpFile(scan2, join15(claudeDir, "settings.json"), { scope: "user" });
35545
- collectMcpFile(scan2, join15(input2.cwd, ".claude", "settings.json"), projectOrigin);
35546
- collectMcpFile(scan2, join15(input2.cwd, ".claude", "settings.local.json"), {
36384
+ collectMcpFile(scan2, join16(input2.cwd, ".mcp.json"), projectOrigin, { recordErrors: true });
36385
+ collectUserClaudeJson(scan2, join16(home, ".claude.json"), input2.cwd, repoIdentity);
36386
+ collectMcpFile(scan2, join16(claudeDir, "settings.json"), { scope: "user" });
36387
+ collectMcpFile(scan2, join16(input2.cwd, ".claude", "settings.json"), projectOrigin);
36388
+ collectMcpFile(scan2, join16(input2.cwd, ".claude", "settings.local.json"), {
35547
36389
  scope: "local",
35548
36390
  project: repoIdentity
35549
36391
  });
35550
36392
  collectConfigFiles(scan2, claudeDir, input2.cwd);
35551
- collectSkillsDir(scan2, join15(claudeDir, "skills"), { source: "local", scope: "user" });
35552
- collectSkillsDir(scan2, join15(input2.cwd, ".claude", "skills"), {
36393
+ collectSkillsDir(scan2, join16(claudeDir, "skills"), { source: "local", scope: "user" });
36394
+ collectSkillsDir(scan2, join16(input2.cwd, ".claude", "skills"), {
35553
36395
  source: projectSource,
35554
36396
  scope: "project"
35555
36397
  });
35556
36398
  collectInstalledPlugins(scan2, claudeDir);
35557
36399
  collectMarketplaceSkills(scan2, claudeDir);
35558
- collectSkillsDir(scan2, join15(input2.cwd, "skills"), { source: projectSource, scope: "project" });
36400
+ collectSkillsDir(scan2, join16(input2.cwd, "skills"), { source: projectSource, scope: "project" });
35559
36401
  scan2.skills = dedupeSkills(scan2.skills);
35560
36402
  scan2.mcpServers = dedupeMcpServers(scan2.mcpServers);
35561
36403
  } catch (err) {
@@ -35684,7 +36526,7 @@ function projectEntryFor(projects, cwd) {
35684
36526
  return void 0;
35685
36527
  }
35686
36528
  function collectPluginManifestMcp(scan2, installPath, origin) {
35687
- const manifestPath = join15(installPath, ".claude-plugin", "plugin.json");
36529
+ const manifestPath = join16(installPath, ".claude-plugin", "plugin.json");
35688
36530
  const raw = readOptional(manifestPath);
35689
36531
  if (raw === void 0) return;
35690
36532
  try {
@@ -35692,7 +36534,7 @@ function collectPluginManifestMcp(scan2, installPath, origin) {
35692
36534
  if (typeof parsed2 !== "object" || parsed2 === null) return;
35693
36535
  const declared = parsed2.mcpServers;
35694
36536
  if (typeof declared === "string" && declared.length > 0) {
35695
- collectMcpFile(scan2, join15(installPath, declared), origin, { recordErrors: true });
36537
+ collectMcpFile(scan2, join16(installPath, declared), origin, { recordErrors: true });
35696
36538
  } else {
35697
36539
  collectMcpObject(scan2, declared, manifestPath, origin);
35698
36540
  }
@@ -35709,14 +36551,14 @@ var SETTINGS_KEY_LABELS = [
35709
36551
  ["statusLine", "status line"]
35710
36552
  ];
35711
36553
  function collectConfigFiles(scan2, claudeDir, cwd) {
35712
- settingsConfigFile(scan2, join15(claudeDir, "settings.json"), "user", "User settings");
35713
- settingsConfigFile(scan2, join15(cwd, ".claude", "settings.json"), "project", "Project settings");
35714
- settingsConfigFile(scan2, join15(cwd, ".claude", "settings.local.json"), "local", "Local overrides");
35715
- memoryConfigFile(scan2, join15(claudeDir, "CLAUDE.md"), "user", "User memory");
35716
- memoryConfigFile(scan2, join15(cwd, "CLAUDE.md"), "project", "Project memory");
35717
- mcpJsonConfigFile(scan2, join15(cwd, ".mcp.json"));
35718
- dirConfigFile(scan2, join15(cwd, ".claude", "commands"), "Slash commands", "command");
35719
- dirConfigFile(scan2, join15(cwd, ".claude", "agents"), "Subagents", "subagent");
36554
+ settingsConfigFile(scan2, join16(claudeDir, "settings.json"), "user", "User settings");
36555
+ settingsConfigFile(scan2, join16(cwd, ".claude", "settings.json"), "project", "Project settings");
36556
+ settingsConfigFile(scan2, join16(cwd, ".claude", "settings.local.json"), "local", "Local overrides");
36557
+ memoryConfigFile(scan2, join16(claudeDir, "CLAUDE.md"), "user", "User memory");
36558
+ memoryConfigFile(scan2, join16(cwd, "CLAUDE.md"), "project", "Project memory");
36559
+ mcpJsonConfigFile(scan2, join16(cwd, ".mcp.json"));
36560
+ dirConfigFile(scan2, join16(cwd, ".claude", "commands"), "Slash commands", "command");
36561
+ dirConfigFile(scan2, join16(cwd, ".claude", "agents"), "Subagents", "subagent");
35720
36562
  }
35721
36563
  function configFileEntry(path, scope, kind) {
35722
36564
  try {
@@ -35791,7 +36633,7 @@ function countMarkdownFiles(dir, depth) {
35791
36633
  let count = 0;
35792
36634
  for (const dirent of readdirSync2(dir, { withFileTypes: true })) {
35793
36635
  if (dirent.name.startsWith(".")) continue;
35794
- if (dirent.isDirectory()) count += countMarkdownFiles(join15(dir, dirent.name), depth + 1);
36636
+ if (dirent.isDirectory()) count += countMarkdownFiles(join16(dir, dirent.name), depth + 1);
35795
36637
  else if (dirent.name.endsWith(".md")) count += 1;
35796
36638
  }
35797
36639
  return count;
@@ -35804,7 +36646,7 @@ function collectSkillsDir(scan2, dir, origin) {
35804
36646
  return;
35805
36647
  }
35806
36648
  for (const name of names) {
35807
- const skillFile = join15(dir, name, "SKILL.md");
36649
+ const skillFile = join16(dir, name, "SKILL.md");
35808
36650
  try {
35809
36651
  const raw = readOptional(skillFile);
35810
36652
  if (raw === void 0) continue;
@@ -35813,7 +36655,7 @@ function collectSkillsDir(scan2, dir, origin) {
35813
36655
  name: front.name ?? name,
35814
36656
  source: origin.source,
35815
36657
  scope: origin.scope,
35816
- location: join15(dir, name),
36658
+ location: join16(dir, name),
35817
36659
  updatedAt: statSync7(skillFile).mtime.toISOString()
35818
36660
  };
35819
36661
  const version2 = front.version ?? origin.defaultVersion;
@@ -35844,7 +36686,7 @@ function parseFrontmatter(raw) {
35844
36686
  return out;
35845
36687
  }
35846
36688
  function collectInstalledPlugins(scan2, claudeDir) {
35847
- const manifestPath = join15(claudeDir, "plugins", "installed_plugins.json");
36689
+ const manifestPath = join16(claudeDir, "plugins", "installed_plugins.json");
35848
36690
  const raw = readOptional(manifestPath);
35849
36691
  if (raw === void 0) return;
35850
36692
  let plugins;
@@ -35869,7 +36711,7 @@ function collectInstalledPlugins(scan2, claudeDir) {
35869
36711
  if (typeof installPath !== "string" || seen.has(installPath)) continue;
35870
36712
  seen.add(installPath);
35871
36713
  const version2 = install.version;
35872
- const hooksPath = join15(installPath, "hooks", "hooks.json");
36714
+ const hooksPath = join16(installPath, "hooks", "hooks.json");
35873
36715
  const hooksRaw = readOptional(hooksPath);
35874
36716
  if (hooksRaw !== void 0) {
35875
36717
  try {
@@ -35889,22 +36731,22 @@ function collectInstalledPlugins(scan2, claudeDir) {
35889
36731
  }
35890
36732
  const origin = { source: marketplace, scope: "plugin", pluginName };
35891
36733
  if (typeof version2 === "string") origin.defaultVersion = version2;
35892
- collectSkillsDir(scan2, join15(installPath, "skills"), origin);
36734
+ collectSkillsDir(scan2, join16(installPath, "skills"), origin);
35893
36735
  const mcpOrigin = { scope: "plugin", pluginName, marketplace };
35894
- collectMcpFile(scan2, join15(installPath, ".mcp.json"), mcpOrigin, { recordErrors: true });
36736
+ collectMcpFile(scan2, join16(installPath, ".mcp.json"), mcpOrigin, { recordErrors: true });
35895
36737
  collectPluginManifestMcp(scan2, installPath, mcpOrigin);
35896
36738
  }
35897
36739
  }
35898
36740
  }
35899
36741
  function collectMarketplaceSkills(scan2, claudeDir) {
35900
- for (const mp of readMarketplaces(join15(claudeDir, "plugins", "known_marketplaces.json"))) {
36742
+ for (const mp of readMarketplaces(join16(claudeDir, "plugins", "known_marketplaces.json"))) {
35901
36743
  if (isClaudeOfficialMarketplace(mp.name, mp.repo)) continue;
35902
- collectSkillsDir(scan2, join15(mp.installLocation, "skills"), {
36744
+ collectSkillsDir(scan2, join16(mp.installLocation, "skills"), {
35903
36745
  source: mp.name,
35904
36746
  scope: "plugin"
35905
36747
  });
35906
- collectPluginSkillDirs(scan2, join15(mp.installLocation, "plugins"), mp.name);
35907
- collectPluginSkillDirs(scan2, join15(mp.installLocation, "external_plugins"), mp.name);
36748
+ collectPluginSkillDirs(scan2, join16(mp.installLocation, "plugins"), mp.name);
36749
+ collectPluginSkillDirs(scan2, join16(mp.installLocation, "external_plugins"), mp.name);
35908
36750
  }
35909
36751
  }
35910
36752
  function collectPluginSkillDirs(scan2, pluginsDir, marketplace) {
@@ -35915,7 +36757,7 @@ function collectPluginSkillDirs(scan2, pluginsDir, marketplace) {
35915
36757
  return;
35916
36758
  }
35917
36759
  for (const plugin of plugins) {
35918
- collectSkillsDir(scan2, join15(pluginsDir, plugin, "skills"), {
36760
+ collectSkillsDir(scan2, join16(pluginsDir, plugin, "skills"), {
35919
36761
  source: marketplace,
35920
36762
  scope: "plugin",
35921
36763
  pluginName: plugin
@@ -35969,7 +36811,7 @@ function dedupeMcpServers(servers) {
35969
36811
  }
35970
36812
  function readOptional(path) {
35971
36813
  try {
35972
- return readFileSync9(path, "utf8");
36814
+ return readFileSync10(path, "utf8");
35973
36815
  } catch {
35974
36816
  return void 0;
35975
36817
  }
@@ -36003,11 +36845,11 @@ import { Worker } from "worker_threads";
36003
36845
 
36004
36846
  // ../../packages/plugin-sdk/src/ignore-layers.ts
36005
36847
  var import_ignore = __toESM(require_ignore(), 1);
36006
- import { readFileSync as readFileSync10 } from "fs";
36007
- import { join as join16 } from "path";
36848
+ import { readFileSync as readFileSync11 } from "fs";
36849
+ import { join as join17 } from "path";
36008
36850
  function readIgnoreLayer(dir, filename, anchorLen) {
36009
36851
  try {
36010
- return { matcher: (0, import_ignore.default)().add(readFileSync10(join16(dir, filename), "utf8")), anchorLen };
36852
+ return { matcher: (0, import_ignore.default)().add(readFileSync11(join17(dir, filename), "utf8")), anchorLen };
36011
36853
  } catch {
36012
36854
  return void 0;
36013
36855
  }
@@ -36069,25 +36911,25 @@ import {
36069
36911
  fstatSync,
36070
36912
  mkdirSync as mkdirSync2,
36071
36913
  openSync as openSync2,
36072
- readFileSync as readFileSync11,
36914
+ readFileSync as readFileSync12,
36073
36915
  readSync,
36074
36916
  writeFileSync as writeFileSync5
36075
36917
  } from "fs";
36076
- import { join as join17 } from "path";
36918
+ import { join as join18 } from "path";
36077
36919
  var TAIL_BYTES = 256 * 1024;
36078
36920
 
36079
36921
  // ../../packages/plugin-sdk/src/nudge.ts
36080
- import { mkdirSync as mkdirSync3, readFileSync as readFileSync12, writeFileSync as writeFileSync6 } from "fs";
36081
- import { join as join18 } from "path";
36922
+ import { mkdirSync as mkdirSync3, readFileSync as readFileSync13, writeFileSync as writeFileSync6 } from "fs";
36923
+ import { join as join19 } from "path";
36082
36924
  var SESSION_START_MARKER = "session-start-last";
36083
36925
  function claimSessionStart(dataDir2, sessionId) {
36084
36926
  return claimOncePerSession(dataDir2, SESSION_START_MARKER, sessionId);
36085
36927
  }
36086
36928
  function claimOncePerSession(dataDir2, marker, sessionId) {
36087
36929
  if (!sessionId) return true;
36088
- const path = join18(dataDir2, marker);
36930
+ const path = join19(dataDir2, marker);
36089
36931
  try {
36090
- if (readFileSync12(path, "utf8") === sessionId) return false;
36932
+ if (readFileSync13(path, "utf8") === sessionId) return false;
36091
36933
  } catch {
36092
36934
  }
36093
36935
  try {
@@ -36100,11 +36942,11 @@ function claimOncePerSession(dataDir2, marker, sessionId) {
36100
36942
 
36101
36943
  // ../../packages/plugin-sdk/src/paths.ts
36102
36944
  import { readdirSync as readdirSync3, realpathSync as realpathSync3 } from "fs";
36103
- import { basename as basename5, dirname as dirname4, sep as sep3 } from "path";
36945
+ import { basename as basename5, dirname as dirname5, sep as sep3 } from "path";
36104
36946
 
36105
36947
  // ../../packages/plugin-sdk/src/project-files.ts
36106
36948
  import { existsSync as existsSync10, readdirSync as readdirSync4 } from "fs";
36107
- import { basename as basename6, join as join19 } from "path";
36949
+ import { basename as basename6, join as join20 } from "path";
36108
36950
  var SKIP_DIRS = /* @__PURE__ */ new Set([
36109
36951
  ".git",
36110
36952
  "node_modules",
@@ -36201,8 +37043,8 @@ function resolveProjectFiles(cwd, opts = {}) {
36201
37043
  }
36202
37044
  if (entry.isDirectory()) {
36203
37045
  if (SKIP_DIRS.has(entry.name) || isIgnored(dirLayers, dirRel, entry.name, true)) continue;
36204
- const fullPath = join19(dir, entry.name);
36205
- if (existsSync10(join19(fullPath, ".git"))) continue;
37046
+ const fullPath = join20(dir, entry.name);
37047
+ if (existsSync10(join20(fullPath, ".git"))) continue;
36206
37048
  if (depth >= bounds.maxDepth) {
36207
37049
  walk.omitted = true;
36208
37050
  continue;
@@ -36303,9 +37145,9 @@ var THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1e3;
36303
37145
 
36304
37146
  // ../../packages/plugin-sdk/src/throttle.ts
36305
37147
  import { mkdirSync as mkdirSync4, statSync as statSync8, writeFileSync as writeFileSync7 } from "fs";
36306
- import { join as join20 } from "path";
37148
+ import { join as join21 } from "path";
36307
37149
  function throttled(dataDir2, markerName, windowMs) {
36308
- const marker = join20(dataDir2, markerName);
37150
+ const marker = join21(dataDir2, markerName);
36309
37151
  try {
36310
37152
  if (Date.now() - statSync8(marker).mtimeMs < windowMs) return true;
36311
37153
  } catch {
@@ -36318,25 +37160,17 @@ function throttled(dataDir2, markerName, windowMs) {
36318
37160
  return false;
36319
37161
  }
36320
37162
 
36321
- // ../../packages/plugin-runtime/src/attached/with-timeout.ts
36322
- var REQUEST_TIMEOUT_MS = 2e3;
36323
- function withTimeout(promise2, ms) {
36324
- let timer;
36325
- const timeout = new Promise((_, reject) => {
36326
- timer = setTimeout(() => {
36327
- reject(new Error("attached gateway request timed out"));
36328
- }, ms);
36329
- });
36330
- promise2.catch(() => void 0);
36331
- return Promise.race([promise2, timeout]).finally(() => {
36332
- clearTimeout(timer);
36333
- });
36334
- }
36335
-
36336
37163
  // ../../packages/plugin-runtime/src/attached/forward-policy.ts
36337
37164
  function isInvalidRequest(err) {
36338
37165
  return typeof err === "object" && err !== null && err.name === "RemoteRequestInvalid";
36339
37166
  }
37167
+ function isRouteAbsent(err) {
37168
+ return typeof err === "object" && err !== null && err.name === "RemoteRouteAbsent";
37169
+ }
37170
+ function isServerRejection(err) {
37171
+ const status = statusOf(err);
37172
+ return status !== null && status >= 400 && status <= 499 && status !== 401 && status !== 403 && status !== 404 && status !== 429;
37173
+ }
36340
37174
  var FORWARD_BUDGET_MS = 1500;
36341
37175
  var DECISION_PATH_BUDGET_MS = 800;
36342
37176
  var BREAKER_FAILURE_THRESHOLD = 3;
@@ -36364,7 +37198,7 @@ function parseBreakerState(raw, nowMs) {
36364
37198
  }
36365
37199
  function createForwardPolicy(deps) {
36366
37200
  const now = deps.now ?? (() => Date.now());
36367
- const file2 = join21(deps.dir, STATE_FILENAME);
37201
+ const file2 = join22(deps.dir, STATE_FILENAME);
36368
37202
  let state = null;
36369
37203
  let loading = null;
36370
37204
  async function readState() {
@@ -36404,6 +37238,20 @@ function createForwardPolicy(deps) {
36404
37238
  } catch {
36405
37239
  current = { ...CLOSED };
36406
37240
  }
37241
+ const restoreOpenedAtMs = (openedAtMs) => persist({
37242
+ consecutiveFailures: current.consecutiveFailures,
37243
+ openedAtMs,
37244
+ lastFailure: current.lastFailure
37245
+ });
37246
+ const recordFailure = (cause) => {
37247
+ const failures = current.consecutiveFailures + 1;
37248
+ const shouldOpen = current.openedAtMs !== null || failures >= BREAKER_FAILURE_THRESHOLD;
37249
+ return persist({
37250
+ consecutiveFailures: failures,
37251
+ openedAtMs: shouldOpen ? now() : null,
37252
+ lastFailure: cause
37253
+ });
37254
+ };
36407
37255
  const at = now();
36408
37256
  if (current.openedAtMs !== null) {
36409
37257
  if (at - current.openedAtMs < BREAKER_COOLDOWN_MS) {
@@ -36422,15 +37270,20 @@ function createForwardPolicy(deps) {
36422
37270
  }
36423
37271
  return { ok: true, value };
36424
37272
  } catch (err) {
36425
- if (isInvalidRequest(err)) return { ok: false, reason: "invalid-request" };
37273
+ if (isInvalidRequest(err)) {
37274
+ if (current.openedAtMs !== null) await restoreOpenedAtMs(current.openedAtMs);
37275
+ return { ok: false, reason: "invalid-request" };
37276
+ }
37277
+ if (isRouteAbsent(err)) {
37278
+ if (current.openedAtMs !== null) await restoreOpenedAtMs(null);
37279
+ return { ok: false, reason: "route-absent" };
37280
+ }
37281
+ if (isServerRejection(err)) {
37282
+ await recordFailure("unreachable");
37283
+ return { ok: false, reason: "rejected" };
37284
+ }
36426
37285
  const reason = classifyFailure(err);
36427
- const failures = current.consecutiveFailures + 1;
36428
- const shouldOpen = current.openedAtMs !== null || failures >= BREAKER_FAILURE_THRESHOLD;
36429
- await persist({
36430
- consecutiveFailures: failures,
36431
- openedAtMs: shouldOpen ? now() : null,
36432
- lastFailure: reason
36433
- });
37286
+ await recordFailure(reason);
36434
37287
  return { ok: false, reason };
36435
37288
  }
36436
37289
  }
@@ -36438,13 +37291,11 @@ function createForwardPolicy(deps) {
36438
37291
  }
36439
37292
 
36440
37293
  // ../../packages/plugin-runtime/src/attached/gateway.ts
36441
- var ACTION_STRENGTH = {
36442
- allow: 0,
36443
- log: 1,
36444
- warn: 2,
36445
- redact: 3,
36446
- block: 4
36447
- };
37294
+ function strongerOf(a, b) {
37295
+ if (a === null) return b;
37296
+ if (b === null) return a;
37297
+ return strongerAction(a, b);
37298
+ }
36448
37299
  function ruleCategoryMap(wireRules, localRules) {
36449
37300
  const map2 = /* @__PURE__ */ new Map();
36450
37301
  for (const rule of wireRules ?? []) map2.set(rule.id, rule.category);
@@ -36454,11 +37305,6 @@ function ruleCategoryMap(wireRules, localRules) {
36454
37305
  }
36455
37306
  return map2;
36456
37307
  }
36457
- function strongerOf(a, b) {
36458
- if (a === null) return b;
36459
- if (b === null) return a;
36460
- return ACTION_STRENGTH[a] >= ACTION_STRENGTH[b] ? a : b;
36461
- }
36462
37308
  function policyKey(policy) {
36463
37309
  return "ruleId" in policy.target ? `rule:${policy.target.ruleId}` : `category:${policy.target.category}`;
36464
37310
  }
@@ -36477,7 +37323,7 @@ function mergeRaiseOnly(localPolicies, remotePolicies, categoryByRuleId) {
36477
37323
  const floor = floorFor(policy, categoryByRuleId);
36478
37324
  remoteCategoryAction.set(
36479
37325
  policy.target.category,
36480
- floor !== null && ACTION_STRENGTH[policy.action] < ACTION_STRENGTH[floor] ? floor : policy.action
37326
+ floor !== null && !isActionAtLeast(policy.action, floor) ? floor : policy.action
36481
37327
  );
36482
37328
  }
36483
37329
  for (const policy of localPolicies) {
@@ -36494,7 +37340,7 @@ function mergeRaiseOnly(localPolicies, remotePolicies, categoryByRuleId) {
36494
37340
  }
36495
37341
  merged.set(
36496
37342
  key,
36497
- remoteFloor !== null && ACTION_STRENGTH[policy.action] < ACTION_STRENGTH[remoteFloor] ? { ...policy, action: remoteFloor } : policy
37343
+ remoteFloor !== null && !isActionAtLeast(policy.action, remoteFloor) ? { ...policy, action: remoteFloor } : policy
36498
37344
  );
36499
37345
  }
36500
37346
  const localCategoryAction = /* @__PURE__ */ new Map();
@@ -36514,13 +37360,13 @@ function mergeRaiseOnly(localPolicies, remotePolicies, categoryByRuleId) {
36514
37360
  if (category !== void 0) localFloor = localCategoryAction.get(category) ?? null;
36515
37361
  }
36516
37362
  const effectiveFloor = strongerOf(floor, localFloor);
36517
- const clamped = effectiveFloor !== null && ACTION_STRENGTH[policy.action] < ACTION_STRENGTH[effectiveFloor] ? { ...policy, action: effectiveFloor } : policy;
37363
+ const clamped = effectiveFloor !== null && !isActionAtLeast(policy.action, effectiveFloor) ? { ...policy, action: effectiveFloor } : policy;
36518
37364
  const existing = merged.get(key);
36519
37365
  if (existing === void 0) {
36520
37366
  merged.set(key, clamped);
36521
37367
  continue;
36522
37368
  }
36523
- if (ACTION_STRENGTH[clamped.action] > ACTION_STRENGTH[existing.action]) {
37369
+ if (actionRank(clamped.action) > actionRank(existing.action)) {
36524
37370
  merged.set(key, clamped);
36525
37371
  }
36526
37372
  }
@@ -36553,6 +37399,8 @@ var AttachedDataGateway = class {
36553
37399
  );
36554
37400
  if (forwarded.ok && forwarded.value.accepted + forwarded.value.duplicates > 0) {
36555
37401
  this.deps.local.markCaptureDelivered(record2.event, Date.now());
37402
+ } else {
37403
+ this.deps.local.markCaptureOwed(record2.event);
36556
37404
  }
36557
37405
  }
36558
37406
  async ensureInventory(ctx) {
@@ -36589,9 +37437,10 @@ var AttachedDataGateway = class {
36589
37437
  // a retried tool_call, exactly this path — can never stomp a populated row.
36590
37438
  async recordAuditEvent(event) {
36591
37439
  await this.deps.local.recordAuditEvent(event);
36592
- await this.deps.forward.run(
37440
+ const forwarded = await this.deps.forward.run(
36593
37441
  () => this.deps.client.recordAuditEvent(reKeyForForward(event, this.remoteInventory))
36594
37442
  );
37443
+ if (forwarded.ok) this.deps.local.markAuditEventsDelivered([event], Date.now());
36595
37444
  }
36596
37445
  // Attached `llm_call` is written locally by the inner gateway, then routed to
36597
37446
  // the control plane through the existing `recordAuditEvent` ingest (no dedicated
@@ -36600,44 +37449,170 @@ var AttachedDataGateway = class {
36600
37449
  // which would write the event to the local store a second time.
36601
37450
  async recordLlmCall(input2) {
36602
37451
  await this.deps.local.recordLlmCall(input2);
36603
- await this.deps.forward.run(
36604
- () => this.deps.client.recordAuditEvent(
36605
- reKeyForForward(llmAuditEvent(input2), this.remoteInventory)
36606
- )
37452
+ const event = llmAuditEvent(input2);
37453
+ const forwarded = await this.deps.forward.run(
37454
+ () => this.deps.client.recordAuditEvent(reKeyForForward(event, this.remoteInventory))
36607
37455
  );
37456
+ if (forwarded.ok) this.deps.local.markAuditEventsDelivered([event], Date.now());
36608
37457
  }
36609
37458
  /**
36610
- * Forward one batch, item by item, under ONE aggregate deadline.
37459
+ * Forward one batch in CHUNKS of AUDIT_EVENT_BATCH_MAX, under ONE aggregate deadline.
37460
+ *
37461
+ * This used to send one HTTP request per event, which is what made the batch
37462
+ * budget bite: at 200ms round-trip a 3s budget admitted ~15 events and threw
37463
+ * away everything after them. The same rows now cross 50 at a time over
37464
+ * `POST /v1/audit-events/batch` — the route the attach-time drain has always
37465
+ * used — so the same budget admits ~750. The wire cap is the server's own
37466
+ * constant, sized against server cost, and the client REFUSES a longer array
37467
+ * client-side, so the chunking here is not a convention.
36611
37468
  *
36612
- * Per-item budgets bound each request and nothing bounded their sum — see
36613
- * BATCH_FORWARD_BUDGET_MS. When the deadline passes the remainder is dropped
36614
- * rather than sent: the local write has already succeeded, so every caller
36615
- * has a correct result to return, and a drop is the outcome this path is
36616
- * built to accept (G8) where a blown hook timeout is not.
37469
+ * Still serial, and still for the original reason: firing N requests at once
37470
+ * would trade a latency problem for a burst the plane's per-key rate limiting
37471
+ * answers with the refusals the breaker then counts. Fewer, fuller requests is
37472
+ * the fix; more concurrent ones is not.
36617
37473
  *
36618
- * Serial rather than concurrent on purpose. Firing N requests at once would
36619
- * trade a latency problem for a burst the plane's own per-key rate limiting
36620
- * would answer with the refusals the breaker then counts.
37474
+ * When the deadline passes the remainder is dropped rather than sent: the
37475
+ * local write has already succeeded, so every caller has a correct result to
37476
+ * return. What is dropped is COUNTED, everywhere it can happen — this path
37477
+ * returns BEFORE `ForwardPolicy.run` is reached, so without the tally in
37478
+ * `forward-drops.ts` a slow-but-answering plane produces no failures, keeps
37479
+ * the breaker closed, renders a healthy block, and discards the tail of every
37480
+ * batch indefinitely. The SAME tally also covers a single that fails inside
37481
+ * the per-item retry below — the breaker opening mid-retry is a failure the
37482
+ * breaker's own state DOES capture, but the events still in this chunk once
37483
+ * that happens are neither delivered nor otherwise counted anywhere, which is
37484
+ * the same invisibility with a different cause.
36621
37485
  *
36622
- * WHAT IS DROPPED IS COUNTED. Every other forward failure ends in
36623
- * `ForwardPolicy.run`'s catch and moves the breaker's file, which is what
36624
- * lets status call the forward unhealthy; this path returns BEFORE `run` is
36625
- * reached, so without the tally in `forward-drops.ts` a slow-but-answering
36626
- * plane produces no failures, keeps the breaker closed, renders a healthy
36627
- * block, and discards the tail of every batch indefinitely.
37486
+ * `ok` ALONE IS NOT DELIVERY, the same rule `recordCapture` states for the
37487
+ * single-event ack and at fifty times the blast radius here:
37488
+ * `AuditEventBatchAck.accepted` is an aggregate count the wire contract does
37489
+ * not tie to the chunk's own length, so a 2xx answering `{accepted: 30}` for
37490
+ * fifty events is well-formed. Trusting `ok` alone would stamp all fifty as
37491
+ * delivered and never re-offer the twenty the plane did not take. So success
37492
+ * is checked against `chunk.length`; anything short of it falls into the same
37493
+ * per-item pass as a refused chunk, which is the only way to recover the
37494
+ * rows that did not land, since the ack carries no per-row verdict to
37495
+ * resend by.
37496
+ *
37497
+ * That fallback ASSUMES a re-send of an already-landed row is a harmless
37498
+ * no-op rather than a second cost — an assumption this file cannot verify.
37499
+ * `AuditEventBatchAck` carries only `accepted`, unlike its sibling
37500
+ * `IngestAck` (`accepted` + `duplicates`, with `accepted + duplicates ==`
37501
+ * the batch size as the invariant `recordCapture` reads), so whether a
37502
+ * duplicate counts toward THIS route's `accepted` is not expressed
37503
+ * anywhere in this repo. If it follows its sibling's convention and does
37504
+ * NOT, a chunk containing even one already-delivered row — the ordinary
37505
+ * consequence of a lost stamp, which this file already treats as cheap —
37506
+ * answers short forever and enters the per-item pass on every pass it is
37507
+ * offered again. The cost of that is bounded rather than silent: the
37508
+ * pass converges (every row lands and stamps), so it is one wasted round
37509
+ * of singles rather than a stall, and it errs toward an extra resend
37510
+ * rather than toward the lost row the alternative risks.
37511
+ *
37512
+ * BATCH-ATOMIC SETTLEMENT is otherwise the rule: the receiver wraps a chunk in
37513
+ * one transaction, so a full 2xx settles every event in it and a non-2xx
37514
+ * settles none — which is why the whole chunk is stamped together on a FULL
37515
+ * accept and none of it otherwise. THREE reasons do not deserve whole-chunk
37516
+ * treatment, alongside a short accept, and all are re-sent one event at a
37517
+ * time:
37518
+ *
37519
+ * `invalid-request` a chunk the client refused to send at all. One malformed
37520
+ * event would otherwise cost the 49 good ones beside it —
37521
+ * a new way to lose data introduced by the very change
37522
+ * meant to stop losing it.
37523
+ * `route-absent` a deployment that predates the batch route. The
37524
+ * single-event route is the one it serves, and re-sending
37525
+ * here rather than inside the client is what gives each
37526
+ * request its own budget instead of 50 inside one.
37527
+ * `rejected` the deployment's SERVER-side twin of `invalid-request` —
37528
+ * a 4xx body refusal from schema drift on the other side
37529
+ * of the wire. Settlement is batch-atomic on this reason
37530
+ * exactly as on the others, so leaving it out would cost
37531
+ * the whole chunk for one event the DEPLOYMENT considers
37532
+ * malformed, where the per-item form cost only that one.
37533
+ *
37534
+ * Every other reason (breaker-open, a refusal, a timeout) applies to the whole
37535
+ * chunk, and re-sending it item by item would just spend the budget failing 50
37536
+ * more times — for those, the blast radius stays exactly what it was before
37537
+ * batching.
36628
37538
  */
36629
37539
  async forwardBatch(inputs, toEvent) {
36630
37540
  const deadline = Date.now() + BATCH_FORWARD_BUDGET_MS;
36631
- for (let i = 0; i < inputs.length; i += 1) {
36632
- const now = Date.now();
36633
- if (now >= deadline) {
36634
- recordForwardDrops(this.deps.dataDir, inputs.length - i, now);
36635
- return;
37541
+ const delivered = [];
37542
+ try {
37543
+ for (let i = 0; i < inputs.length; i += AUDIT_EVENT_BATCH_MAX) {
37544
+ const now = Date.now();
37545
+ if (now >= deadline) {
37546
+ recordForwardDrops(this.deps.dataDir, inputs.length - i, now);
37547
+ return;
37548
+ }
37549
+ const chunk = inputs.slice(i, i + AUDIT_EVENT_BATCH_MAX).map((input2) => toEvent(input2));
37550
+ const forwarded = await this.deps.forward.run(
37551
+ () => this.deps.client.recordAuditEvents(
37552
+ chunk.map((event) => reKeyForForward(event, this.remoteInventory))
37553
+ )
37554
+ );
37555
+ if (forwarded.ok) {
37556
+ if (forwarded.value.accepted === chunk.length) {
37557
+ delivered.push(...chunk);
37558
+ continue;
37559
+ }
37560
+ } else if (
37561
+ // THREE reasons are worth a second pass, one at a time, and they are
37562
+ // the three settled BEFORE the control plane refused anything, or
37563
+ // (for `rejected`) refused the BODY rather than the connection.
37564
+ //
37565
+ // `invalid-request` — the CLIENT refused the body before any request
37566
+ // went out: a defect in one event, not an outage. Re-sending singly
37567
+ // isolates the bad one instead of charging its 49 neighbours for it.
37568
+ //
37569
+ // `route-absent` — the deployment predates the batch route and serves
37570
+ // only the single-event one. The retry IS the compatibility path, and
37571
+ // it has to live HERE rather than inside the client: each single gets
37572
+ // its own FORWARD_BUDGET_MS through `run`, whereas the client's own
37573
+ // fallback would spend 50 sequential round trips inside the ONE
37574
+ // budget wrapping this call — turning a working older deployment into
37575
+ // a timeout, three of those into an open breaker, and every row into
37576
+ // a silent drop while the status surface called an answering
37577
+ // deployment down.
37578
+ //
37579
+ // `rejected` — the deployment's own 4xx refusal of the body, the
37580
+ // server-side twin of `invalid-request`: isolating it the same way
37581
+ // costs one event instead of the whole chunk for a defect the
37582
+ // deployment considers local to one row.
37583
+ //
37584
+ // Every other reason (breaker-open, a refusal, a timeout) applies to
37585
+ // the whole chunk; re-sending it item by item would just spend the
37586
+ // budget failing 50 more times.
37587
+ forwarded.reason !== "invalid-request" && forwarded.reason !== "route-absent" && forwarded.reason !== "rejected"
37588
+ ) {
37589
+ continue;
37590
+ }
37591
+ for (const [j, event] of chunk.entries()) {
37592
+ const at = Date.now();
37593
+ if (at >= deadline) {
37594
+ recordForwardDrops(this.deps.dataDir, inputs.length - i - j, at);
37595
+ return;
37596
+ }
37597
+ const single = await this.deps.forward.run(
37598
+ () => this.deps.client.recordAuditEvent(reKeyForForward(event, this.remoteInventory))
37599
+ );
37600
+ if (single.ok) {
37601
+ delivered.push(event);
37602
+ continue;
37603
+ }
37604
+ if (single.reason === "breaker-open") {
37605
+ recordForwardDrops(this.deps.dataDir, inputs.length - i - j, at);
37606
+ return;
37607
+ }
37608
+ recordForwardDrops(this.deps.dataDir, 1, at);
37609
+ }
37610
+ }
37611
+ } finally {
37612
+ try {
37613
+ this.deps.local.markAuditEventsDelivered(delivered, Date.now());
37614
+ } catch {
36636
37615
  }
36637
- const input2 = inputs[i];
36638
- await this.deps.forward.run(
36639
- () => this.deps.client.recordAuditEvent(reKeyForForward(toEvent(input2), this.remoteInventory))
36640
- );
36641
37616
  }
36642
37617
  }
36643
37618
  // Delegated as a BATCH rather than looped over recordLlmCall: the inner
@@ -36680,9 +37655,10 @@ var AttachedDataGateway = class {
36680
37655
  // local store.
36681
37656
  async recordConfigScan(record2) {
36682
37657
  await this.deps.local.recordConfigScan(record2);
36683
- await this.deps.forward.run(
37658
+ const forwarded = await this.deps.forward.run(
36684
37659
  () => this.deps.client.recordAuditEvent(reKeyForForward(record2.scanEvent, this.remoteInventory))
36685
37660
  );
37661
+ if (forwarded.ok) this.deps.local.markAuditEventsDelivered([record2.scanEvent], Date.now());
36686
37662
  }
36687
37663
  async recordBlockedDetection(entry) {
36688
37664
  return this.deps.local.recordBlockedDetection(entry);
@@ -36816,6 +37792,18 @@ var AttachedDataGateway = class {
36816
37792
  // exactly what it did, leaving the whole control inert on every device
36817
37793
  // while every test around it stayed green.
36818
37794
  prohibitedModels: cached2.prohibitedModels
37795
+ // ALSO HONOURED FROM THE CACHE, and not a bundle field at all: each
37796
+ // merged policy's own `provenance`. `mergeRaiseOnly` spreads the policies
37797
+ // it emits, so an 'authored' policy arriving from the control plane
37798
+ // keeps that marker even where the clamp rebuilds it with a stronger
37799
+ // action. The device reads it in exactly one direction — the rules such a
37800
+ // policy targets are not locally re-assignable — so it sits on the
37801
+ // `prohibitedModels` side of the line for the same reason that field
37802
+ // does: it can only ever ADD a refusal, never relax one, and an unsigned
37803
+ // cache therefore has no relaxation to grant by carrying it. Dropping it
37804
+ // would be the silent failure rather than the safe one — the action would
37805
+ // still be enforced while the local override the organization authored
37806
+ // away quietly came back.
36819
37807
  // `rulesComplete` is a STANDALONE-ONLY signal (the user's local installed
36820
37808
  // snapshot) and is taken from the LOCAL bundle only — never from the wire
36821
37809
  // or the on-disk cache. Honoring a cached one would hand the control plane, or
@@ -36855,10 +37843,10 @@ var AttachedDataGateway = class {
36855
37843
  //
36856
37844
  // Implementing these is what actually closes the skipped-local-maintenance
36857
37845
  // gap: the OSS structural guard `hasLocalStoreMaintenance()` is satisfied by
36858
- // any object carrying all five, so the composite qualifies and SessionStart
37846
+ // any object carrying them all, so the composite qualifies and SessionStart
36859
37847
  // runs maintenance on the device's real store.
36860
37848
  //
36861
- // ⚠ Three of the six are SYNCHRONOUS and must stay that way. `handle-session-start`
37849
+ // ⚠ Several of them are SYNCHRONOUS and must stay that way. `handle-session-start`
36862
37850
  // calls `capWarnEraEnforcement` without `await` and uses `staleBinaryNotice`'s
36863
37851
  // return value directly; declaring them `async` here would hand those call
36864
37852
  // sites a Promise and silently break both.
@@ -36881,9 +37869,15 @@ var AttachedDataGateway = class {
36881
37869
  // Delegated like the rest, and SYNCHRONOUS for the reason the note above
36882
37870
  // gives: `recordCapture` calls it after the forward has already settled, on a
36883
37871
  // path that has nothing left to await.
37872
+ markCaptureOwed(event) {
37873
+ this.deps.local.markCaptureOwed(event);
37874
+ }
36884
37875
  markCaptureDelivered(event, atMs) {
36885
37876
  this.deps.local.markCaptureDelivered(event, atMs);
36886
37877
  }
37878
+ markAuditEventsDelivered(events, atMs) {
37879
+ this.deps.local.markAuditEventsDelivered(events, atMs);
37880
+ }
36887
37881
  };
36888
37882
  function reKeyForForward(event, remote) {
36889
37883
  if (remote === null) {
@@ -36926,281 +37920,17 @@ function toolAuditEvent(input2) {
36926
37920
  }
36927
37921
 
36928
37922
  // ../../packages/plugin-runtime/src/attached/history-state.ts
36929
- import { readFileSync as readFileSync14 } from "fs";
36930
- import { join as join22 } from "path";
37923
+ import { readFileSync as readFileSync15 } from "fs";
37924
+ import { join as join23 } from "path";
36931
37925
 
36932
37926
  // ../../packages/plugin-runtime/src/attached/history-sync.ts
36933
37927
  import { createHash as createHash6 } from "crypto";
36934
37928
  import { hostname as hostname5 } from "os";
36935
37929
 
36936
- // ../../packages/remote/src/http.ts
36937
- import { request as httpRequest } from "http";
36938
- import { request as httpsRequest } from "https";
36939
- var DEFAULT_TIMEOUT_MS = 1e4;
36940
- var MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
36941
- var RemoteRequestError = class extends Error {
36942
- constructor(status) {
36943
- super(`control-plane request failed with status ${String(status)}`);
36944
- this.status = status;
36945
- this.name = "RemoteRequestError";
36946
- }
36947
- status;
36948
- };
36949
- var RemoteRequestInvalid = class extends Error {
36950
- constructor(route, cause) {
36951
- super(`refusing to send a malformed body to ${route}`);
36952
- this.cause = cause;
36953
- this.name = "RemoteRequestInvalid";
36954
- }
36955
- cause;
36956
- };
36957
- var RemoteResponseInvalid = class extends Error {
36958
- constructor(route, detail) {
36959
- super(`control plane answered ${route} with ${detail}`);
36960
- this.name = "RemoteResponseInvalid";
36961
- }
36962
- };
36963
- var RemoteTransportError = class extends Error {
36964
- /**
36965
- * The status the peer sent, when headers arrived and only the BODY was
36966
- * refused.
36967
- *
36968
- * Undefined for the ordinary case this class was written for — no answer at
36969
- * all. It exists because two paths reject after a status has already been
36970
- * delivered: an oversized body and an aborted response. Discarding it there
36971
- * reported a deployment answering 401 with a verbose body as a network
36972
- * outage, which sends the reader to look at their network instead of their
36973
- * credential.
36974
- */
36975
- constructor(reason, status) {
36976
- super(`control-plane request did not complete: ${reason}`);
36977
- this.status = status;
36978
- this.name = "RemoteTransportError";
36979
- }
36980
- status;
36981
- };
36982
- async function send(options) {
36983
- const url2 = new URL(options.url);
36984
- const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
36985
- const send_ = url2.protocol === "http:" ? httpRequest : httpsRequest;
36986
- const requestOptions = {
36987
- method: options.method,
36988
- headers: {
36989
- // CALLER HEADERS FIRST, so this module's own are not overridable. Spread
36990
- // last they win, and two of the values below are ones no caller may
36991
- // replace: `x-api-key` is the credential, and `content-length` is the
36992
- // byte count that stops a multi-byte body being truncated by the
36993
- // receiver. `SendOptions.headers` is a free-form record on an exported
36994
- // function, so "no caller does that today" is not the guarantee to rely
36995
- // on. The one header any caller actually passes — `if-none-match` on the
36996
- // conditional GET — is untouched by this order.
36997
- ...options.headers,
36998
- // The credential. One header, matching what the deployment authenticates
36999
- // on; a second copy in an `Authorization` header would be one more place
37000
- // it can be logged by an intermediary for no gain.
37001
- //
37002
- // Spread conditionally rather than assigned as `undefined`: Node's header
37003
- // handling and `content-length` bookkeeping treat a present-but-undefined
37004
- // key differently from an absent one, and "the header is not there" is
37005
- // the property the attach flow needs.
37006
- ...options.apiKey === void 0 ? {} : { "x-api-key": options.apiKey },
37007
- accept: "application/json",
37008
- ...options.body === void 0 ? {} : {
37009
- "content-type": "application/json",
37010
- // Byte length, not string length: a multi-byte body sent with a
37011
- // character count is truncated by the receiver.
37012
- "content-length": String(Buffer.byteLength(options.body))
37013
- }
37014
- }
37015
- };
37016
- return new Promise((resolve2, reject) => {
37017
- let settled = false;
37018
- const fail = (reason, status) => {
37019
- if (settled) return;
37020
- settled = true;
37021
- reject(new RemoteTransportError(reason, status));
37022
- };
37023
- const req = send_(url2, requestOptions, (res) => {
37024
- const chunks = [];
37025
- let size = 0;
37026
- res.on("data", (chunk) => {
37027
- size += chunk.length;
37028
- if (size > MAX_RESPONSE_BYTES) {
37029
- fail(`response exceeded ${String(MAX_RESPONSE_BYTES)} bytes`, res.statusCode);
37030
- res.destroy();
37031
- req.destroy();
37032
- return;
37033
- }
37034
- chunks.push(chunk);
37035
- });
37036
- res.on("aborted", () => {
37037
- fail("the response was aborted", res.statusCode);
37038
- });
37039
- res.on("end", () => {
37040
- if (settled) return;
37041
- settled = true;
37042
- resolve2({
37043
- status: res.statusCode ?? 0,
37044
- headers: res.headers,
37045
- body: Buffer.concat(chunks).toString("utf8")
37046
- });
37047
- });
37048
- });
37049
- const deadline = setTimeout(() => {
37050
- fail(`no response within ${String(timeoutMs)}ms`);
37051
- req.destroy();
37052
- }, timeoutMs);
37053
- deadline.unref();
37054
- req.on("upgrade", (_res, socket) => {
37055
- fail("the deployment answered with a protocol upgrade");
37056
- socket.destroy();
37057
- });
37058
- req.on("close", () => {
37059
- fail("the connection closed before a response was read");
37060
- clearTimeout(deadline);
37061
- });
37062
- req.on("error", (err) => {
37063
- fail(err.message);
37064
- });
37065
- if (options.body !== void 0) req.write(options.body);
37066
- req.end();
37067
- });
37068
- }
37069
-
37070
- // ../../packages/remote/src/client.ts
37071
- var ROUTES = {
37072
- events: "/v1/events",
37073
- auditEvents: "/v1/audit-events",
37074
- auditEventsBatch: "/v1/audit-events/batch",
37075
- inventory: "/v1/inventory",
37076
- storePosture: "/v1/store-posture",
37077
- policyBundle: "/v1/policy-bundle",
37078
- whoami: "/v1/plugin/whoami",
37079
- shares: "/v1/shares"
37080
- };
37081
- function headerValue(response, name) {
37082
- const raw = response.headers[name];
37083
- if (raw === void 0) return void 0;
37084
- return Array.isArray(raw) ? raw[0] : raw;
37085
- }
37086
- function okBody(response) {
37087
- if (response.status < 200 || response.status >= 300) {
37088
- throw new RemoteRequestError(response.status);
37089
- }
37090
- return response.body;
37091
- }
37092
- function parsed(schema, body, route) {
37093
- let json2;
37094
- try {
37095
- json2 = JSON.parse(body);
37096
- } catch {
37097
- throw new RemoteResponseInvalid(route, "a body that is not JSON");
37098
- }
37099
- const result = schema.safeParse(json2);
37100
- if (!result.success) {
37101
- throw new RemoteResponseInvalid(route, "a body this client cannot read");
37102
- }
37103
- return result.data;
37104
- }
37105
- function withoutTrailingSlashes(endpoint) {
37106
- let end = endpoint.length;
37107
- while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH) end -= 1;
37108
- return endpoint.slice(0, end);
37109
- }
37110
- var SLASH = "/".charCodeAt(0);
37111
- function createRemoteClient(options) {
37112
- const base = withoutTrailingSlashes(options.endpoint);
37113
- const url2 = (route) => `${base}${route}`;
37114
- const common = { apiKey: options.apiKey, timeoutMs: options.timeoutMs };
37115
- const sendOne = async (event) => {
37116
- const validated = RecordAuditEventRequest.safeParse(event);
37117
- if (!validated.success) throw new RemoteRequestInvalid(ROUTES.auditEvents, validated.error);
37118
- const response = await send({
37119
- ...common,
37120
- method: "POST",
37121
- url: url2(ROUTES.auditEvents),
37122
- body: JSON.stringify(validated.data)
37123
- });
37124
- okBody(response);
37125
- };
37126
- return {
37127
- async ingestEvents(batch) {
37128
- const response = await send({
37129
- ...common,
37130
- method: "POST",
37131
- url: url2(ROUTES.events),
37132
- body: JSON.stringify(batch)
37133
- });
37134
- return parsed(IngestAck, okBody(response), ROUTES.events);
37135
- },
37136
- async ingestInventory(context) {
37137
- const response = await send({
37138
- ...common,
37139
- method: "POST",
37140
- url: url2(ROUTES.inventory),
37141
- body: JSON.stringify(context)
37142
- });
37143
- return parsed(ResolvedInventory, okBody(response), ROUTES.inventory);
37144
- },
37145
- async recordAuditEvent(event) {
37146
- await sendOne(event);
37147
- },
37148
- async recordAuditEvents(events) {
37149
- const validated = RecordAuditEventBatch.safeParse({ events });
37150
- if (!validated.success) {
37151
- throw new RemoteRequestInvalid(ROUTES.auditEventsBatch, validated.error);
37152
- }
37153
- const response = await send({
37154
- ...common,
37155
- method: "POST",
37156
- url: url2(ROUTES.auditEventsBatch),
37157
- body: JSON.stringify(validated.data)
37158
- });
37159
- if (response.status === 404) {
37160
- for (const event of validated.data.events) await sendOne(event);
37161
- return { accepted: validated.data.events.length };
37162
- }
37163
- return parsed(AuditEventBatchAck, okBody(response), ROUTES.auditEventsBatch);
37164
- },
37165
- async reportStorePosture(snapshot) {
37166
- const response = await send({
37167
- ...common,
37168
- method: "POST",
37169
- url: url2(ROUTES.storePosture),
37170
- body: JSON.stringify(snapshot)
37171
- });
37172
- okBody(response);
37173
- },
37174
- async getPolicyBundle(etag) {
37175
- const response = await send({
37176
- ...common,
37177
- method: "GET",
37178
- url: url2(ROUTES.policyBundle),
37179
- ...etag === void 0 ? {} : { headers: { "if-none-match": etag } }
37180
- });
37181
- if (response.status === 304) {
37182
- return { changed: false, etag: headerValue(response, "etag") ?? etag };
37183
- }
37184
- const bundle = parsed(PolicyBundle, okBody(response), ROUTES.policyBundle);
37185
- return { changed: true, bundle, etag: headerValue(response, "etag") };
37186
- },
37187
- async whoami() {
37188
- const response = await send({ ...common, method: "GET", url: url2(ROUTES.whoami) });
37189
- return parsed(PluginWhoami, okBody(response), ROUTES.whoami);
37190
- },
37191
- async recordProjectEgress(request) {
37192
- const validated = EgressIngestRequest.safeParse(request);
37193
- if (!validated.success) throw new RemoteRequestInvalid(ROUTES.shares, validated.error);
37194
- const response = await send({
37195
- ...common,
37196
- method: "POST",
37197
- url: url2(ROUTES.shares),
37198
- body: JSON.stringify(validated.data)
37199
- });
37200
- okBody(response);
37201
- }
37202
- };
37203
- }
37930
+ // ../../packages/plugin-runtime/src/attached/capture-rebuild.ts
37931
+ var CORRELATION_ID = EventMetadata.shape.correlationId;
37932
+ var TRACE_ID = EventMetadata.shape.traceId;
37933
+ var EXCEPTION_ID = EventMetadata.shape.exceptionIds.unwrap().element;
37204
37934
 
37205
37935
  // ../../packages/plugin-runtime/src/attached/history-sync-trigger.ts
37206
37936
  import { spawn } from "child_process";
@@ -37232,14 +37962,14 @@ function spawnDetached(scriptPath) {
37232
37962
  }
37233
37963
 
37234
37964
  // ../../packages/plugin-runtime/src/attached/plugin-block.ts
37235
- import { readFileSync as readFileSync15 } from "fs";
37965
+ import { readFileSync as readFileSync16 } from "fs";
37236
37966
  var manifestBuildCache = /* @__PURE__ */ new Map();
37237
37967
  function readManifestBuild(manifestUrl, packageName) {
37238
37968
  const key = manifestUrl.href;
37239
37969
  if (!manifestBuildCache.has(key)) {
37240
37970
  let build;
37241
37971
  try {
37242
- const manifest = JSON.parse(readFileSync15(manifestUrl, "utf8"));
37972
+ const manifest = JSON.parse(readFileSync16(manifestUrl, "utf8"));
37243
37973
  build = typeof manifest.version === "string" && manifest.version.length > 0 ? { package: packageName, version: manifest.version } : void 0;
37244
37974
  } catch {
37245
37975
  build = void 0;
@@ -37266,7 +37996,7 @@ function createPluginBlock(build, policyStore) {
37266
37996
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
37267
37997
  import { randomUUID as randomUUID16 } from "crypto";
37268
37998
  import { readFile as readFile2, rm, writeFile as writeFile2 } from "fs/promises";
37269
- import { join as join23 } from "path";
37999
+ import { join as join24 } from "path";
37270
38000
 
37271
38001
  // ../../packages/plugin-runtime/src/attached/atomic-publish.ts
37272
38002
  import { rename as rename2 } from "fs/promises";
@@ -37290,7 +38020,7 @@ async function publishByRename(tmp, file2, move = rename2) {
37290
38020
 
37291
38021
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
37292
38022
  function createPolicyStore(dir = dataDir()) {
37293
- const file2 = join23(dir, "policy-cache.json");
38023
+ const file2 = join24(dir, "policy-cache.json");
37294
38024
  async function read() {
37295
38025
  try {
37296
38026
  const raw = await readFile2(file2, "utf8");
@@ -37299,22 +38029,32 @@ function createPolicyStore(dir = dataDir()) {
37299
38029
  const record2 = parsed2;
37300
38030
  const bundle = PolicyBundle.parse(record2.bundle);
37301
38031
  const fetchedAtMs = typeof record2.fetchedAtMs === "number" ? record2.fetchedAtMs : 0;
37302
- const etag = typeof record2.etag === "string" ? record2.etag : void 0;
38032
+ const stored = typeof record2.etag === "string" ? record2.etag : void 0;
38033
+ const replayable = record2.shapeId === POLICY_BUNDLE_SHAPE_ID || knowsMoreThanThisBuild(record2.shapeId);
38034
+ const etag = replayable ? stored : void 0;
37303
38035
  return { bundle, fetchedAtMs, ...etag === void 0 ? {} : { etag } };
37304
38036
  } catch {
37305
38037
  return null;
37306
38038
  }
37307
38039
  }
37308
- async function write(bundle, etag) {
37309
- await ensureDataDir(dir);
37310
- const stored = {
37311
- bundle,
37312
- fetchedAtMs: Date.now(),
37313
- ...etag === void 0 ? {} : { etag }
37314
- };
38040
+ function knowsMoreThanThisBuild(shapeId) {
38041
+ if (typeof shapeId !== "string" || shapeId === "") return false;
38042
+ const theirs = new Set(shapeId.split(","));
38043
+ const ours = new Set(POLICY_BUNDLE_SHAPE_ID.split(","));
38044
+ return theirs.size > ours.size && [...ours].every((key) => theirs.has(key));
38045
+ }
38046
+ async function priorRecord() {
38047
+ try {
38048
+ const parsed2 = JSON.parse(await readFile2(file2, "utf8"));
38049
+ return typeof parsed2 === "object" && parsed2 !== null ? parsed2 : null;
38050
+ } catch {
38051
+ return null;
38052
+ }
38053
+ }
38054
+ async function publishRecord(record2) {
37315
38055
  const tmp = `${file2}.${randomUUID16()}.tmp`;
37316
38056
  try {
37317
- await writeFile2(tmp, JSON.stringify(stored), {
38057
+ await writeFile2(tmp, JSON.stringify(record2), {
37318
38058
  encoding: "utf8",
37319
38059
  mode: DATA_FILE_MODE,
37320
38060
  flag: "wx"
@@ -37325,6 +38065,27 @@ function createPolicyStore(dir = dataDir()) {
37325
38065
  throw err;
37326
38066
  }
37327
38067
  }
38068
+ async function write(bundle, etag) {
38069
+ await ensureDataDir(dir);
38070
+ const prior = await priorRecord();
38071
+ const priorVersion = prior?.bundle?.version;
38072
+ if (prior !== null && knowsMoreThanThisBuild(prior.shapeId) && priorVersion === bundle.version) {
38073
+ await publishRecord({
38074
+ ...prior,
38075
+ fetchedAtMs: Date.now()
38076
+ });
38077
+ return;
38078
+ }
38079
+ await publishRecord({
38080
+ bundle,
38081
+ fetchedAtMs: Date.now(),
38082
+ // Stamped on EVERY write, the 304 arm's included: that arm hands back the
38083
+ // bundle it already holds, and the point of the stamp is to describe the
38084
+ // build that last narrowed those bytes, which is this one.
38085
+ shapeId: POLICY_BUNDLE_SHAPE_ID,
38086
+ ...etag === void 0 ? {} : { etag }
38087
+ });
38088
+ }
37328
38089
  return { read, write, file: file2 };
37329
38090
  }
37330
38091
 
@@ -37490,11 +38251,11 @@ function readStorePosture(dbPath2) {
37490
38251
  // ../../packages/plugin-runtime/src/attached/posture-store.ts
37491
38252
  import { randomUUID as randomUUID17 } from "crypto";
37492
38253
  import { readFile as readFile3, rm as rm2, writeFile as writeFile3 } from "fs/promises";
37493
- import { join as join24 } from "path";
38254
+ import { join as join25 } from "path";
37494
38255
  var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
37495
38256
  function createPostureStore(dir = settingsDir(), legacyDir) {
37496
- const file2 = join24(dir, "posture-state.json");
37497
- const legacyFile = legacyDir === void 0 ? null : join24(legacyDir, "posture-state.json");
38257
+ const file2 = join25(dir, "posture-state.json");
38258
+ const legacyFile = legacyDir === void 0 ? null : join25(legacyDir, "posture-state.json");
37498
38259
  async function persist(state) {
37499
38260
  await ensureDataDir(dir);
37500
38261
  const tmp = `${file2}.${randomUUID17()}.tmp`;
@@ -37562,8 +38323,8 @@ function createPostureStore(dir = settingsDir(), legacyDir) {
37562
38323
  }
37563
38324
 
37564
38325
  // ../../packages/plugin-runtime/src/attached/sync-state.ts
37565
- import { readFileSync as readFileSync16 } from "fs";
37566
- import { join as join25 } from "path";
38326
+ import { readFileSync as readFileSync17 } from "fs";
38327
+ import { join as join26 } from "path";
37567
38328
 
37568
38329
  // ../../packages/plugin-runtime/src/attached/status.ts
37569
38330
  var REFUSAL_LINES = {
@@ -37905,9 +38666,21 @@ var StandaloneDataGateway = class {
37905
38666
  // for the whole of it, so a member that threw would make that answer a lie
37906
38667
  // the moment a composite delegated to it. A store-level no-op is the honest
37907
38668
  // shape — a standalone machine has nothing delivered to record.
38669
+ markCaptureOwed(event) {
38670
+ this.db.markCaptureOwed(event);
38671
+ }
37908
38672
  markCaptureDelivered(event, atMs) {
37909
38673
  this.db.markCaptureDelivered(event, atMs);
37910
38674
  }
38675
+ // Implemented, not stubbed, for the same reason its sibling above is: the
38676
+ // attached gateway is a DECORATOR over an instance of this class
38677
+ // (`attached/factory.ts` builds one and passes it as `deps.local`), so every
38678
+ // stamp the live forward makes lands here with a non-empty array. This is the
38679
+ // production write path for that feature, not a shape-satisfying no-op — a
38680
+ // machine that is merely standalone simply never calls it.
38681
+ markAuditEventsDelivered(events, atMs) {
38682
+ this.db.markAuditEventsDelivered(events, atMs);
38683
+ }
37911
38684
  staleBinaryNotice(currentVersion) {
37912
38685
  try {
37913
38686
  const newest = this.db.installedPacks.newestRecordedBinary();
@@ -38191,7 +38964,7 @@ function pluginBuild() {
38191
38964
 
38192
38965
  // src/history/reconcile-trigger.ts
38193
38966
  import { spawn as spawn3 } from "child_process";
38194
- import { dirname as dirname5, join as join27 } from "path";
38967
+ import { dirname as dirname6, join as join28 } from "path";
38195
38968
  import { fileURLToPath as fileURLToPath4 } from "url";
38196
38969
 
38197
38970
  // src/history/tail.ts
@@ -38201,11 +38974,11 @@ import {
38201
38974
  fstatSync as fstatSync2,
38202
38975
  mkdirSync as mkdirSync5,
38203
38976
  openSync as openSync3,
38204
- readFileSync as readFileSync17,
38977
+ readFileSync as readFileSync18,
38205
38978
  readSync as readSync2,
38206
38979
  writeFileSync as writeFileSync8
38207
38980
  } from "fs";
38208
- import { join as join26 } from "path";
38981
+ import { join as join27 } from "path";
38209
38982
  var SAFE_SESSION_ID = /^[A-Za-z0-9._-]+$/;
38210
38983
  function safeSessionId(sessionId) {
38211
38984
  if (SAFE_SESSION_ID.test(sessionId) && sessionId !== "." && sessionId !== "..") {
@@ -38221,8 +38994,8 @@ function triggerReconcile(dataDir2, sessionId, transcriptPath) {
38221
38994
  try {
38222
38995
  const marker = `${RECONCILE_MARKER_PREFIX}-${safeSessionId(sessionId)}`;
38223
38996
  if (throttled(dataDir2, marker, RECONCILE_THROTTLE_MS)) return;
38224
- const here = dirname5(fileURLToPath4(import.meta.url));
38225
- const child = spawn3(process.execPath, [join27(here, "reconcile.js"), sessionId, transcriptPath], {
38997
+ const here = dirname6(fileURLToPath4(import.meta.url));
38998
+ const child = spawn3(process.execPath, [join28(here, "reconcile.js"), sessionId, transcriptPath], {
38226
38999
  detached: true,
38227
39000
  stdio: "ignore"
38228
39001
  });
@@ -38232,9 +39005,9 @@ function triggerReconcile(dataDir2, sessionId, transcriptPath) {
38232
39005
  }
38233
39006
 
38234
39007
  // src/history/transcripts.ts
38235
- import { closeSync as closeSync4, openSync as openSync4, readdirSync as readdirSync5, readFileSync as readFileSync18, readSync as readSync3, statSync as statSync10 } from "fs";
39008
+ import { closeSync as closeSync4, openSync as openSync4, readdirSync as readdirSync5, readFileSync as readFileSync19, readSync as readSync3, statSync as statSync10 } from "fs";
38236
39009
  import { homedir as homedir3 } from "os";
38237
- import { join as join28 } from "path";
39010
+ import { join as join29 } from "path";
38238
39011
  function isRecord(value) {
38239
39012
  return typeof value === "object" && value !== null;
38240
39013
  }
@@ -38308,16 +39081,16 @@ function getString(record2, key) {
38308
39081
  }
38309
39082
 
38310
39083
  // src/hooks/store-health.ts
38311
- import { mkdirSync as mkdirSync6, readFileSync as readFileSync19, writeFileSync as writeFileSync9 } from "fs";
38312
- import { dirname as dirname6, join as join29 } from "path";
39084
+ import { mkdirSync as mkdirSync6, readFileSync as readFileSync20, writeFileSync as writeFileSync9 } from "fs";
39085
+ import { dirname as dirname7, join as join30 } from "path";
38313
39086
  var STORE_REDIRECT_MARKER = "store-redirect-last-session";
38314
39087
  function markerDirs(dataDir2) {
38315
- return [dataDir2, dirname6(dataDir2)];
39088
+ return [dataDir2, dirname7(dataDir2)];
38316
39089
  }
38317
39090
  function alreadyClaimed(dirs, marker, sessionId) {
38318
39091
  return dirs.some((dir) => {
38319
39092
  try {
38320
- return readFileSync19(join29(dir, marker), "utf8") === sessionId;
39093
+ return readFileSync20(join30(dir, marker), "utf8") === sessionId;
38321
39094
  } catch {
38322
39095
  return false;
38323
39096
  }
@@ -38327,7 +39100,7 @@ function recordClaim(dirs, marker, sessionId) {
38327
39100
  for (const dir of dirs) {
38328
39101
  try {
38329
39102
  mkdirSync6(dir, { recursive: true, mode: DATA_DIR_MODE });
38330
- writeFileSync9(join29(dir, marker), sessionId, { mode: DATA_FILE_MODE });
39103
+ writeFileSync9(join30(dir, marker), sessionId, { mode: DATA_FILE_MODE });
38331
39104
  return;
38332
39105
  } catch {
38333
39106
  }
@@ -38352,7 +39125,7 @@ function formatMode(mode) {
38352
39125
  }
38353
39126
  function warnIfStoreRedirected(config2, sessionId, write = (message2) => void process.stderr.write(message2)) {
38354
39127
  try {
38355
- const paths = symlinkedStorePaths(dirname6(config2.dataDir));
39128
+ const paths = symlinkedStorePaths(dirname7(config2.dataDir));
38356
39129
  if (paths.length === 0) return;
38357
39130
  if (!sessionId) {
38358
39131
  write(storeRedirectedMessage(paths));
@@ -38371,7 +39144,7 @@ function harnessVersion() {
38371
39144
  const manifestPath = process.argv[2];
38372
39145
  if (!manifestPath) return void 0;
38373
39146
  try {
38374
- const manifest = JSON.parse(readFileSync20(manifestPath, "utf8"));
39147
+ const manifest = JSON.parse(readFileSync21(manifestPath, "utf8"));
38375
39148
  return typeof manifest.version === "string" ? manifest.version : void 0;
38376
39149
  } catch {
38377
39150
  return void 0;