@akasecurity/ai-tc-claude-code 0.9.11 → 0.9.13

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.
@@ -50,7 +50,7 @@ var require_ignore = __commonJS({
50
50
  var REGEX_SPLITALL_CRLF = /\r?\n/g;
51
51
  var REGEX_TEST_INVALID_PATH = /^\.{0,2}\/|^\.{1,2}$/;
52
52
  var REGEX_TEST_TRAILING_SLASH = /\/$/;
53
- var SLASH = "/";
53
+ var SLASH2 = "/";
54
54
  var TMP_KEY_IGNORE = "node-ignore";
55
55
  if (typeof Symbol !== "undefined") {
56
56
  TMP_KEY_IGNORE = /* @__PURE__ */ Symbol.for("node-ignore");
@@ -422,11 +422,11 @@ var require_ignore = __commonJS({
422
422
  if (!REGEX_TEST_TRAILING_SLASH.test(path)) {
423
423
  return this.test(path);
424
424
  }
425
- const slices = path.split(SLASH).filter(Boolean);
425
+ const slices = path.split(SLASH2).filter(Boolean);
426
426
  slices.pop();
427
427
  if (slices.length) {
428
428
  const parent = this._t(
429
- slices.join(SLASH) + SLASH,
429
+ slices.join(SLASH2) + SLASH2,
430
430
  this._testCache,
431
431
  true,
432
432
  slices
@@ -442,14 +442,14 @@ var require_ignore = __commonJS({
442
442
  return cache[path];
443
443
  }
444
444
  if (!slices) {
445
- slices = path.split(SLASH).filter(Boolean);
445
+ slices = path.split(SLASH2).filter(Boolean);
446
446
  }
447
447
  slices.pop();
448
448
  if (!slices.length) {
449
449
  return cache[path] = this._rules.test(path, checkUnignored, MODE_IGNORE);
450
450
  }
451
451
  const parent = this._t(
452
- slices.join(SLASH) + SLASH,
452
+ slices.join(SLASH2) + SLASH2,
453
453
  cache,
454
454
  checkUnignored,
455
455
  slices
@@ -493,7 +493,7 @@ var require_ignore = __commonJS({
493
493
 
494
494
  // ../../packages/plugin-sdk/src/config.ts
495
495
  import { existsSync as existsSync8 } from "fs";
496
- import { join as join14 } from "path";
496
+ import { join as join16 } from "path";
497
497
 
498
498
  // ../../packages/persistence/src/attached-derived.ts
499
499
  import { rmSync } from "fs";
@@ -504,6 +504,14 @@ var POLICY_CACHE_FILENAME = "policy-cache.json";
504
504
  import { chmodSync as chmodSync2, lstatSync as lstatSync2, readFileSync, rmSync as rmSync3, statSync } from "fs";
505
505
  import { join as join2 } from "path";
506
506
 
507
+ // ../../packages/schema/src/drizzle/deferred-migrations.ts
508
+ var DEFERRED_MIGRATION_TAGS = [
509
+ "0031_audit_capture_by_time_index",
510
+ "0032_audit_capture_by_id_index",
511
+ "0033_audit_capture_location_index",
512
+ "0034_findings_read_indexes"
513
+ ];
514
+
507
515
  // ../../packages/schema/src/drizzle/sqlite-ddl.ts
508
516
  var SQLITE_MIGRATIONS = [
509
517
  {
@@ -621,6 +629,30 @@ var SQLITE_MIGRATIONS = [
621
629
  {
622
630
  tag: "0028_activity_session_probe_indexes",
623
631
  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"
632
+ },
633
+ {
634
+ tag: "0029_audit_capture_rollup_index",
635
+ sql: "CREATE INDEX `idx_audit_capture_rollup` ON `audit_events` (`event_type`,`started_at`,`repo`,`id`) WHERE event_type IN ('prompt','response','code_change','tool_use');"
636
+ },
637
+ {
638
+ tag: "0030_audit_content_expiry",
639
+ sql: "ALTER TABLE `audit_events` ADD `content_expired_at` integer;--> statement-breakpoint\nCREATE INDEX `idx_audit_expirable_body` ON `audit_events` (`started_at`) WHERE content IS NOT NULL;"
640
+ },
641
+ {
642
+ tag: "0031_audit_capture_by_time_index",
643
+ sql: "CREATE INDEX `idx_audit_capture_by_time` ON `audit_events` (`started_at`,`id`,`event_type`,`root_session_id`,`source_tool`,`repo`,`file_path`,`tool_name`) WHERE event_type IN ('prompt','response','code_change','tool_use');"
644
+ },
645
+ {
646
+ tag: "0032_audit_capture_by_id_index",
647
+ sql: "CREATE INDEX `idx_audit_capture_by_id` ON `audit_events` (`id`,`started_at`,`event_type`,`root_session_id`,`source_tool`,`repo`,`file_path`,`tool_name`) WHERE event_type IN ('prompt','response','code_change','tool_use');"
648
+ },
649
+ {
650
+ tag: "0033_audit_capture_location_index",
651
+ sql: "CREATE INDEX `idx_audit_capture_location` ON `audit_events` (`repo`,`file_path`,`started_at`,`id`,`event_type`) WHERE event_type IN ('prompt','response','code_change','tool_use');"
652
+ },
653
+ {
654
+ tag: "0034_findings_read_indexes",
655
+ sql: "CREATE INDEX `idx_inspection_definitions_rule` ON `inspection_definitions` (`rule_id`,`severity`,`category`);--> statement-breakpoint\nCREATE INDEX `idx_inspection_findings_def` ON `inspection_findings` (`inspection_definition_id`,`audit_event_id`);--> statement-breakpoint\nCREATE INDEX `idx_inspection_findings_event_cover` ON `inspection_findings` (`audit_event_id`,`inspection_definition_id`,`action_taken`,`finding_key`,`id`);"
624
656
  }
625
657
  ];
626
658
 
@@ -20448,7 +20480,17 @@ var UNPRICEABLE_PROVIDERS = Object.freeze([
20448
20480
  "gateway",
20449
20481
  "unknown",
20450
20482
  "cli",
20451
- "api"
20483
+ "api",
20484
+ // The browser extension's native host records these as `llm_call.provider`
20485
+ // for a web-chat turn — the web tool id, deliberately never the vendor id
20486
+ // (`openai`/`anthropic`) the session root carries. Subscription traffic
20487
+ // burns rate-limit budget, not dollar credits, and listing them here is
20488
+ // what keeps that true structurally: a later maintainer who wants to price
20489
+ // web-chat traffic at API rates has to delete this entry first, and meet
20490
+ // the reason on the way, rather than quietly adding one to
20491
+ // PROVIDER_PLATFORM.
20492
+ "chatgpt",
20493
+ "claude-ai"
20452
20494
  ]);
20453
20495
  function platformForProvider(provider) {
20454
20496
  return PROVIDER_PLATFORM.get(provider.trim().toLowerCase()) ?? null;
@@ -20591,7 +20633,12 @@ var HARNESS = {
20591
20633
  ClaudeDesktop: "claudedesktop",
20592
20634
  ChatGpt: "chatgpt",
20593
20635
  ClaudeAi: "claudeai",
20594
- Api: "api"
20636
+ Api: "api",
20637
+ // Not a coding assistant a person drives — an in-process SDK embedded in an
20638
+ // application, so it has no IDE/CLI/desktop/web surface of its own. Carries
20639
+ // the same id as its SOURCE_TOOL counterpart, unlike every capture-side tool
20640
+ // whose wire spelling differs from its display spelling.
20641
+ AiTcSdk: "ai-tc-sdk"
20595
20642
  };
20596
20643
  var Harness = external_exports.enum(HARNESS).meta({ id: "Harness" });
20597
20644
  var SOURCE_TOOL = {
@@ -20607,9 +20654,15 @@ var SOURCE_TOOL = {
20607
20654
  // whose tool could not be identified both render through the read side's
20608
20655
  // miss path rather than as a harness of their own.
20609
20656
  Cli: "cli",
20610
- Unknown: "unknown"
20657
+ Unknown: "unknown",
20658
+ // The wire id an in-process, request-path SDK stamps on its own structural
20659
+ // rows (`request_decision`) — never a capture of prompt/response/tool text,
20660
+ // since the SDK sits in front of a model call rather than inside a coding
20661
+ // assistant's own hook contract.
20662
+ AiTcSdk: "ai-tc-sdk"
20611
20663
  };
20612
20664
  var SourceTool = external_exports.enum(SOURCE_TOOL).meta({ id: "SourceTool" });
20665
+ var WebSourceTool = SourceTool.extract(["ChatGpt", "ClaudeAi"]);
20613
20666
  var TOOL_TO_HARNESS = {
20614
20667
  [SOURCE_TOOL.ClaudeCode]: HARNESS.ClaudeCode,
20615
20668
  [SOURCE_TOOL.ClaudeDesktop]: HARNESS.ClaudeDesktop,
@@ -20618,7 +20671,12 @@ var TOOL_TO_HARNESS = {
20618
20671
  [SOURCE_TOOL.ChatGpt]: HARNESS.ChatGpt,
20619
20672
  [SOURCE_TOOL.Codex]: HARNESS.Codex,
20620
20673
  [SOURCE_TOOL.Antigravity]: HARNESS.Antigravity,
20621
- [SOURCE_TOOL.ClaudeAi]: HARNESS.ClaudeAi
20674
+ [SOURCE_TOOL.ClaudeAi]: HARNESS.ClaudeAi,
20675
+ // Wire and display id are the same string here, but the row still belongs:
20676
+ // both vocabularies carry the `AiTcSdk` member, and the join is exactly
20677
+ // their intersection — leaving a shared member out would read as an
20678
+ // uninstrumented tool on both surfaces, which this one is not.
20679
+ [SOURCE_TOOL.AiTcSdk]: HARNESS.AiTcSdk
20622
20680
  };
20623
20681
 
20624
20682
  // ../../packages/schema/src/zod/finding.ts
@@ -20652,7 +20710,8 @@ var FindingProvider = Harness.extract([
20652
20710
  "ClaudeAi",
20653
20711
  "Codex",
20654
20712
  "Antigravity",
20655
- "Api"
20713
+ "Api",
20714
+ "AiTcSdk"
20656
20715
  ]).meta({ id: "FindingProvider" });
20657
20716
  var FindingCategory = external_exports.enum([
20658
20717
  "secret",
@@ -20668,6 +20727,15 @@ var FindingCategory = external_exports.enum([
20668
20727
  ]).meta({ id: "FindingCategory" });
20669
20728
  var FindingOrigin = external_exports.enum(["in-flight", "at-rest"]).meta({ id: "FindingOrigin" });
20670
20729
  var FindingStatus = external_exports.enum(["open", "handled", "resolved", "dismissed"]).meta({ id: "FindingStatus" });
20730
+ var SyncFailureReason = external_exports.enum(["deployment_refused", "payload_invalid", "detached_undelivered"]).meta({ id: "SyncFailureReason" });
20731
+ var FindingDeliveryState = external_exports.enum(["sent", "queued", "not_sent", "never_offered", "local_scan"]).meta({ id: "FindingDeliveryState" });
20732
+ var FindingDelivery = external_exports.object({
20733
+ state: FindingDeliveryState,
20734
+ // The delivery time for `sent`; the failure time for `not_sent` when recorded.
20735
+ at: external_exports.iso.datetime().optional(),
20736
+ // Only on `not_sent`, and only when a known reason was recorded.
20737
+ reason: SyncFailureReason.optional()
20738
+ }).meta({ id: "FindingDelivery" });
20671
20739
  var ResolutionMethod = external_exports.enum([
20672
20740
  "enforced-in-flight",
20673
20741
  "fixed-at-source",
@@ -20724,7 +20792,10 @@ var FindingInstance = external_exports.object({
20724
20792
  // The session that event belongs to, when it has one — the seam a
20725
20793
  // per-instance "view session" link needs. Absent for events captured
20726
20794
  // outside a session.
20727
- sessionId: external_exports.string().optional()
20795
+ sessionId: external_exports.string().optional(),
20796
+ // The delivery state of the event above (see FindingDelivery). Optional so
20797
+ // readers that do not project it stay valid.
20798
+ delivery: FindingDelivery.optional()
20728
20799
  }).meta({ id: "FindingInstance" });
20729
20800
  var FindingGroup = external_exports.object({
20730
20801
  id: external_exports.string(),
@@ -20776,7 +20847,10 @@ var FindingFacets = external_exports.object({
20776
20847
  // Host tool (attributes.tool_name). Present only on the instance-level
20777
20848
  // reads, which can filter by it; the type-level read omits the dimension
20778
20849
  // because a group spans tools.
20779
- tool: external_exports.array(FindingFacetItem).optional()
20850
+ tool: external_exports.array(FindingFacetItem).optional(),
20851
+ // Delivery states (FindingDeliveryState). Present only on the
20852
+ // instance-level reads, like `tool`.
20853
+ deployment: external_exports.array(FindingFacetItem).optional()
20780
20854
  }).meta({ id: "FindingFacets" });
20781
20855
  var FindingTypeSummary = FindingGroup.omit({ instances: true, match: true }).meta({
20782
20856
  id: "FindingTypeSummary"
@@ -20887,6 +20961,8 @@ var ListFindingInstancesQuery = external_exports.object({
20887
20961
  // Exact host-tool names (attributes.tool_name, e.g. 'Bash'). A real filter,
20888
20962
  // where the free-text `q` can only match the rendered "via Bash" label.
20889
20963
  tool: external_exports.array(external_exports.string()).optional(),
20964
+ // The delivery state of each finding's event (see FindingDelivery).
20965
+ deployment: external_exports.array(FindingDeliveryState).optional(),
20890
20966
  // Exact repository / file-path matches, for the drill-down out of the
20891
20967
  // locations view. A row whose event carries no repo/file matches neither.
20892
20968
  repo: external_exports.string().optional(),
@@ -20907,6 +20983,10 @@ var ListFindingInstancesResponse = external_exports.object({
20907
20983
  items: external_exports.array(FindingInstanceDetail),
20908
20984
  nextCursor: external_exports.string().nullable()
20909
20985
  }).meta({ id: "ListFindingInstancesResponse" });
20986
+ var ListFindingInstancesPage = external_exports.object({
20987
+ items: external_exports.array(FindingInstanceDetail),
20988
+ nextCursor: external_exports.string().nullable()
20989
+ }).meta({ id: "ListFindingInstancesPage" });
20910
20990
  var FindingLocationSummary = external_exports.object({
20911
20991
  // Opaque, stable, minted from the pair by encodeLocationId. It exists
20912
20992
  // because a location's identity is two values and a URL param carries one:
@@ -20949,6 +21029,8 @@ var ListFindingLocationsQuery = external_exports.object({
20949
21029
  // instances that match, and folds its status from those.
20950
21030
  status: external_exports.array(FindingStatus).optional(),
20951
21031
  tool: external_exports.array(external_exports.string()).optional(),
21032
+ // The delivery state of each finding's event (see FindingDelivery).
21033
+ deployment: external_exports.array(FindingDeliveryState).optional(),
20952
21034
  q: external_exports.string().optional(),
20953
21035
  sessionId: external_exports.string().optional(),
20954
21036
  from: external_exports.iso.datetime().optional(),
@@ -21006,18 +21088,41 @@ var AuditEventType = external_exports.enum([
21006
21088
  // 'tool_call' is the reconciler's structural row for every call, while
21007
21089
  // 'tool_use' exists only where a hook enforced against the arguments.
21008
21090
  "tool_use",
21009
- // One row per model REFUSAL: a switch onto a prohibited model that was
21010
- // denied, or a turn refused because the session was already running on one.
21011
- // A structural row like the ones above rather than a capture — it carries
21012
- // the model that was refused and nothing the user typed, because what is
21013
- // worth recording about a governance decision is the decision, and prompt
21014
- // text is the thing this product exists to keep from travelling.
21091
+ // One row per model REFUSAL, across all four seams a prohibited model can be
21092
+ // stopped at: a switch onto it, a turn already running on it, a subagent
21093
+ // spawn asking for it, or a request-path refusal an embedded request-path
21094
+ // SDK makes in-process before the call leaves the application. Which seam
21095
+ // rides `attributes.refusal_seam`, never this member name. A structural row
21096
+ // like the ones above rather than a capture — it carries the model that was
21097
+ // refused and nothing the user typed, because what is worth recording about
21098
+ // a governance decision is the decision, and prompt text is the thing this
21099
+ // product exists to keep from travelling.
21015
21100
  "model_refusal",
21101
+ // One row per request-path DECISION: a policy check an embedded request-path
21102
+ // SDK performs in-process before a model call leaves the application, or
21103
+ // against that call's non-streamed response. A structural row like
21104
+ // 'model_refusal' rather than a capture — content-free in the same way:
21105
+ // which side, which seam, what action and which field are decided rides
21106
+ // `attributes`, never this member name, and the matched text itself never
21107
+ // travels.
21108
+ //
21109
+ // A prohibited-model refusal on the request path is deliberately NOT this
21110
+ // member: it stays 'model_refusal' with `refusal_seam: 'request'`, so it
21111
+ // shares one bucket with the plugin's switch/turn/spawn refusals rather
21112
+ // than splitting one governance concept across two event types. This
21113
+ // member carries every OTHER request-path decision.
21114
+ "request_decision",
21016
21115
  // One row per config-inventory scan, hung off the session root. It is the
21017
21116
  // fact the posture inspection findings reference (findings require an
21018
21117
  // audit_event_id), and its started_at is the "scanned Nm ago" the read
21019
21118
  // surface renders.
21020
- "config_scan"
21119
+ "config_scan",
21120
+ // One row per reported browser-extension capture status, hung off the web
21121
+ // session root. The durable home of what one tab's network interception
21122
+ // is doing — a write-through of the native host's in-memory tracker, so a
21123
+ // second process (aka extension status) and a restarted host both have
21124
+ // somewhere to read it back from.
21125
+ "capture_status"
21021
21126
  ]).meta({ id: "AuditEventType" });
21022
21127
  var AttributeBag = external_exports.record(external_exports.string(), external_exports.unknown());
21023
21128
  var HostAttributes = external_exports.object({
@@ -21151,6 +21256,10 @@ var CaptureAttributes = external_exports.object({
21151
21256
  // to 'allow' — the enforcement audit trail's link back to the grant that
21152
21257
  // authorized the bypass.
21153
21258
  exception_ids: external_exports.array(external_exports.guid()).optional(),
21259
+ // The persisted spellings of EventMetadata's messageId/conversationId — the
21260
+ // join back to the `llm_call` leaf for the same assistant turn.
21261
+ message_id: external_exports.string().optional(),
21262
+ conversation_id: external_exports.string().optional(),
21154
21263
  // Whole milliseconds this capture's inspection blocked its caller — the
21155
21264
  // plugin's own added latency (see EventMetadata.inspectionMs, whose value
21156
21265
  // this is). Promoted to the `inspection_ms` generated column so the facet is
@@ -21159,7 +21268,33 @@ var CaptureAttributes = external_exports.object({
21159
21268
  // inline json_extract and is not itself an optimization.
21160
21269
  // ABSENT on replayed captures (backfill / worktree scan) and on rows written
21161
21270
  // before the measurement shipped — never present as a placeholder 0.
21162
- inspection_ms: external_exports.number().int().nonnegative().optional()
21271
+ inspection_ms: external_exports.number().int().nonnegative().optional(),
21272
+ // What a `redact` this capture could not carry out became instead (see
21273
+ // EventMetadata.redactDegradedTo, whose value this is). Present only when a
21274
+ // degrade actually happened, so absence is the ordinary case rather than a
21275
+ // reader having to distinguish it from a zero.
21276
+ //
21277
+ // PER CAPTURE, while `inspection_findings.action_taken` is per finding —
21278
+ // so on a multi-finding row this does not say which finding degraded, and
21279
+ // its presence does not mean the fallback decided the capture's action. A
21280
+ // capture denied by another finding's own Block policy carries `block`
21281
+ // here too. The full statement is on EventMetadata.redactDegradedTo; it is
21282
+ // repeated rather than referenced because a store reader opens this file.
21283
+ redact_degraded_to: ActionTaken.optional()
21284
+ }).catchall(external_exports.unknown());
21285
+ var CaptureStatusAttributes = external_exports.object({
21286
+ source_tool: external_exports.string().optional(),
21287
+ patched: external_exports.boolean().optional(),
21288
+ live: external_exports.boolean().optional(),
21289
+ blind: external_exports.boolean().optional(),
21290
+ sends_seen_dom: external_exports.number().int().nonnegative().optional(),
21291
+ exchanges_seen_net: external_exports.number().int().nonnegative().optional(),
21292
+ parse_failures: external_exports.number().int().nonnegative().optional(),
21293
+ unparsed_bodies: external_exports.number().int().nonnegative().optional(),
21294
+ shape_misses: external_exports.array(external_exports.string()).optional(),
21295
+ conversation_endpoints: external_exports.number().int().nonnegative().optional(),
21296
+ closed: external_exports.boolean().optional(),
21297
+ enforcement: external_exports.string().optional()
21163
21298
  }).catchall(external_exports.unknown());
21164
21299
  var ToolCallInspection = external_exports.object({
21165
21300
  ruleId: external_exports.string().min(1),
@@ -21358,7 +21493,17 @@ var AuditEvent = external_exports.object({
21358
21493
  /** `share` to a first-party/internal destination. */
21359
21494
  internal: external_exports.boolean(),
21360
21495
  /** Event needs review (e.g. unverified egress). */
21361
- flagged: external_exports.boolean()
21496
+ flagged: external_exports.boolean(),
21497
+ /**
21498
+ * The body this event's `title` is drawn from was cleared by local body
21499
+ * expiry, so an EMPTY title here means "gone", not "never had one".
21500
+ *
21501
+ * A separate flag rather than a sentinel written into `title`: the title is
21502
+ * rendered text, and a store-layer module that invented display copy for it
21503
+ * would be choosing words the view is supposed to choose. Additive and
21504
+ * defaulted, so an older producer still validates.
21505
+ */
21506
+ bodyExpired: external_exports.boolean().default(false)
21362
21507
  }).meta({ id: "ActivityAuditEvent" });
21363
21508
  var ActivitySessionSummary = external_exports.object({
21364
21509
  id: external_exports.string(),
@@ -22163,6 +22308,11 @@ var RemoteFailureKind = external_exports.enum([
22163
22308
  "rejected",
22164
22309
  "unreachable"
22165
22310
  ]);
22311
+ var ControlPlaneFailure = RemoteFailureKind.extract([
22312
+ "unauthorized",
22313
+ "forbidden",
22314
+ "unreachable"
22315
+ ]);
22166
22316
  var AttachDeviceRequest = external_exports.object({
22167
22317
  // This machine's own continuity id, so re-attaching ROTATES the credential
22168
22318
  // on one machine record instead of producing a second one. Client-minted
@@ -22698,6 +22848,17 @@ var EventMetadata = external_exports.object({
22698
22848
  // to 'allow' — the enforcement audit trail's link back to the grant that
22699
22849
  // authorized the bypass. Absent on captures where no exception applied.
22700
22850
  exceptionIds: external_exports.array(external_exports.guid()).optional(),
22851
+ // The assistant message this capture belongs to, and the conversation it sits
22852
+ // in — set by the browser extension's network capture so a stored `response`
22853
+ // row can be joined to the `llm_call` leaf describing the same turn. Absent
22854
+ // on every other capture path, which has no such id.
22855
+ //
22856
+ // Non-empty for the reason WebExchange.messageId is: it is the join key, and
22857
+ // a blank one matches no `llm_call` leaf. That refusal reaches only the
22858
+ // places an event is PARSED; the local write path types the event and parses
22859
+ // nothing, which is why `toCaptureAttributes` omits a blank one separately.
22860
+ messageId: external_exports.string().min(1).optional(),
22861
+ conversationId: external_exports.string().optional(),
22701
22862
  // How long THIS capture's inspection blocked its caller, in whole
22702
22863
  // milliseconds — the plugin's own added latency, NOT the LLM call it sat in
22703
22864
  // front of. Measured inside `capture()` (@akasecurity/plugin-sdk) across
@@ -22710,7 +22871,37 @@ var EventMetadata = external_exports.object({
22710
22871
  // Absent is also what every pre-measurement client writes, and what a
22711
22872
  // clock failure degrades to — a reader must treat absence as "not measured"
22712
22873
  // and never as a zero, which would read as "inspection is free".
22713
- inspectionMs: external_exports.number().int().nonnegative().optional()
22874
+ inspectionMs: external_exports.number().int().nonnegative().optional(),
22875
+ // What a `redact` this capture COULD NOT CARRY OUT became instead — the
22876
+ // workspace's `redactFallback`, applied because the field could not be
22877
+ // masked in place (a shell command, a URL, or any argument on a host whose
22878
+ // hook contract offers no rewrite channel).
22879
+ //
22880
+ // It exists because the action alone cannot say why. A finding recorded as
22881
+ // `warn` reads identically whether its detection was ASSIGNED Warn or was
22882
+ // assigned Redact on a field that could not take one — and those are
22883
+ // different facts about the same row: the first is a policy the user chose,
22884
+ // the second is a masking the host could not perform. Absent means no
22885
+ // degrade happened, which is every ordinary capture.
22886
+ //
22887
+ // TWO LIMITS a reader of a stored row has to know, because the grain here
22888
+ // is the CAPTURE while `actionTaken` is per FINDING:
22889
+ //
22890
+ // - It does not say WHICH finding degraded. A capture carrying a degraded
22891
+ // `redact` alongside a finding ASSIGNED the same action stores both
22892
+ // identically and one reason for the pair; attributing it to both
22893
+ // describes the assigned one wrongly, and to neither loses the degrade.
22894
+ // - PRESENCE IS NOT CAUSATION. The value is the action the lost redact
22895
+ // became, not the reason the capture ended as it did — a capture denied
22896
+ // by some other finding's own Block policy still carries `block` here,
22897
+ // and clearing the workspace's fallback would not have let it through.
22898
+ // Gate on the value against what a fallback can produce; never read the
22899
+ // field's presence as "this was the fallback's doing".
22900
+ //
22901
+ // Both are pinned as behaviour in @akasecurity/plugin-sdk's runtime suite.
22902
+ // Closing either means moving the reason onto the finding row, which
22903
+ // already carries its own action.
22904
+ redactDegradedTo: ActionTaken.optional()
22714
22905
  }).meta({ id: "EventMetadata" });
22715
22906
  var Event = external_exports.object({
22716
22907
  id: external_exports.guid(),
@@ -22820,7 +23011,32 @@ var RotateKeyInput = external_exports.object({
22820
23011
  confirmation: external_exports.string()
22821
23012
  });
22822
23013
 
23014
+ // ../../packages/schema/src/zod/finding-delivery.ts
23015
+ var KNOWN_REASONS = SyncFailureReason.options;
23016
+ function knownReason(value) {
23017
+ return value !== null && KNOWN_REASONS.includes(value) ? value : void 0;
23018
+ }
23019
+ function deriveFindingDelivery(row) {
23020
+ if (row.kind === "code_change") return { state: "local_scan" };
23021
+ if (row.syncedAt !== null && row.syncedAt > 0) {
23022
+ return { state: "sent", at: epochMillisToIso(row.syncedAt) };
23023
+ }
23024
+ if (row.syncedAt !== null) {
23025
+ const reason = knownReason(row.syncFailure);
23026
+ return {
23027
+ state: "not_sent",
23028
+ ...row.syncFailedAt === null ? {} : { at: epochMillisToIso(row.syncFailedAt) },
23029
+ ...reason === void 0 ? {} : { reason }
23030
+ };
23031
+ }
23032
+ if (row.outboxOwed === 1 || row.syncClaimedAt !== null) return { state: "queued" };
23033
+ return { state: "never_offered" };
23034
+ }
23035
+
22823
23036
  // ../../packages/schema/src/zod/findings-group-build.ts
23037
+ function lookupOwn(map2, key) {
23038
+ return Object.hasOwn(map2, key) ? map2[key] : void 0;
23039
+ }
22824
23040
  function toApiAction(dbVal) {
22825
23041
  const map2 = {
22826
23042
  log: "monitored",
@@ -22829,7 +23045,7 @@ function toApiAction(dbVal) {
22829
23045
  warn: "warned",
22830
23046
  allow: "allowed"
22831
23047
  };
22832
- return map2[dbVal] ?? "allowed";
23048
+ return lookupOwn(map2, dbVal) ?? "allowed";
22833
23049
  }
22834
23050
  function toApiCategory(dbVal) {
22835
23051
  if (dbVal === "code_context") return "source_code";
@@ -22837,13 +23053,18 @@ function toApiCategory(dbVal) {
22837
23053
  return parsed.success ? parsed.data : "custom";
22838
23054
  }
22839
23055
  function toApiProvider(sourceTool) {
22840
- return TOOL_TO_HARNESS[sourceTool] ?? HARNESS.Api;
23056
+ return lookupOwn(TOOL_TO_HARNESS, sourceTool) ?? HARNESS.Api;
22841
23057
  }
22842
- var STATUS_PRECEDENCE = ["open", "handled", "dismissed", "resolved"];
23058
+ var FINDING_STATUS_PRECEDENCE = [
23059
+ "open",
23060
+ "handled",
23061
+ "dismissed",
23062
+ "resolved"
23063
+ ];
22843
23064
  function foldGroupStatus(instanceStatuses) {
22844
23065
  const statuses = new Set(instanceStatuses.filter((s) => s !== void 0));
22845
23066
  if (statuses.size === 0) return void 0;
22846
- for (const candidate of STATUS_PRECEDENCE) {
23067
+ for (const candidate of FINDING_STATUS_PRECEDENCE) {
22847
23068
  if (statuses.has(candidate)) return candidate;
22848
23069
  }
22849
23070
  return void 0;
@@ -22950,11 +23171,16 @@ function applyFindingFilters(types, opts) {
22950
23171
  }
22951
23172
  return filtered;
22952
23173
  }
22953
- var SEVERITY_ORDER = { critical: 0, high: 1, medium: 2, low: 3 };
22954
- var SEVERITY_RANK = SEVERITY_ORDER;
23174
+ function rankByOrder(members2) {
23175
+ return Object.fromEntries(members2.map((member, index) => [member, index]));
23176
+ }
23177
+ var SEVERITY_RANK = rankByOrder(Severity.options);
23178
+ function severityRank(severity) {
23179
+ return lookupOwn(SEVERITY_RANK, severity);
23180
+ }
22955
23181
  function compareFindingGroupOrder(a, b) {
22956
- const rankA = SEVERITY_RANK[a.severity] ?? -1;
22957
- const rankB = SEVERITY_RANK[b.severity] ?? -1;
23182
+ const rankA = severityRank(a.severity) ?? -1;
23183
+ const rankB = severityRank(b.severity) ?? -1;
22958
23184
  const severityDiff = rankA - rankB;
22959
23185
  if (severityDiff !== 0) return severityDiff;
22960
23186
  const recencyDiff = b.latestDetectedAt.localeCompare(a.latestDetectedAt);
@@ -23029,6 +23255,20 @@ function computeFindingFacets(allTypes, opts) {
23029
23255
  }
23030
23256
 
23031
23257
  // ../../packages/schema/src/zod/findings-flat-build.ts
23258
+ function compareCodePoints(a, b) {
23259
+ const aIter = a[Symbol.iterator]();
23260
+ const bIter = b[Symbol.iterator]();
23261
+ for (; ; ) {
23262
+ const aNext = aIter.next();
23263
+ const bNext = bIter.next();
23264
+ if (aNext.done && bNext.done) return 0;
23265
+ if (aNext.done) return -1;
23266
+ if (bNext.done) return 1;
23267
+ const aPoint = aNext.value.codePointAt(0) ?? 0;
23268
+ const bPoint = bNext.value.codePointAt(0) ?? 0;
23269
+ if (aPoint !== bPoint) return aPoint - bPoint;
23270
+ }
23271
+ }
23032
23272
  function rowHaystack(row) {
23033
23273
  return [
23034
23274
  row.ruleId,
@@ -23053,6 +23293,8 @@ function matchesDimension(row, opts, dimension) {
23053
23293
  return !opts.actions?.length || opts.actions.includes(toApiAction(row.actionTaken));
23054
23294
  case "statuses":
23055
23295
  return !opts.statuses?.length || row.status !== void 0 && opts.statuses.includes(row.status);
23296
+ case "deliveries":
23297
+ return !opts.deliveries?.length || row.delivery !== void 0 && opts.deliveries.includes(row.delivery.state);
23056
23298
  case "tools":
23057
23299
  return !opts.tools?.length || row.toolName !== void 0 && opts.tools.includes(row.toolName);
23058
23300
  // An EMPTY value is a real filter here, not an absent one. The location
@@ -23079,6 +23321,7 @@ var DIMENSIONS = [
23079
23321
  "providers",
23080
23322
  "actions",
23081
23323
  "statuses",
23324
+ "deliveries",
23082
23325
  "tools",
23083
23326
  "repo",
23084
23327
  "file",
@@ -23092,10 +23335,19 @@ function matchesInstanceFilters(row, opts, except) {
23092
23335
  return true;
23093
23336
  }
23094
23337
  function toItems(counts) {
23095
- return [...counts.entries()].map(([value, count]) => ({ value, count })).sort((a, b) => b.count - a.count || a.value.localeCompare(b.value));
23338
+ return [...counts.entries()].map(([value, count]) => ({ value, count })).sort(
23339
+ (a, b) => b.count - a.count || a.value.localeCompare(b.value) || // localeCompare reports canonically-equivalent strings (an NFC and an
23340
+ // NFD spelling of the same text) as equal, so a count tie between
23341
+ // them would otherwise be ordered by whichever the Map iteration
23342
+ // produced. compareCodePoints breaks that tie deterministically, which
23343
+ // makes this a TOTAL order — not one that agrees with SQL collation,
23344
+ // which it need not: foldFacetTuples runs this same sort over grouped
23345
+ // tuples, so both paths order facets identically by construction.
23346
+ compareCodePoints(a.value, b.value)
23347
+ );
23096
23348
  }
23097
- function bump(counts, value) {
23098
- counts.set(value, (counts.get(value) ?? 0) + 1);
23349
+ function bump(counts, value, by = 1) {
23350
+ counts.set(value, (counts.get(value) ?? 0) + by);
23099
23351
  }
23100
23352
  function createInstanceFacetAccumulator(opts) {
23101
23353
  const severity = /* @__PURE__ */ new Map();
@@ -23104,6 +23356,7 @@ function createInstanceFacetAccumulator(opts) {
23104
23356
  const action = /* @__PURE__ */ new Map();
23105
23357
  const status = /* @__PURE__ */ new Map();
23106
23358
  const tool = /* @__PURE__ */ new Map();
23359
+ const deployment = /* @__PURE__ */ new Map();
23107
23360
  return {
23108
23361
  add(row) {
23109
23362
  if (matchesInstanceFilters(row, opts, "severity")) bump(severity, row.severity);
@@ -23118,6 +23371,9 @@ function createInstanceFacetAccumulator(opts) {
23118
23371
  if (row.toolName !== void 0 && matchesInstanceFilters(row, opts, "tools")) {
23119
23372
  bump(tool, row.toolName);
23120
23373
  }
23374
+ if (row.delivery !== void 0 && matchesInstanceFilters(row, opts, "deliveries")) {
23375
+ bump(deployment, row.delivery.state);
23376
+ }
23121
23377
  },
23122
23378
  facets: () => ({
23123
23379
  severity: toItems(severity),
@@ -23125,7 +23381,8 @@ function createInstanceFacetAccumulator(opts) {
23125
23381
  provider: toItems(provider),
23126
23382
  action: toItems(action),
23127
23383
  status: toItems(status),
23128
- tool: toItems(tool)
23384
+ tool: toItems(tool),
23385
+ deployment: toItems(deployment)
23129
23386
  })
23130
23387
  };
23131
23388
  }
@@ -23139,6 +23396,7 @@ function toInstanceDetail(row) {
23139
23396
  ...row.toolName === void 0 ? {} : { toolName: row.toolName },
23140
23397
  eventId: row.eventId,
23141
23398
  ...row.sessionId === void 0 ? {} : { sessionId: row.sessionId },
23399
+ ...row.delivery === void 0 ? {} : { delivery: row.delivery },
23142
23400
  ...row.user === void 0 ? {} : { user: row.user },
23143
23401
  action: toApiAction(row.actionTaken),
23144
23402
  detectedAt: row.occurredAt,
@@ -23153,12 +23411,6 @@ function toInstanceDetail(row) {
23153
23411
  policy: { id: `category:${category}`, name: category }
23154
23412
  };
23155
23413
  }
23156
- var SEVERITY_ORDER2 = {
23157
- critical: 0,
23158
- high: 1,
23159
- medium: 2,
23160
- low: 3
23161
- };
23162
23414
  function newLocationAccumulator() {
23163
23415
  return {
23164
23416
  instanceCount: 0,
@@ -23173,7 +23425,7 @@ function newLocationAccumulator() {
23173
23425
  }
23174
23426
  function addToLocation(acc, row) {
23175
23427
  acc.instanceCount += 1;
23176
- const rank = SEVERITY_ORDER2[row.severity] ?? Number.MAX_SAFE_INTEGER - 1;
23428
+ const rank = severityRank(row.severity) ?? Number.MAX_SAFE_INTEGER - 1;
23177
23429
  if (rank < acc.maxSeverityRank) {
23178
23430
  acc.maxSeverityRank = rank;
23179
23431
  acc.maxSeverity = row.severity;
@@ -23183,15 +23435,15 @@ function addToLocation(acc, row) {
23183
23435
  acc.ruleIds.add(row.ruleId);
23184
23436
  }
23185
23437
  function compareLocationOrder(a, b) {
23186
- const rankA = SEVERITY_ORDER2[a.maxSeverity] ?? -1;
23187
- const rankB = SEVERITY_ORDER2[b.maxSeverity] ?? -1;
23438
+ const rankA = severityRank(a.maxSeverity) ?? -1;
23439
+ const rankB = severityRank(b.maxSeverity) ?? -1;
23188
23440
  if (rankA !== rankB) return rankA - rankB;
23189
23441
  if (a.latestDetectedAt !== b.latestDetectedAt) {
23190
23442
  return a.latestDetectedAt < b.latestDetectedAt ? 1 : -1;
23191
23443
  }
23192
- if (a.repo !== b.repo) return a.repo < b.repo ? -1 : 1;
23193
- if (a.file !== b.file) return a.file < b.file ? -1 : 1;
23194
- return 0;
23444
+ const repoDiff = compareCodePoints(a.repo, b.repo);
23445
+ if (repoDiff !== 0) return repoDiff;
23446
+ return compareCodePoints(a.file, b.file);
23195
23447
  }
23196
23448
  function encodeLocationId(repo, file2) {
23197
23449
  return `${encodePart(repo)}/${encodePart(file2)}`;
@@ -23266,6 +23518,11 @@ var Policy = external_exports.object({
23266
23518
  // test `prohibitedModels` passes and `reversibleRuleIds` fails.
23267
23519
  provenance: PolicyProvenance.optional()
23268
23520
  }).meta({ id: "Policy" });
23521
+ var KNOWN_BUILTIN_IDS = ["monitor", "warn", "redact", "vault", "block"];
23522
+ var BuiltinPolicyId = external_exports.enum(KNOWN_BUILTIN_IDS).meta({ id: "BuiltinPolicyId" });
23523
+ var RedactFallback = BuiltinPolicyId.extract(["monitor", "warn", "block"]).meta({
23524
+ id: "RedactFallback"
23525
+ });
23269
23526
  var PolicyBundle = external_exports.object({
23270
23527
  version: external_exports.string(),
23271
23528
  policies: external_exports.array(Policy),
@@ -23313,6 +23570,16 @@ var PolicyBundle = external_exports.object({
23313
23570
  // control plane), so no name resolution stands between the decision and the
23314
23571
  // comparison.
23315
23572
  prohibitedModels: external_exports.array(external_exports.string()).optional(),
23573
+ // What a resolved `redact` becomes on a field the host cannot rewrite, as
23574
+ // the ORGANIZATION would have it. Merged raise-only against the device's own
23575
+ // `WorkspaceSettings.redactFallback` (see strongerRedactFallback below), so
23576
+ // a control plane can tighten a machine and never loosen one — the same
23577
+ // direction `mergeRaiseOnly` enforces for policies.
23578
+ //
23579
+ // Optional so an older backend, and an older on-disk cache, still parses;
23580
+ // absent leaves the device's own setting in force, which is the behaviour
23581
+ // that predates the field and the safe direction to default.
23582
+ redactFallback: RedactFallback.optional(),
23316
23583
  customKeywords: external_exports.array(external_exports.string()),
23317
23584
  fetchedAt: external_exports.iso.datetime()
23318
23585
  }).meta({ id: "PolicyBundle" });
@@ -23342,11 +23609,6 @@ function severityFloorPolicy(category) {
23342
23609
  const peak = CATEGORY_PEAK_SEVERITY[category];
23343
23610
  return peak === "critical" || peak === "high" ? "warn" : "monitor";
23344
23611
  }
23345
- var KNOWN_BUILTIN_IDS = ["monitor", "warn", "redact", "vault", "block"];
23346
- var BuiltinPolicyId = external_exports.enum(KNOWN_BUILTIN_IDS).meta({ id: "BuiltinPolicyId" });
23347
- var RedactFallback = BuiltinPolicyId.extract(["monitor", "warn", "block"]).meta({
23348
- id: "RedactFallback"
23349
- });
23350
23612
  var BUILTIN_ORDER = KNOWN_BUILTIN_IDS;
23351
23613
  var BUILTIN_POLICY_SPECS = {
23352
23614
  monitor: {
@@ -23650,7 +23912,7 @@ function isVaultConsentValid(consent) {
23650
23912
  }
23651
23913
 
23652
23914
  // ../../packages/schema/src/zod/local.ts
23653
- var WORKSPACE_SETTINGS_SPEC_VERSION = 7;
23915
+ var WORKSPACE_SETTINGS_SPEC_VERSION = 8;
23654
23916
  var MODEL_JUDGE_PAYLOAD_VERSION = 1;
23655
23917
  var RunMode = external_exports.enum(["standalone", "attached"]);
23656
23918
  var ControlPlaneConnection = external_exports.object({
@@ -23670,6 +23932,27 @@ var HistorySyncConsent = external_exports.object({
23670
23932
  payloadVersion: external_exports.number().int().positive(),
23671
23933
  endpoint: external_exports.string()
23672
23934
  });
23935
+ var WebChatCaptureConsent = external_exports.object({
23936
+ acknowledgedAt: external_exports.iso.datetime(),
23937
+ version: external_exports.number().int().positive()
23938
+ });
23939
+ var WebChatResponseCapture = external_exports.enum(["with-findings", "always", "never"]);
23940
+ var WebChatCapture = external_exports.object({
23941
+ responses: WebChatResponseCapture.default("with-findings"),
23942
+ account: external_exports.boolean().default(false),
23943
+ // Absent until granted. Presence alone does not authorize anything — see
23944
+ // isWebChatCaptureConsentValid.
23945
+ consent: WebChatCaptureConsent.optional()
23946
+ });
23947
+ var BODY_RETENTION_DEFAULT_DAYS = 30;
23948
+ var BodyRetention = external_exports.object({
23949
+ enabled: external_exports.boolean().default(false),
23950
+ // Never 0, and the ceiling is a fat-finger guard rather than a policy
23951
+ // limit — `enabled` is the real gate. A low value cannot reach a row the
23952
+ // sync ledger still owes: the sweep's age filter only ever NARROWS a
23953
+ // candidate set that is already bounded by "delivered, or never owed".
23954
+ retainDays: external_exports.number().int().min(1).max(3650).default(BODY_RETENTION_DEFAULT_DAYS)
23955
+ }).meta({ id: "BodyRetention" });
23673
23956
  var WorkspaceSettings = external_exports.object({
23674
23957
  specVersion: external_exports.number().int().positive().default(WORKSPACE_SETTINGS_SPEC_VERSION),
23675
23958
  runMode: RunMode.default("standalone"),
@@ -23718,7 +24001,23 @@ var WorkspaceSettings = external_exports.object({
23718
24001
  // carry prompt/reply/tool-output text in `content`; the key name predates
23719
24002
  // both widenings. Absent until granted, and a grant for a different endpoint
23720
24003
  // or an older payload no longer counts.
23721
- historySyncConsent: HistorySyncConsent.optional()
24004
+ historySyncConsent: HistorySyncConsent.optional(),
24005
+ // What the browser extension may record from a web chat, and the grant that
24006
+ // authorizes it. Absent until the user answers: recording something that was
24007
+ // never recorded before is never an assumed grant on upgrade, so the whole
24008
+ // block is optional rather than defaulted in. What an absent block means is
24009
+ // webChatCaptureOf's answer, in one place.
24010
+ //
24011
+ // Enforcement is NOT gated on this. A machine that has never answered still
24012
+ // blocks, redacts and warns on what a user sends; the grant covers what is
24013
+ // written down.
24014
+ webChatCapture: WebChatCapture.optional(),
24015
+ // Local body expiry (see BodyRetention). Off until switched on; expiring a
24016
+ // body never removes the row or its findings.
24017
+ bodyRetention: BodyRetention.default({
24018
+ enabled: false,
24019
+ retainDays: BODY_RETENTION_DEFAULT_DAYS
24020
+ })
23722
24021
  });
23723
24022
  function defaultWorkspaceSettings() {
23724
24023
  return WorkspaceSettings.parse({});
@@ -23813,12 +24112,18 @@ function toCaptureAttributes(event) {
23813
24112
  ...metadata?.traceId !== void 0 ? { trace_id: metadata.traceId } : {},
23814
24113
  ...metadata?.exceptionIds !== void 0 ? { exception_ids: metadata.exceptionIds } : {},
23815
24114
  ...metadata?.inspectionMs !== void 0 ? { inspection_ms: metadata.inspectionMs } : {},
24115
+ ...metadata?.redactDegradedTo !== void 0 ? { redact_degraded_to: metadata.redactDegradedTo } : {},
23816
24116
  // `model`/`turnIndex` have no dedicated CaptureAttributes field (no writer
23817
24117
  // has ever populated either), but every legacy metadata key still rides
23818
24118
  // the bag rather than being silently dropped — CaptureAttributes'
23819
24119
  // `.catchall(z.unknown())` carries the long tail.
23820
24120
  ...metadata?.model !== void 0 ? { model: metadata.model } : {},
23821
- ...metadata?.turnIndex !== void 0 ? { turn_index: metadata.turnIndex } : {}
24121
+ ...metadata?.turnIndex !== void 0 ? { turn_index: metadata.turnIndex } : {},
24122
+ // A blank id is omitted rather than stored: it is a join key and `''` joins
24123
+ // nothing. This runs on the local write path, which types the event but
24124
+ // never parses it, so EventMetadata's own `.min(1)` does not reach here.
24125
+ ...metadata?.messageId !== void 0 && metadata.messageId !== "" ? { message_id: metadata.messageId } : {},
24126
+ ...metadata?.conversationId !== void 0 ? { conversation_id: metadata.conversationId } : {}
23822
24127
  };
23823
24128
  }
23824
24129
  function captureDefinitionVersion(finding) {
@@ -23846,13 +24151,22 @@ var ManagedSettingKey = external_exports.enum([
23846
24151
  "vaultInlineReveal",
23847
24152
  "modelJudgeConsent",
23848
24153
  "dataSharesInPlace",
23849
- "redactFallback"
24154
+ "redactFallback",
24155
+ // Pins the toggle and the day count together — see BodyRetention on why the
24156
+ // two are one unit. An administrator mandating a window wants the count
24157
+ // enforced with it, not one a user can widen while the toggle stays on.
24158
+ "bodyRetention"
23850
24159
  ]).meta({ id: "ManagedSettingKey" });
23851
24160
  function isManagedSettingKey(value) {
23852
24161
  return ManagedSettingKey.safeParse(value).success;
23853
24162
  }
23854
24163
  var ManagedSettingsValues = external_exports.object({
23855
24164
  runMode: external_exports.enum(["standalone", "attached"]).optional(),
24165
+ // `controlPlane` and `bodyRetention` are the two nested values, and both are
24166
+ // plain, non-strict objects: a key under either that this build does not know
24167
+ // is stripped and nothing reports it. The unknown-value split in
24168
+ // ManagedSettings below classifies top-level names only, so it stops at
24169
+ // these boundaries.
23856
24170
  controlPlane: external_exports.object({
23857
24171
  endpoint: external_exports.string().min(1),
23858
24172
  label: external_exports.string().min(1).optional()
@@ -23863,7 +24177,8 @@ var ManagedSettingsValues = external_exports.object({
23863
24177
  vaultInlineReveal: external_exports.enum(["masked", "full", "off"]).optional(),
23864
24178
  modelJudgeConsent: external_exports.boolean().optional(),
23865
24179
  dataSharesInPlace: external_exports.boolean().optional(),
23866
- redactFallback: RedactFallback.optional()
24180
+ redactFallback: RedactFallback.optional(),
24181
+ bodyRetention: BodyRetention.optional()
23867
24182
  }).meta({ id: "ManagedSettingsValues" });
23868
24183
  var ManagedSettings = external_exports.object({
23869
24184
  specVersion: external_exports.number().int().positive().default(MANAGED_SETTINGS_SPEC_VERSION),
@@ -23871,7 +24186,21 @@ var ManagedSettings = external_exports.object({
23871
24186
  // decision from a bug. Absent renders as a generic "your organization".
23872
24187
  organization: external_exports.string().min(1).optional(),
23873
24188
  // What the administrator pinned.
23874
- values: ManagedSettingsValues.default({}),
24189
+ //
24190
+ // Parsed as a RECORD rather than as the nested schema, and split below for
24191
+ // the same reason `lockedFields` is parsed as names: a plain `z.object`
24192
+ // drops an unrecognised key and succeeds, so a pin this build does not know
24193
+ // vanished and nothing anywhere said so. A pin with no lock is a supported
24194
+ // shape — it is a DEFAULT the user may still change — so that silence hit
24195
+ // exactly the file an administrator is most likely to write while a fleet
24196
+ // is mid-upgrade.
24197
+ //
24198
+ // Splitting here rather than calling `.strict()`: strict would REFUSE the
24199
+ // file, which is the outcome the lock half already rejected — an older
24200
+ // build then runs entirely unmanaged, every pin and lock gone. A bad KNOWN
24201
+ // value still fails, because the nested schema is re-run over the known
24202
+ // subset and its issues are re-raised on this parse.
24203
+ values: external_exports.record(external_exports.string(), external_exports.unknown()).default({}),
23875
24204
  // Which of those the user may not change. A key here with no matching value
23876
24205
  // freezes whatever the user last chose; a value with no lock is a DEFAULT
23877
24206
  // the user may still override. The two are separable on purpose.
@@ -23884,17 +24213,31 @@ var ManagedSettings = external_exports.object({
23884
24213
  // the fleets most likely to carry a version skew. A name outside the enum
23885
24214
  // is still never HONOURED: the lockable set stays explicit above.
23886
24215
  lockedFields: external_exports.array(external_exports.string()).default([])
23887
- }).transform(({ lockedFields, ...rest }) => {
24216
+ }).transform(({ lockedFields, values, ...rest }, ctx) => {
23888
24217
  const known = [];
23889
24218
  const unknown2 = [];
23890
24219
  for (const name of lockedFields) {
23891
24220
  if (isManagedSettingKey(name)) known.push(name);
23892
24221
  else unknown2.push(name);
23893
24222
  }
24223
+ const knownValues = /* @__PURE__ */ Object.create(null);
24224
+ const unknownValues = [];
24225
+ for (const [name, value] of Object.entries(values)) {
24226
+ if (Object.hasOwn(ManagedSettingsValues.shape, name)) knownValues[name] = value;
24227
+ else unknownValues.push(name);
24228
+ }
24229
+ const pinned = ManagedSettingsValues.safeParse(knownValues);
24230
+ if (!pinned.success) {
24231
+ for (const issue2 of pinned.error.issues)
24232
+ ctx.addIssue({ ...issue2, path: ["values", ...issue2.path] });
24233
+ return external_exports.NEVER;
24234
+ }
23894
24235
  return {
23895
24236
  ...rest,
24237
+ values: pinned.data,
23896
24238
  lockedFields: known,
23897
- ...unknown2.length > 0 ? { unknownLockedFields: unknown2 } : {}
24239
+ ...unknown2.length > 0 ? { unknownLockedFields: unknown2 } : {},
24240
+ ...unknownValues.length > 0 ? { unknownValueFields: unknownValues } : {}
23898
24241
  };
23899
24242
  }).meta({ id: "ManagedSettings" });
23900
24243
 
@@ -24153,12 +24496,30 @@ var RecommendedActionIdParam = external_exports.object({ id: external_exports.st
24153
24496
  // ../../packages/schema/src/zod/settings-action.ts
24154
24497
  var HistorySyncConsentChoice = external_exports.enum(["granted", "revoked", "unchanged"]).meta({ id: "HistorySyncConsentChoice" });
24155
24498
  var ModelJudgeConsentChoice = external_exports.enum(["granted", "revoked", "unchanged"]).meta({ id: "ModelJudgeConsentChoice" });
24499
+ var WebChatCaptureConsentChoice = external_exports.enum(["granted", "revoked", "unchanged"]).meta({ id: "WebChatCaptureConsentChoice" });
24156
24500
  var SaveSettingsInput = external_exports.object({
24157
24501
  historicalAccess: external_exports.string(),
24158
24502
  modelJudgeConsent: ModelJudgeConsentChoice,
24159
24503
  historySyncConsent: HistorySyncConsentChoice,
24160
24504
  vaultConsent: external_exports.string(),
24161
- vaultInlineReveal: external_exports.string()
24505
+ vaultInlineReveal: external_exports.string(),
24506
+ webChatCaptureConsent: WebChatCaptureConsentChoice,
24507
+ // Widened to `string` like its neighbours rather than typed as
24508
+ // `RedactFallback`, on this module's own layering rule: shape here, VALUE at
24509
+ // the call site, so the domain check receives the type it was written for.
24510
+ //
24511
+ // NOT because a narrower schema would reject differently. `parseActionInput`
24512
+ // is a `safeParse` wrapper and throws for no field schema, so either spelling
24513
+ // reaches a recoverable `{ ok: false }` and there is no rejected promise to
24514
+ // trade against. The real cost runs the other way and is the part worth
24515
+ // knowing: a value this schema admits and the domain enum then rejects lands
24516
+ // on the action's shared refusal, which names NO field, where a shape
24517
+ // rejection reaches `malformedInput` and names the schema key.
24518
+ redactFallback: external_exports.string(),
24519
+ // Shape only, the way the enum fields above are strings only: the RANGE is
24520
+ // `BodyRetention`'s and the action checks it there, so there is one place
24521
+ // that decides what a legal horizon is rather than two that can drift.
24522
+ bodyRetention: external_exports.object({ enabled: external_exports.boolean(), retainDays: external_exports.number() })
24162
24523
  });
24163
24524
  var AttachInput = external_exports.object({
24164
24525
  endpoint: external_exports.string(),
@@ -24330,6 +24691,123 @@ function reviewSeverityRank(reasons) {
24330
24691
  return Math.min(...reasons.map((r) => REVIEW_SEVERITY_RANK[r]));
24331
24692
  }
24332
24693
 
24694
+ // ../../packages/schema/src/zod/web-capture.ts
24695
+ var WebUsageSource = external_exports.enum(["site", "estimated", "none"]);
24696
+ var WebUsage = external_exports.object({
24697
+ inputTokens: external_exports.number().int().nonnegative().optional(),
24698
+ outputTokens: external_exports.number().int().nonnegative().optional(),
24699
+ cacheReadInputTokens: external_exports.number().int().nonnegative().optional(),
24700
+ cacheCreationInputTokens: external_exports.number().int().nonnegative().optional()
24701
+ });
24702
+ var WebToolCall = external_exports.object({
24703
+ toolUseId: external_exports.string().min(1),
24704
+ toolName: external_exports.string().min(1),
24705
+ target: external_exports.string().optional(),
24706
+ isError: external_exports.boolean().optional(),
24707
+ inputSize: external_exports.number().int().nonnegative().optional(),
24708
+ outputSize: external_exports.number().int().nonnegative().optional()
24709
+ });
24710
+ var WebExchange = external_exports.object({
24711
+ messageId: external_exports.string().min(1),
24712
+ startedAt: external_exports.iso.datetime(),
24713
+ model: external_exports.string().optional(),
24714
+ usage: WebUsage.optional(),
24715
+ usageSource: WebUsageSource,
24716
+ stopReason: external_exports.string().optional(),
24717
+ conversationId: external_exports.string().optional(),
24718
+ turnIndex: external_exports.number().int().nonnegative().optional(),
24719
+ toolCalls: external_exports.array(WebToolCall).default([]),
24720
+ // Absent when the adapter recovered no text. Capped by the caller at
24721
+ // RESPONSE_TEXT_MAX_BYTES, so a short capture is never mistaken for a short
24722
+ // reply.
24723
+ responseText: external_exports.string().optional(),
24724
+ // The stored text is short of the reply. It does NOT say which of the two
24725
+ // ceilings on this path cut it: the caller applies its own cap on the raw
24726
+ // bytes it reads off the wire, which can be reached by a stream whose
24727
+ // recovered text stays well under RESPONSE_TEXT_MAX_BYTES, and applies that
24728
+ // one to the text. A reader cannot tell them apart, and nothing downstream
24729
+ // should branch as though it could.
24730
+ truncated: external_exports.boolean().default(false)
24731
+ });
24732
+ var WebEnforcementState = external_exports.enum([
24733
+ "watching",
24734
+ "composer-only",
24735
+ "button-only",
24736
+ "unattached",
24737
+ "unknown"
24738
+ ]);
24739
+ var RESPONSE_TEXT_MAX_BYTES = 2 * 1024 * 1024;
24740
+ var WebCaptureStatus = external_exports.object({
24741
+ patched: external_exports.boolean(),
24742
+ live: external_exports.boolean(),
24743
+ blind: external_exports.boolean(),
24744
+ sendsSeenDom: external_exports.number().int().nonnegative(),
24745
+ exchangesSeenNet: external_exports.number().int().nonnegative(),
24746
+ parseFailures: external_exports.number().int().nonnegative(),
24747
+ unparsedBodies: external_exports.number().int().nonnegative(),
24748
+ // The adapter-declared JSON key paths that were absent from a real payload —
24749
+ // the earliest signal that a site's contract moved.
24750
+ shapeMisses: external_exports.array(external_exports.string()).default([]),
24751
+ // How many `kind: 'conversation'` endpoints the reporting tab's adapter
24752
+ // compiled. Zero means this build declares none for the site, so observing
24753
+ // nothing is the design rather than a fault — the one fact that separates a
24754
+ // site nobody has surveyed yet from one whose contract moved. Defaulted so a
24755
+ // build predating the field is read as declaring nothing rather than refused.
24756
+ conversationEndpoints: external_exports.number().int().nonnegative().default(0),
24757
+ // The document that sent this report is going away. The bridge sets it on
24758
+ // its `pagehide` report and nowhere else.
24759
+ //
24760
+ // A property of the REPORT rather than of capture health, which is why
24761
+ // nothing in `deriveWebCaptureState` reads it and why it stays out of the
24762
+ // bridge's own report signature — a closing tab's last word must not be
24763
+ // suppressed for carrying the same health as the report before it. What
24764
+ // reads it is the per-site fold: a document that said it was unloading stops
24765
+ // voting on the site's state, so the reload the `blind` remediation asks for
24766
+ // can actually clear the verdict it was shown. A document that dies without
24767
+ // sending one is covered by CAPTURE_STATUS_DOCUMENT_QUIET_MS instead.
24768
+ //
24769
+ // Defaulted so a build predating the field reads as a document that never
24770
+ // said it was closing — which keeps it voting, the same as every report that
24771
+ // is not a final one.
24772
+ closed: external_exports.boolean().default(false),
24773
+ // What the DOM enforcement path is doing, which none of the counters above
24774
+ // can say: `sendsSeenDom` rises only once a send has COMPLETED, so a tab
24775
+ // whose watcher never bound reports zero exactly like a tab nobody typed in.
24776
+ // Defaulted to 'unknown' rather than 'watching' so a status from a build
24777
+ // predating the field is not read as reporting a healthy one.
24778
+ enforcement: WebEnforcementState.default("unknown")
24779
+ });
24780
+ function webCaptureStatusObservedTurnPath(status) {
24781
+ if (!status.patched) return true;
24782
+ if (status.conversationEndpoints === 0) return true;
24783
+ return status.blind || status.shapeMisses.length > 0 || status.parseFailures > 0 || status.unparsedBodies > 0 || status.exchangesSeenNet > 0;
24784
+ }
24785
+ function pickReportedCaptureStatus(candidates) {
24786
+ return candidates.find((c) => webCaptureStatusObservedTurnPath(c.status)) ?? candidates[0];
24787
+ }
24788
+ var CAPTURE_STATUS_RECENCY_MS = 30 * 24 * 60 * 60 * 1e3;
24789
+ var CAPTURE_STATUS_RECENCY_DAYS = CAPTURE_STATUS_RECENCY_MS / (24 * 60 * 60 * 1e3);
24790
+ var CAPTURE_STATUS_DOCUMENT_QUIET_MS = 12 * 60 * 60 * 1e3;
24791
+ function fromCaptureStatusAttributes(bag) {
24792
+ const parsedBag = CaptureStatusAttributes.safeParse(bag);
24793
+ if (!parsedBag.success) return null;
24794
+ const b = parsedBag.data;
24795
+ const parsedStatus = WebCaptureStatus.safeParse({
24796
+ patched: b.patched,
24797
+ live: b.live,
24798
+ blind: b.blind,
24799
+ sendsSeenDom: b.sends_seen_dom,
24800
+ exchangesSeenNet: b.exchanges_seen_net,
24801
+ parseFailures: b.parse_failures,
24802
+ unparsedBodies: b.unparsed_bodies,
24803
+ shapeMisses: b.shape_misses,
24804
+ conversationEndpoints: b.conversation_endpoints,
24805
+ closed: b.closed,
24806
+ enforcement: b.enforcement
24807
+ });
24808
+ return parsedStatus.success ? parsedStatus.data : null;
24809
+ }
24810
+
24333
24811
  // ../../packages/persistence/src/paths.ts
24334
24812
  import {
24335
24813
  chmodSync,
@@ -24599,6 +25077,22 @@ function discardStore(file2, backup) {
24599
25077
  }
24600
25078
  }
24601
25079
 
25080
+ // ../../packages/persistence/src/internal/sql-functions.ts
25081
+ var utf8 = new TextDecoder();
25082
+ function akaLower(value) {
25083
+ if (value === null) return null;
25084
+ if (typeof value === "string") return value.toLowerCase();
25085
+ if (typeof value === "number" || typeof value === "bigint") return String(value).toLowerCase();
25086
+ return utf8.decode(value).toLowerCase();
25087
+ }
25088
+ function registerSqlFunctions(db) {
25089
+ db.function(
25090
+ "aka_lower",
25091
+ { deterministic: true, directOnly: true, useBigIntArguments: true },
25092
+ akaLower
25093
+ );
25094
+ }
25095
+
24602
25096
  // ../../packages/persistence/src/internal/sql-text.ts
24603
25097
  function escapeLikePattern(s) {
24604
25098
  return s.replace(/\\/g, "\\\\").replace(/%/g, "\\%").replace(/_/g, "\\_");
@@ -24683,6 +25177,11 @@ function schemaObjectExists(db, kind, name) {
24683
25177
  function indexExists(db, name) {
24684
25178
  return schemaObjectExists(db, "index", name);
24685
25179
  }
25180
+ function indexColumns(db, name) {
25181
+ if (!indexExists(db, name)) return [];
25182
+ const columns = db.prepare(`PRAGMA index_info(${name})`).all();
25183
+ return columns.map((c) => c.name).filter((c) => c !== null);
25184
+ }
24686
25185
  function columnNames(db, table, opts) {
24687
25186
  const pragma = opts?.includeGenerated ? "table_xinfo" : "table_info";
24688
25187
  const columns = db.prepare(`PRAGMA ${pragma}(${table})`).all();
@@ -24744,160 +25243,802 @@ function mapRowsTolerant(rows, map2) {
24744
25243
  return out;
24745
25244
  }
24746
25245
 
24747
- // ../../packages/persistence/src/migrations.ts
24748
- function describeObject(object2) {
24749
- return object2.kind === "column" ? `column ${object2.table}.${object2.name}` : `table ${object2.name}`;
24750
- }
24751
- function splitStatements(sql) {
24752
- return sql.split(/-->\s*statement-breakpoint/).map((s) => s.trim()).filter((s) => s.length > 0);
24753
- }
24754
- function createdIndexName(statement) {
24755
- const body = statement.replace(/^(?:\s*--[^\n]*\n?)+/, "").trimStart();
24756
- return /^CREATE (?:UNIQUE )?INDEX (?:IF NOT EXISTS )?`([^`]+)`/.exec(body)?.[1];
25246
+ // ../../packages/persistence/src/internal/outbox-lane.ts
25247
+ var OUTBOX_CAPTURE_EVENT_TYPES = ["prompt", "response", "tool_use"];
25248
+ var OUTBOX_CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25249
+
25250
+ // ../../packages/persistence/src/sync-failure.ts
25251
+ var SYNC_FAILURE_REASONS = SyncFailureReason.options;
25252
+ function syncFailureRejectCondition(column = "sync_failure") {
25253
+ const members2 = SYNC_FAILURE_REASONS.map((r) => `'${r}'`).join(", ");
25254
+ return `NEW.${column} IS NOT NULL AND NEW.${column} NOT IN (${members2})`;
24757
25255
  }
24758
- var LEGACY_DROP_MIGRATION_TAG = "0014_drop_legacy_events_findings";
24759
- function applyMigrations(db, file2) {
24760
- const legacyCount = db.prepare("PRAGMA user_version").get().user_version;
24761
- db.exec(
24762
- "CREATE TABLE IF NOT EXISTS migration_ledger (tag TEXT PRIMARY KEY, applied_at INTEGER NOT NULL)"
24763
- );
24764
- const applied = new Set(
24765
- db.prepare("SELECT tag FROM migration_ledger").all().map((r) => r.tag)
24766
- );
24767
- const preLedgerStore = applied.size === 0 && legacyCount > 0;
24768
- const record2 = db.prepare(
24769
- "INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)"
24770
- );
24771
- for (const [index, migration] of SQLITE_MIGRATIONS.entries()) {
24772
- if (applied.has(migration.tag)) continue;
24773
- if (migration.tag === LEGACY_DROP_MIGRATION_TAG) continue;
24774
- const evidence = evidenceObjects(migration.sql);
24775
- const present = evidence.filter((o) => evidenceExists(db, o));
24776
- if (present.length > 0 && present.length < evidence.length) {
24777
- const missing = evidence.filter((o) => !present.includes(o));
24778
- const message = `sqlite migration ${migration.tag} has no ledger row, but the store already has ${present.map(describeObject).join(", ")} while missing ${missing.map(describeObject).join(", ")} \u2014 the schema diverged from the migration history; refusing to replay or skip.`;
24779
- akaWarn(message);
24780
- throw new Error(`[aka] ${message}`);
24781
- }
24782
- const alreadyApplied = evidence.length > 0 ? present.length === evidence.length : preLedgerStore && index < legacyCount;
24783
- const wantsFkOff = /PRAGMA foreign_keys\s*=\s*OFF/i.test(migration.sql);
24784
- const statements = splitStatements(migration.sql);
24785
- if (wantsFkOff) db.exec("PRAGMA foreign_keys = OFF");
24786
- try {
24787
- withTransaction(
24788
- db,
24789
- () => {
24790
- for (const statement of statements) {
24791
- const indexName = createdIndexName(statement);
24792
- if (indexName === void 0) {
24793
- if (alreadyApplied) continue;
24794
- } else if (indexExists(db, indexName)) {
24795
- continue;
24796
- }
24797
- db.exec(statement);
24798
- }
24799
- if (wantsFkOff && !alreadyApplied) {
24800
- const violations = db.prepare("PRAGMA foreign_key_check").all();
24801
- if (violations.length > 0) {
24802
- throw new Error(
24803
- `[aka] sqlite migration ${migration.tag} left ${String(violations.length)} foreign-key violation(s); rolling back.`
24804
- );
24805
- }
24806
- }
24807
- record2.run(migration.tag, Date.now());
24808
- },
24809
- "IMMEDIATE"
24810
- );
24811
- } finally {
24812
- if (wantsFkOff) db.exec("PRAGMA foreign_keys = ON");
24813
- }
25256
+
25257
+ // ../../packages/persistence/src/repositories/history-sync.ts
25258
+ var STRUCTURAL_EVENT_TYPES = ["session", "llm_call", "tool_call"];
25259
+ var TYPE_LIST = STRUCTURAL_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25260
+ var CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_TYPE_LIST;
25261
+ var COUNTED_EVENT_TYPES = [
25262
+ ...STRUCTURAL_EVENT_TYPES,
25263
+ ...OUTBOX_CAPTURE_EVENT_TYPES
25264
+ ];
25265
+ var COUNTED_TYPE_LIST = COUNTED_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25266
+ var PARTITION_BUCKETS = `
25267
+ SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NULL THEN 1 ELSE 0 END) AS queued,
25268
+ SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NOT NULL THEN 1 ELSE 0 END) AS inProgress,
25269
+ SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS synced,
25270
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25271
+ AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
25272
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25273
+ AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached,
25274
+ -- Spelled as what it INCLUDES rather than what it excludes, so a reason
25275
+ -- added later lands in no bucket and fails the sum assertion, instead
25276
+ -- of silently joining this one.
25277
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25278
+ AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
25279
+ THEN 1 ELSE 0 END) AS failed,
25280
+ COUNT(*) AS total`;
25281
+ var COUNTED_SCOPE = `
25282
+ WHERE event_type IN (${COUNTED_TYPE_LIST})
25283
+ AND (
25284
+ event_type IN (${TYPE_LIST})
25285
+ OR synced_at IS NOT NULL
25286
+ OR outbox_owed = 1
25287
+ )`;
25288
+ var SKIPPED = -1;
25289
+ var ROW_COLUMNS = `id,
25290
+ parent_id AS parentId,
25291
+ root_session_id AS rootSessionId,
25292
+ event_type AS eventType,
25293
+ host_id AS hostId,
25294
+ harness_id AS harnessId,
25295
+ source_project_id AS sourceProjectId,
25296
+ started_at AS startedAt,
25297
+ ended_at AS endedAt,
25298
+ severity,
25299
+ priority,
25300
+ content,
25301
+ content_hash AS contentHash,
25302
+ attributes`;
25303
+ var SqliteHistorySyncRepository = class {
25304
+ constructor(db) {
25305
+ this.db = db;
25306
+ this.ensureRowStmt = db.prepare(`INSERT OR IGNORE INTO history_sync (id) VALUES (1)`);
25307
+ this.sessionsStmt = db.prepare(
25308
+ `SELECT COALESCE(root_session_id, id) AS sessionId, MIN(started_at) AS earliest
25309
+ FROM audit_events
25310
+ WHERE synced_at IS NULL
25311
+ AND event_type IN (${TYPE_LIST})
25312
+ AND started_at < :before
25313
+ GROUP BY sessionId
25314
+ ORDER BY earliest
25315
+ LIMIT :limit`
25316
+ );
25317
+ this.rowsStmt = db.prepare(
25318
+ `SELECT ${ROW_COLUMNS}
25319
+ FROM audit_events
25320
+ WHERE synced_at IS NULL
25321
+ AND event_type IN (${TYPE_LIST})
25322
+ AND started_at < :before
25323
+ AND COALESCE(root_session_id, id) = :sessionId
25324
+ ORDER BY (event_type = 'session') DESC, started_at
25325
+ LIMIT :limit`
25326
+ );
25327
+ this.captureRowsStmt = db.prepare(
25328
+ `SELECT ${ROW_COLUMNS}
25329
+ FROM audit_events
25330
+ WHERE synced_at IS NULL
25331
+ AND sync_claimed_at IS NULL
25332
+ AND outbox_owed = 1
25333
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25334
+ AND started_at < :before
25335
+ ORDER BY started_at
25336
+ LIMIT :limit`
25337
+ );
25338
+ this.markOwedStmt = db.prepare(
25339
+ `UPDATE audit_events SET outbox_owed = 1 WHERE id = :id AND synced_at IS NULL`
25340
+ );
25341
+ this.markCaptureBacklogOwedStmt = db.prepare(
25342
+ `UPDATE audit_events SET outbox_owed = 1
25343
+ WHERE synced_at IS NULL
25344
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25345
+ AND started_at < :before`
25346
+ );
25347
+ this.stampStmt = db.prepare(
25348
+ `UPDATE audit_events
25349
+ SET synced_at = :at,
25350
+ sync_claimed_at = NULL,
25351
+ sync_failed_at = :failedAt,
25352
+ sync_failure = :failure
25353
+ WHERE id = :id`
25354
+ );
25355
+ this.claimRowStmt = db.prepare(
25356
+ `UPDATE audit_events SET sync_claimed_at = :at WHERE id = :id AND synced_at IS NULL`
25357
+ );
25358
+ this.releaseRowStmt = db.prepare(
25359
+ `UPDATE audit_events SET sync_claimed_at = NULL WHERE id = :id`
25360
+ );
25361
+ this.releaseStaleClaimsStmt = db.prepare(
25362
+ `UPDATE audit_events SET sync_claimed_at = NULL
25363
+ WHERE sync_claimed_at IS NOT NULL AND sync_claimed_at < :staleBefore`
25364
+ );
25365
+ this.partitionStmt = db.prepare(`SELECT${PARTITION_BUCKETS}
25366
+ FROM audit_events${COUNTED_SCOPE}`);
25367
+ this.partitionByKindStmt = db.prepare(
25368
+ `SELECT event_type AS kind,${PARTITION_BUCKETS}
25369
+ FROM audit_events INDEXED BY idx_audit_events_sync${COUNTED_SCOPE}
25370
+ GROUP BY event_type`
25371
+ );
25372
+ this.countsStmt = db.prepare(
25373
+ `SELECT
25374
+ SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
25375
+ SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
25376
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25377
+ AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
25378
+ THEN 1 ELSE 0 END) AS skipped,
25379
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25380
+ AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
25381
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25382
+ AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached
25383
+ FROM audit_events
25384
+ WHERE event_type IN (${TYPE_LIST})`
25385
+ );
25386
+ this.captureSkipCountStmt = db.prepare(
25387
+ // EVERY sentinel capture, whatever the reason — deliberately NOT split the
25388
+ // way the structural totals are. The split exists because a refusal is
25389
+ // terminal only against the deployment that gave it, and the structural
25390
+ // re-arm frees it on a change of deployment. The capture lane has no such
25391
+ // escape: re-arming a capture would offer one deployment's undelivered
25392
+ // prompts, with their text, to a deployment that never saw them, which is
25393
+ // exactly what disownCapturesStmt exists to prevent. So on this lane both
25394
+ // reasons mean the same thing — this row will not be sent — and splitting
25395
+ // them would put refused captures in a bucket nothing reads and nothing
25396
+ // frees.
25397
+ `SELECT COUNT(*) AS skipped
25398
+ FROM audit_events
25399
+ WHERE synced_at = ${String(SKIPPED)}
25400
+ AND event_type IN (${CAPTURE_TYPE_LIST})`
25401
+ );
25402
+ this.fingerprintStmt = db.prepare(
25403
+ `SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
25404
+ FROM history_sync WHERE id = 1`
25405
+ );
25406
+ this.setFingerprintStmt = db.prepare(
25407
+ `UPDATE history_sync
25408
+ SET endpoint_fingerprint = :fingerprint, backlog_before = :backlogBefore
25409
+ WHERE id = 1`
25410
+ );
25411
+ this.disownCapturesStmt = db.prepare(
25412
+ `UPDATE audit_events SET outbox_owed = NULL
25413
+ WHERE outbox_owed IS NOT NULL
25414
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25415
+ AND started_at < :attachedAt`
25416
+ );
25417
+ this.rearmStmt = db.prepare(
25418
+ `UPDATE audit_events
25419
+ SET synced_at = NULL, sync_failed_at = NULL, sync_failure = NULL
25420
+ WHERE (synced_at > 0
25421
+ OR sync_failure IN ('deployment_refused', 'detached_undelivered'))
25422
+ AND event_type IN (${TYPE_LIST})`
25423
+ );
25424
+ this.claimStmt = db.prepare(
25425
+ `UPDATE history_sync
25426
+ SET owner_pid = :pid, owner_host = :host, acquired_at = :now, heartbeat_at = :now
25427
+ WHERE id = 1
25428
+ AND (owner_pid IS NULL
25429
+ OR heartbeat_at IS NULL
25430
+ OR heartbeat_at < :staleBefore
25431
+ OR heartbeat_at > :now)`
25432
+ );
25433
+ this.heartbeatStmt = db.prepare(
25434
+ `UPDATE history_sync SET heartbeat_at = :now WHERE id = 1 AND owner_pid = :pid`
25435
+ );
25436
+ this.releaseStmt = db.prepare(
25437
+ `UPDATE history_sync
25438
+ SET owner_pid = NULL, owner_host = NULL, acquired_at = NULL, heartbeat_at = NULL
25439
+ WHERE id = 1 AND owner_pid = :pid`
25440
+ );
25441
+ this.closeWindowStmt = db.prepare(
25442
+ `UPDATE audit_events
25443
+ SET synced_at = ${String(SKIPPED)},
25444
+ sync_failed_at = :at,
25445
+ sync_failure = 'detached_undelivered'
25446
+ WHERE synced_at IS NULL
25447
+ AND event_type IN (${TYPE_LIST})
25448
+ AND started_at >= :attachedAt`
25449
+ );
25450
+ this.releaseBoundaryStmt = db.prepare(
25451
+ `UPDATE history_sync SET backlog_before = NULL WHERE id = 1`
25452
+ );
25453
+ this.freezeBoundaryStmt = db.prepare(
25454
+ `UPDATE history_sync SET backlog_before = :backlogBefore WHERE id = 1`
25455
+ );
25456
+ this.leaseStmt = db.prepare(
25457
+ `SELECT owner_pid AS ownerPid, owner_host AS ownerHost,
25458
+ acquired_at AS acquiredAt, heartbeat_at AS heartbeatAt
25459
+ FROM history_sync WHERE id = 1`
25460
+ );
25461
+ this.inspectionsStmt = db.prepare(
25462
+ `SELECT d.rule_id AS ruleId,
25463
+ d.name AS ruleName,
25464
+ d.version AS ruleVersion,
25465
+ d.category AS category,
25466
+ d.severity AS severity,
25467
+ f.span_start AS spanStart,
25468
+ f.span_end AS spanEnd,
25469
+ f.masked_match AS maskedMatch,
25470
+ f.action_taken AS actionTaken,
25471
+ f.confidence AS confidence
25472
+ FROM inspection_findings f
25473
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
25474
+ WHERE f.audit_event_id = :auditEventId
25475
+ ORDER BY f.span_start, f.id`
25476
+ );
24814
25477
  }
24815
- if (legacyCount < SQLITE_MIGRATIONS.length) {
24816
- db.exec(`PRAGMA user_version = ${String(SQLITE_MIGRATIONS.length)}`);
25478
+ db;
25479
+ ensureRowStmt;
25480
+ sessionsStmt;
25481
+ rowsStmt;
25482
+ stampStmt;
25483
+ countsStmt;
25484
+ fingerprintStmt;
25485
+ setFingerprintStmt;
25486
+ rearmStmt;
25487
+ claimStmt;
25488
+ heartbeatStmt;
25489
+ releaseStmt;
25490
+ leaseStmt;
25491
+ inspectionsStmt;
25492
+ closeWindowStmt;
25493
+ releaseBoundaryStmt;
25494
+ freezeBoundaryStmt;
25495
+ captureRowsStmt;
25496
+ markOwedStmt;
25497
+ markCaptureBacklogOwedStmt;
25498
+ captureSkipCountStmt;
25499
+ disownCapturesStmt;
25500
+ partitionStmt;
25501
+ partitionByKindStmt;
25502
+ claimRowStmt;
25503
+ releaseRowStmt;
25504
+ releaseStaleClaimsStmt;
25505
+ /**
25506
+ * The masked detections recorded against one tool call.
25507
+ *
25508
+ * These travel with the event because a tool call's target is not
25509
+ * re-inspectable from the event alone — unlike a capture, where the text
25510
+ * itself is re-scannable. What crosses is the masked match and the rule that
25511
+ * produced it, never the value.
25512
+ */
25513
+ inspectionsFor(auditEventId) {
25514
+ return allRows(this.inspectionsStmt, { auditEventId });
24817
25515
  }
24818
- ensureSyncedAtColumn(db, "audit_events");
24819
- ensureScanLedgerTable(db);
24820
- ensureHistorySyncTable(db);
24821
- ensureBlockedDetectionsTable(db);
24822
- ensureRuleProbeCacheTable(db);
24823
- ensureWriteGateTrigger(db);
24824
- ensureTokenUsageColumns(db);
24825
- reconcileSourceProjectIds(db);
24826
- if (!applied.has(LEGACY_DROP_MIGRATION_TAG)) {
24827
- const drained = runLegacyHistoryBackfill(db);
24828
- if (drained) applyLegacyDropMigration(db, file2);
25516
+ /**
25517
+ * Sessions with structural rows still to send, oldest first.
25518
+ *
25519
+ * BOUNDED BY THE BACKLOG BOUNDARY, which is the whole correctness of this
25520
+ * read. Anything recorded after the machine attached is the live forward
25521
+ * path's to deliver; this drain exists for what was recorded before it, and a
25522
+ * row both paths send is at best a duplicate request and at worst — for a
25523
+ * session root — an overwrite of the inventory ids the live path resolved.
25524
+ */
25525
+ pendingSessions(limit, before) {
25526
+ return allRows(this.sessionsStmt, { limit, before }).map(
25527
+ (r) => r.sessionId
25528
+ );
24829
25529
  }
24830
- }
24831
- function readLegacyTables(db) {
24832
- let holdsRows = false;
24833
- const marks = [];
24834
- for (const table of ["events", "findings"]) {
24835
- try {
24836
- const row = db.prepare(`SELECT count(*) AS n, ifnull(max(rowid), -1) AS hi FROM ${table}`).get();
24837
- if (row === void 0) {
24838
- holdsRows = true;
24839
- marks.push(`${table}:unreadable`);
24840
- continue;
24841
- }
24842
- if (row.n > 0) holdsRows = true;
24843
- marks.push(`${table}:${String(row.n)}:${String(row.hi)}`);
24844
- } catch {
24845
- holdsRows = true;
24846
- marks.push(`${table}:unreadable`);
24847
- }
25530
+ /** One session's undelivered structural rows within the backlog, root first. */
25531
+ pendingRows(sessionId, limit, before) {
25532
+ return allRows(this.rowsStmt, { sessionId, limit, before });
24848
25533
  }
24849
- return { holdsRows, mark: marks.join("|") };
24850
- }
24851
- function applyLegacyDropMigration(db, file2) {
24852
- const migration = SQLITE_MIGRATIONS.find((m) => m.tag === LEGACY_DROP_MIGRATION_TAG);
24853
- if (!migration) return;
24854
- const before = file2 === void 0 ? void 0 : readLegacyTables(db);
24855
- if (file2 !== void 0 && before?.holdsRows === true) {
24856
- try {
24857
- backupBeforeLegacyDrop(db, file2);
24858
- } catch (error61) {
24859
- akaWarn(`legacy events/findings backup failed; deferring the drop: ${String(error61)}`);
24860
- return;
24861
- }
25534
+ /**
25535
+ * Captures this machine still owes the deployment, oldest first.
25536
+ *
25537
+ * Selected by the `outbox_owed` marker the attached forward path writes, not
25538
+ * by a time window — see captureRowsStmt for why a window could not express
25539
+ * this. `before` is the grace window that leaves a just-recorded capture to
25540
+ * the live path.
25541
+ */
25542
+ pendingCaptureRows(limit, before) {
25543
+ return allRows(this.captureRowsStmt, { limit, before });
24862
25544
  }
24863
- try {
25545
+ /**
25546
+ * Record that a capture is OWED to the deployment.
25547
+ *
25548
+ * Written by the attached forward path when a live send did not confirm
25549
+ * delivery, and read by the drain as the whole of its eligibility test. It is
25550
+ * a fact rather than an inference: the machine was attached, the send did not
25551
+ * land, so the row is owed — which no time window can state, because the same
25552
+ * window that holds the rows a past attachment left owed also holds every
25553
+ * capture recorded while the machine was DETACHED, and those were never
25554
+ * offered to anyone.
25555
+ *
25556
+ * Idempotent, and never un-set: `markSynced` settling the row is what takes it
25557
+ * out of the drain's read.
25558
+ */
25559
+ markCaptureOwed(id) {
25560
+ this.markOwedStmt.run({ id });
25561
+ }
25562
+ /**
25563
+ * Mark every capture already on disk as owed, as of `before`.
25564
+ *
25565
+ * The consent-time backfill, called once from `aka attach` when a human
25566
+ * grants existing-history consent — never from an ongoing drain pass, and
25567
+ * never inferred from a boundary that could later move. `before` is the
25568
+ * caller's own "now" at the moment consent was granted, so what this marks
25569
+ * is exactly the backlog the consent prompt already counted, not whatever a
25570
+ * later re-attach or key rotation might widen it to.
25571
+ *
25572
+ * Returns how many rows matched, for the caller to log or test against. Not a
25573
+ * count of NEWLY marked rows — a row still unsynced from an earlier call
25574
+ * matches again and is counted again, the same as `UPDATE`'s own `changes`.
25575
+ */
25576
+ markCaptureBacklogOwed(before) {
25577
+ return Number(this.markCaptureBacklogOwedStmt.run({ before }).changes);
25578
+ }
25579
+ /**
25580
+ * Record delivery. Called only AFTER the far side has accepted the rows.
25581
+ *
25582
+ * CLEARS any failure reason in the same statement. A row that failed against
25583
+ * one deployment and then landed is delivered, and leaving the reason behind
25584
+ * would leave the store holding two contradictory answers about one row —
25585
+ * with the surface free to render either.
25586
+ */
25587
+ markSynced(ids, atMs) {
25588
+ this.stampAll(ids, atMs, null);
25589
+ }
25590
+ /**
25591
+ * Record that THIS MACHINE cannot express the row on the wire.
25592
+ *
25593
+ * Reserved for a local defect — a row that cannot be rebuilt into a valid
25594
+ * payload, or a body the client itself refused to send. It fails identically
25595
+ * against every deployment, so it is terminal everywhere and the re-arm leaves
25596
+ * it alone. A row that merely failed to REACH the deployment stays NULL, so it
25597
+ * is retried; marking those would turn one outage into permanent data loss.
25598
+ */
25599
+ markSkipped(ids, atMs) {
25600
+ this.stampAll(ids, SKIPPED, "payload_invalid", atMs);
25601
+ }
25602
+ /**
25603
+ * Record that THIS DEPLOYMENT refused the row.
25604
+ *
25605
+ * The same sentinel as `markSkipped`, and deliberately so: both stop the row
25606
+ * being re-offered on this lane, and `synced_at` goes on answering whether a
25607
+ * row is outstanding rather than why. What separates them is the reason, and
25608
+ * what the reason buys is the re-arm — a refusal is one deployment's verdict
25609
+ * on one body, so it is terminal only for as long as this machine points at
25610
+ * that deployment, and `rearmFor` clears it when the deployment changes.
25611
+ *
25612
+ * Leaving such a row NULL instead would be worse than the loss it replaces:
25613
+ * these reads carry no cursor, so an unstamped row the deployment refuses is
25614
+ * the head of every subsequent page, and the lane stalls behind it for ever.
25615
+ */
25616
+ markRefused(ids, atMs) {
25617
+ this.stampAll(ids, SKIPPED, "deployment_refused", atMs);
25618
+ }
25619
+ eachInTransaction(ids, run) {
25620
+ if (ids.length === 0) return;
24864
25621
  withTransaction(
24865
- db,
25622
+ this.db,
24866
25623
  () => {
24867
- const alreadyDropped = db.prepare("SELECT 1 FROM migration_ledger WHERE tag = ?").get(migration.tag);
24868
- if (alreadyDropped) return;
24869
- if (before !== void 0 && readLegacyTables(db).mark !== before.mark) {
24870
- akaWarn(
24871
- "legacy events/findings rows changed after the pre-drop snapshot decision; deferring the drop so the next open can copy them first."
24872
- );
24873
- return;
24874
- }
24875
- for (const statement of splitStatements(migration.sql)) {
24876
- db.exec(statement);
24877
- }
24878
- db.prepare("INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)").run(
24879
- migration.tag,
24880
- Date.now()
24881
- );
25624
+ for (const id of ids) run(id);
24882
25625
  },
24883
25626
  "IMMEDIATE"
24884
25627
  );
24885
- } catch (error61) {
24886
- akaWarn(`legacy events/findings drop failed; deferring: ${String(error61)}`);
24887
25628
  }
24888
- }
24889
- function backupBeforeLegacyDrop(db, file2) {
24890
- reapStalePartials(file2);
24891
- const backup = backupPath(file2, "pre-drop");
24892
- snapshotStore(db, backup);
24893
- return backup;
24894
- }
24895
- var TOKEN_USAGE_COLUMNS = [
24896
- {
24897
- name: "input_tokens",
24898
- ddl: "ALTER TABLE audit_events ADD COLUMN input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.input_tokens')) VIRTUAL"
24899
- },
24900
- {
25629
+ stampAll(ids, value, failure, failedAtMs) {
25630
+ if (ids.length === 0) return;
25631
+ const failedAt = failure === null ? null : failedAtMs ?? null;
25632
+ withTransaction(
25633
+ this.db,
25634
+ () => {
25635
+ for (const id of ids) this.stampStmt.run({ at: value, failedAt, failure, id });
25636
+ },
25637
+ "IMMEDIATE"
25638
+ );
25639
+ }
25640
+ /**
25641
+ * Claim rows as in-flight.
25642
+ *
25643
+ * Advisory in exactly the sense the lease is: it records that a send is in
25644
+ * progress so a surface can say so, and a lost claim costs a row showing as
25645
+ * queued while it is actually being sent. It is not exclusion — the far side
25646
+ * settles a duplicate on the row id.
25647
+ */
25648
+ claimRows(ids, atMs) {
25649
+ this.eachInTransaction(ids, (id) => this.claimRowStmt.run({ at: atMs, id }));
25650
+ }
25651
+ /** Give back a claim without settling — the send failed, the row is queued again. */
25652
+ releaseRows(ids) {
25653
+ this.eachInTransaction(ids, (id) => this.releaseRowStmt.run({ id }));
25654
+ }
25655
+ /**
25656
+ * Clear claims older than `staleBefore`, and report how many were cleared.
25657
+ *
25658
+ * A process killed between claiming and settling leaves rows claimed with
25659
+ * nothing left to settle them. Without this they read as "sending" for ever.
25660
+ */
25661
+ releaseStaleClaims(staleBefore) {
25662
+ return Number(this.releaseStaleClaimsStmt.run({ staleBefore }).changes);
25663
+ }
25664
+ /**
25665
+ * Every tracked row in exactly one delivery state.
25666
+ *
25667
+ * Takes no boundary on purpose. The boundary answers "what should the drain
25668
+ * pick up now", which is a different question from "what state is this row
25669
+ * in" — and a machine that has never attached has no boundary to pass, so
25670
+ * requiring one would force a caller to invent one and report the whole store
25671
+ * as queued.
25672
+ */
25673
+ /**
25674
+ * The same partition, one row per kind that a lane carries.
25675
+ *
25676
+ * A kind with nothing to report is ABSENT rather than a row of zeros: the
25677
+ * scope decides which rows exist at all, so a kind that has never been
25678
+ * recorded — or whose captures nobody ever owed — produces no group. A caller
25679
+ * rendering a fixed list of kinds must therefore treat a missing one as "no
25680
+ * rows", never as "zero sent"; the two look identical in a bar and mean
25681
+ * different things.
25682
+ */
25683
+ partitionByKind() {
25684
+ return allRows(
25685
+ this.partitionByKindStmt,
25686
+ {}
25687
+ ).map((row) => ({
25688
+ kind: row.kind,
25689
+ queued: row.queued ?? 0,
25690
+ inProgress: row.inProgress ?? 0,
25691
+ synced: row.synced ?? 0,
25692
+ failed: row.failed ?? 0,
25693
+ refused: row.refused ?? 0,
25694
+ detached: row.detached ?? 0,
25695
+ total: row.total ?? 0
25696
+ }));
25697
+ }
25698
+ partition() {
25699
+ const row = getRow(this.partitionStmt, {});
25700
+ return {
25701
+ queued: row?.queued ?? 0,
25702
+ inProgress: row?.inProgress ?? 0,
25703
+ synced: row?.synced ?? 0,
25704
+ failed: row?.failed ?? 0,
25705
+ refused: row?.refused ?? 0,
25706
+ detached: row?.detached ?? 0,
25707
+ total: row?.total ?? 0
25708
+ };
25709
+ }
25710
+ /** `pending` counts only what is inside the backlog; sent and skipped are totals. */
25711
+ counts(before) {
25712
+ const row = getRow(this.countsStmt, { before });
25713
+ const captures = getRow(this.captureSkipCountStmt);
25714
+ return {
25715
+ pending: row?.pending ?? 0,
25716
+ sent: row?.sent ?? 0,
25717
+ skipped: row?.skipped ?? 0,
25718
+ refused: row?.refused ?? 0,
25719
+ detached: row?.detached ?? 0,
25720
+ capturesSkipped: captures?.skipped ?? 0
25721
+ };
25722
+ }
25723
+ /**
25724
+ * The deployment the current stamps were made against, and where its backlog
25725
+ * ends.
25726
+ *
25727
+ * READ-ONLY. An absent row reads as an absent deployment, which is what a
25728
+ * machine that has never drained is — and every writer below seeds the row
25729
+ * before it needs one, so nothing depends on this creating it. Keeping the
25730
+ * write off the gate path matters because the gate runs on every pass while a
25731
+ * write has to take the database's write lock.
25732
+ */
25733
+ deployment() {
25734
+ const row = getRow(
25735
+ this.fingerprintStmt
25736
+ );
25737
+ return {
25738
+ fingerprint: row?.fingerprint ?? void 0,
25739
+ backlogBefore: row?.backlogBefore ?? void 0
25740
+ };
25741
+ }
25742
+ /**
25743
+ * Point the ledger at a different deployment, discarding what it recorded
25744
+ * about the previous one.
25745
+ *
25746
+ * Delivery is a fact about ONE recipient: rows sent to the deployment a
25747
+ * machine has just left are undelivered as far as the new one is concerned.
25748
+ * All four in one transaction, so a crash between them cannot leave stamps
25749
+ * attributed to the wrong deployment, a boundary that belongs to another, or
25750
+ * a disown with no re-mark to follow it.
25751
+ *
25752
+ * The boundary is written HERE and only here, which is what freezes it: a
25753
+ * re-attach to the SAME deployment (a key rotation) leaves the fingerprint
25754
+ * unchanged, so this never runs and the backlog does not widen back over rows
25755
+ * the live path has since delivered.
25756
+ *
25757
+ * `backfillCapturesBefore` is the caller's OWN "now" at the instant a human
25758
+ * granted existing-history consent for the deployment this call is arming —
25759
+ * a DIFFERENT instant from `backlogBefore`: the re-mark boundary is the GRANT
25760
+ * instant, `backlogBefore` is the ATTACH instant, and the two can be far
25761
+ * apart. Passed only when that grant is valid, since this method has no way
25762
+ * to check consent itself and must not mark a row owed for a machine that
25763
+ * never agreed to it. Applied AFTER the disown above, in the SAME
25764
+ * transaction: what the disown clears is every marker below `backlogBefore`,
25765
+ * which includes this deployment's OWN pre-attach rows — `aka attach` calls
25766
+ * `seedCaptureBacklogOwed` at the attach instant, so every row it marks sits
25767
+ * on the cleared side of that bound — and the re-mark in the same
25768
+ * transaction is what puts those rows back. A crash between the two cannot
25769
+ * strand the ledger disowned with nothing re-marked — the transaction either
25770
+ * lands whole or not at all, and a fingerprint mismatch that has not yet
25771
+ * committed re-enters this method on the very next pass. Omit it (the
25772
+ * structural-only tests do) to exercise the disown in isolation.
25773
+ *
25774
+ * The disown is bounded by `backlogBefore`, which is what keeps it from
25775
+ * touching a marker the NEW deployment's OWN live path has already set: B's
25776
+ * live path can mark a capture owed from the moment `aka attach` writes the
25777
+ * descriptor, before the drain's first pass ever reaches this method, and
25778
+ * such a row sits at or after the bound rather than below it. What keeps the
25779
+ * disown from eating THIS SAME CALL's own re-mark is the order, not the
25780
+ * bound — disown runs first, re-mark second, both inside the one
25781
+ * transaction above.
25782
+ */
25783
+ rearmFor(fingerprint, backlogBefore, backfillCapturesBefore) {
25784
+ this.ensureRowStmt.run();
25785
+ withTransaction(
25786
+ this.db,
25787
+ () => {
25788
+ const previous = getRow(this.fingerprintStmt)?.fingerprint;
25789
+ this.rearmStmt.run();
25790
+ if (previous !== null && previous !== void 0 && previous !== fingerprint) {
25791
+ this.disownCapturesStmt.run({ attachedAt: backlogBefore });
25792
+ }
25793
+ if (backfillCapturesBefore !== void 0) {
25794
+ this.markCaptureBacklogOwedStmt.run({ before: backfillCapturesBefore });
25795
+ }
25796
+ this.setFingerprintStmt.run({ fingerprint, backlogBefore });
25797
+ },
25798
+ "IMMEDIATE"
25799
+ );
25800
+ }
25801
+ /**
25802
+ * End the attached period: hand its rows to the live path, and release the
25803
+ * boundary so the next attachment can freeze a new one.
25804
+ *
25805
+ * WITHOUT THIS, a detach and a re-attach to the same deployment leave a window
25806
+ * nothing delivers. The fingerprint is unchanged, so the boundary is never
25807
+ * re-frozen and stays at the FIRST attachment — while nothing forwards at all
25808
+ * during the detached period, because the machine is not attached. Rows
25809
+ * recorded in that window sit after the boundary and before the re-attach, so
25810
+ * neither path takes them, and the pending count reports none outstanding.
25811
+ *
25812
+ * WHAT IT RECORDS, and what it deliberately does not. These rows were the
25813
+ * closing attachment's to deliver and are no longer outstanding — that is what
25814
+ * lets the boundary move. It is NOT a claim that any of them arrived, and the
25815
+ * distinction is not academic: this used to write a delivery TIME, which every
25816
+ * read treats as delivery, so one detach turned a window of undelivered rows
25817
+ * into a window of delivered ones and no surface could tell. It writes the
25818
+ * skip sentinel and a reason of its own instead, so "no longer owed" and
25819
+ * "received" stop being the same fact.
25820
+ *
25821
+ * A change of deployment still frees them (see the re-arm), because the next
25822
+ * deployment has seen none of this machine's history — so the rows reach it
25823
+ * exactly as they did when this wrote a delivery time.
25824
+ *
25825
+ * ONE TRANSACTION, so a crash cannot release the boundary while leaving the
25826
+ * window unstamped — that half-state would re-send the whole attached period
25827
+ * on the next attach, which is the failure the boundary exists to prevent.
25828
+ */
25829
+ closeAttachedWindow(attachedAtMs, atMs) {
25830
+ this.ensureRowStmt.run();
25831
+ withTransaction(
25832
+ this.db,
25833
+ () => {
25834
+ const row = getRow(this.fingerprintStmt);
25835
+ const from = row?.backlogBefore ?? attachedAtMs;
25836
+ this.closeWindowStmt.run({ at: atMs, attachedAt: from });
25837
+ this.releaseBoundaryStmt.run();
25838
+ },
25839
+ "IMMEDIATE"
25840
+ );
25841
+ }
25842
+ /**
25843
+ * Freeze a boundary for the deployment already on file, KEEPING the stamps.
25844
+ *
25845
+ * The re-attach half of the above. Distinct from `rearmFor`, which is for a
25846
+ * different deployment and therefore discards what was delivered to the old
25847
+ * one: here the recipient is the same, so everything already sent to it stays
25848
+ * sent.
25849
+ */
25850
+ freezeBoundary(backlogBefore) {
25851
+ this.ensureRowStmt.run();
25852
+ this.freezeBoundaryStmt.run({ backlogBefore });
25853
+ }
25854
+ /** Take the claim, or report that someone live already holds it. */
25855
+ claim(pid, host, nowMs, staleAfterMs) {
25856
+ this.ensureRowStmt.run();
25857
+ let taken = false;
25858
+ withTransaction(
25859
+ this.db,
25860
+ () => {
25861
+ const result = this.claimStmt.run({
25862
+ pid,
25863
+ host,
25864
+ now: nowMs,
25865
+ staleBefore: nowMs - staleAfterMs
25866
+ });
25867
+ taken = result.changes === 1;
25868
+ },
25869
+ "IMMEDIATE"
25870
+ );
25871
+ return taken;
25872
+ }
25873
+ /** Say the holder is still alive. A no-op once the claim has moved on. */
25874
+ heartbeat(pid, nowMs) {
25875
+ this.heartbeatStmt.run({ now: nowMs, pid });
25876
+ }
25877
+ /** Give the claim up. Scoped to this holder, so a taken-over claim is left be. */
25878
+ release(pid) {
25879
+ this.releaseStmt.run({ pid });
25880
+ }
25881
+ /** Who holds the claim, if anyone. Read-only, for the same reason as above. */
25882
+ lease() {
25883
+ return getRow(this.leaseStmt);
25884
+ }
25885
+ };
25886
+
25887
+ // ../../packages/persistence/src/migrations.ts
25888
+ function describeObject(object2) {
25889
+ return object2.kind === "column" ? `column ${object2.table}.${object2.name}` : `table ${object2.name}`;
25890
+ }
25891
+ function splitStatements(sql) {
25892
+ return sql.split(/-->\s*statement-breakpoint/).map((s) => s.trim()).filter((s) => s.length > 0);
25893
+ }
25894
+ function createdIndexName(statement) {
25895
+ const body = statement.replace(/^(?:\s*--[^\n]*\n?)+/, "").trimStart();
25896
+ return /^CREATE (?:UNIQUE )?INDEX (?:IF NOT EXISTS )?`([^`]+)`/.exec(body)?.[1];
25897
+ }
25898
+ var LEGACY_DROP_MIGRATION_TAG = "0014_drop_legacy_events_findings";
25899
+ function applyMigrations(db, file2, options = {}) {
25900
+ const legacyCount = db.prepare("PRAGMA user_version").get().user_version;
25901
+ db.exec(
25902
+ "CREATE TABLE IF NOT EXISTS migration_ledger (tag TEXT PRIMARY KEY, applied_at INTEGER NOT NULL)"
25903
+ );
25904
+ const applied = new Set(
25905
+ db.prepare("SELECT tag FROM migration_ledger").all().map((r) => r.tag)
25906
+ );
25907
+ const preLedgerStore = applied.size === 0 && legacyCount > 0;
25908
+ const record2 = db.prepare(
25909
+ "INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)"
25910
+ );
25911
+ for (const [index, migration] of SQLITE_MIGRATIONS.entries()) {
25912
+ if (applied.has(migration.tag)) continue;
25913
+ if (options.skipTags?.has(migration.tag) === true) continue;
25914
+ if (migration.tag === LEGACY_DROP_MIGRATION_TAG) continue;
25915
+ const evidence = evidenceObjects(migration.sql);
25916
+ const present = evidence.filter((o) => evidenceExists(db, o));
25917
+ if (present.length > 0 && present.length < evidence.length) {
25918
+ const missing = evidence.filter((o) => !present.includes(o));
25919
+ const message = `sqlite migration ${migration.tag} has no ledger row, but the store already has ${present.map(describeObject).join(", ")} while missing ${missing.map(describeObject).join(", ")} \u2014 the schema diverged from the migration history; refusing to replay or skip.`;
25920
+ akaWarn(message);
25921
+ throw new Error(`[aka] ${message}`);
25922
+ }
25923
+ const alreadyApplied = evidence.length > 0 ? present.length === evidence.length : preLedgerStore && index < legacyCount;
25924
+ const wantsFkOff = /PRAGMA foreign_keys\s*=\s*OFF/i.test(migration.sql);
25925
+ const statements = splitStatements(migration.sql);
25926
+ if (wantsFkOff) db.exec("PRAGMA foreign_keys = OFF");
25927
+ try {
25928
+ withTransaction(
25929
+ db,
25930
+ () => {
25931
+ for (const statement of statements) {
25932
+ const indexName = createdIndexName(statement);
25933
+ if (indexName === void 0) {
25934
+ if (alreadyApplied) continue;
25935
+ } else if (indexExists(db, indexName)) {
25936
+ continue;
25937
+ }
25938
+ db.exec(statement);
25939
+ }
25940
+ if (wantsFkOff && !alreadyApplied) {
25941
+ const violations = db.prepare("PRAGMA foreign_key_check").all();
25942
+ if (violations.length > 0) {
25943
+ throw new Error(
25944
+ `[aka] sqlite migration ${migration.tag} left ${String(violations.length)} foreign-key violation(s); rolling back.`
25945
+ );
25946
+ }
25947
+ }
25948
+ record2.run(migration.tag, Date.now());
25949
+ },
25950
+ "IMMEDIATE"
25951
+ );
25952
+ } finally {
25953
+ if (wantsFkOff) db.exec("PRAGMA foreign_keys = ON");
25954
+ }
25955
+ }
25956
+ if (legacyCount < SQLITE_MIGRATIONS.length) {
25957
+ db.exec(`PRAGMA user_version = ${String(SQLITE_MIGRATIONS.length)}`);
25958
+ }
25959
+ ensureSyncedAtColumn(db, "audit_events");
25960
+ ensureScanLedgerTable(db);
25961
+ ensureHistorySyncTable(db);
25962
+ ensureBlockedDetectionsTable(db);
25963
+ ensureRuleProbeCacheTable(db);
25964
+ ensureWriteGateTrigger(db);
25965
+ ensureTokenUsageColumns(db);
25966
+ reconcileSourceProjectIds(db);
25967
+ if (!applied.has(LEGACY_DROP_MIGRATION_TAG)) {
25968
+ const drained = runLegacyHistoryBackfill(db);
25969
+ if (drained) applyLegacyDropMigration(db, file2);
25970
+ }
25971
+ }
25972
+ function readLegacyTables(db) {
25973
+ let holdsRows = false;
25974
+ const marks = [];
25975
+ for (const table of ["events", "findings"]) {
25976
+ try {
25977
+ const row = db.prepare(`SELECT count(*) AS n, ifnull(max(rowid), -1) AS hi FROM ${table}`).get();
25978
+ if (row === void 0) {
25979
+ holdsRows = true;
25980
+ marks.push(`${table}:unreadable`);
25981
+ continue;
25982
+ }
25983
+ if (row.n > 0) holdsRows = true;
25984
+ marks.push(`${table}:${String(row.n)}:${String(row.hi)}`);
25985
+ } catch {
25986
+ holdsRows = true;
25987
+ marks.push(`${table}:unreadable`);
25988
+ }
25989
+ }
25990
+ return { holdsRows, mark: marks.join("|") };
25991
+ }
25992
+ function applyLegacyDropMigration(db, file2) {
25993
+ const migration = SQLITE_MIGRATIONS.find((m) => m.tag === LEGACY_DROP_MIGRATION_TAG);
25994
+ if (!migration) return;
25995
+ const before = file2 === void 0 ? void 0 : readLegacyTables(db);
25996
+ if (file2 !== void 0 && before?.holdsRows === true) {
25997
+ try {
25998
+ backupBeforeLegacyDrop(db, file2);
25999
+ } catch (error61) {
26000
+ akaWarn(`legacy events/findings backup failed; deferring the drop: ${String(error61)}`);
26001
+ return;
26002
+ }
26003
+ }
26004
+ try {
26005
+ withTransaction(
26006
+ db,
26007
+ () => {
26008
+ const alreadyDropped = db.prepare("SELECT 1 FROM migration_ledger WHERE tag = ?").get(migration.tag);
26009
+ if (alreadyDropped) return;
26010
+ if (before !== void 0 && readLegacyTables(db).mark !== before.mark) {
26011
+ akaWarn(
26012
+ "legacy events/findings rows changed after the pre-drop snapshot decision; deferring the drop so the next open can copy them first."
26013
+ );
26014
+ return;
26015
+ }
26016
+ for (const statement of splitStatements(migration.sql)) {
26017
+ db.exec(statement);
26018
+ }
26019
+ db.prepare("INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)").run(
26020
+ migration.tag,
26021
+ Date.now()
26022
+ );
26023
+ },
26024
+ "IMMEDIATE"
26025
+ );
26026
+ } catch (error61) {
26027
+ akaWarn(`legacy events/findings drop failed; deferring: ${String(error61)}`);
26028
+ }
26029
+ }
26030
+ function backupBeforeLegacyDrop(db, file2) {
26031
+ reapStalePartials(file2);
26032
+ const backup = backupPath(file2, "pre-drop");
26033
+ snapshotStore(db, backup);
26034
+ return backup;
26035
+ }
26036
+ var TOKEN_USAGE_COLUMNS = [
26037
+ {
26038
+ name: "input_tokens",
26039
+ ddl: "ALTER TABLE audit_events ADD COLUMN input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.input_tokens')) VIRTUAL"
26040
+ },
26041
+ {
24901
26042
  name: "output_tokens",
24902
26043
  ddl: "ALTER TABLE audit_events ADD COLUMN output_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.output_tokens')) VIRTUAL"
24903
26044
  },
@@ -25176,10 +26317,62 @@ function ensureSyncedAtColumn(db, table) {
25176
26317
  if (!columns.includes("outbox_owed")) {
25177
26318
  db.exec(`ALTER TABLE ${table} ADD COLUMN outbox_owed integer`);
25178
26319
  }
26320
+ if (!columns.includes("sync_failed_at")) {
26321
+ db.exec(`ALTER TABLE ${table} ADD COLUMN sync_failed_at integer`);
26322
+ }
26323
+ if (!columns.includes("sync_failure")) {
26324
+ withTransaction(
26325
+ db,
26326
+ () => {
26327
+ db.exec(`ALTER TABLE ${table} ADD COLUMN sync_failure text`);
26328
+ db.exec(
26329
+ `UPDATE ${table} SET synced_at = NULL
26330
+ WHERE synced_at = -1
26331
+ AND event_type IN (${COUNTED_EVENT_TYPES.map((t) => `'${t}'`).join(", ")})`
26332
+ );
26333
+ },
26334
+ "IMMEDIATE"
26335
+ );
26336
+ }
25179
26337
  db.exec(
25180
- `CREATE INDEX IF NOT EXISTS idx_audit_events_sync
25181
- ON audit_events (event_type, synced_at, sync_claimed_at, started_at)`
26338
+ `CREATE TRIGGER IF NOT EXISTS aka_sync_failure_guard
26339
+ BEFORE UPDATE OF sync_failure ON ${table}
26340
+ WHEN ${syncFailureRejectCondition()}
26341
+ BEGIN SELECT RAISE(ABORT, 'sync_failure is not one of the recorded reasons'); END`
25182
26342
  );
26343
+ const syncIndexColumns = [
26344
+ "event_type",
26345
+ "synced_at",
26346
+ "sync_claimed_at",
26347
+ "started_at",
26348
+ // Appended LAST on purpose. The delivery-state read now projects it, so it
26349
+ // has to be in the index for the read to stay covered — but putting it
26350
+ // ahead of `started_at` would reorder the prefix the structural drain's
26351
+ // reads match on.
26352
+ "sync_failure"
26353
+ // `outbox_owed` is DELIBERATELY ABSENT, and it was measured both ways.
26354
+ //
26355
+ // The delivery-state read tests it — a capture's state depends on whether a
26356
+ // live forward marked it owed — so carrying it here makes that read covering
26357
+ // rather than a row fetch per row: 16 ms against 40 ms on a real 6 GB store.
26358
+ // But a sixth column changes what the planner charges for this index, and
26359
+ // with no ANALYZE statistics it plans from schema shape alone: measured, it
26360
+ // then stops choosing the per-session index for the token rollup and walks
26361
+ // every `llm_call` in the store through the event-type index instead. That
26362
+ // read grows with the store; this one does not.
26363
+ //
26364
+ // 40 ms on the largest store measured, once per render, is a cost worth
26365
+ // paying to leave every other read's plan where it was.
26366
+ ];
26367
+ const currentSyncIndex = indexColumns(db, "idx_audit_events_sync");
26368
+ const syncIndexMatches = currentSyncIndex.length === syncIndexColumns.length && currentSyncIndex.every((column, i) => column === syncIndexColumns[i]);
26369
+ if (!syncIndexMatches) {
26370
+ db.exec("DROP INDEX IF EXISTS idx_audit_events_sync");
26371
+ db.exec(
26372
+ `CREATE INDEX idx_audit_events_sync
26373
+ ON audit_events (${syncIndexColumns.join(", ")})`
26374
+ );
26375
+ }
25183
26376
  db.exec(
25184
26377
  `CREATE INDEX IF NOT EXISTS idx_audit_outbox_owed
25185
26378
  ON audit_events (event_type, synced_at, sync_claimed_at, started_at) WHERE outbox_owed = 1`
@@ -25401,7 +26594,11 @@ function buildAuditEvent(row) {
25401
26594
  link: linkParsed?.success ? linkParsed.data : null,
25402
26595
  targetId: row.target_id,
25403
26596
  internal: intToBool(row.internal),
25404
- flagged: intToBool(row.flagged)
26597
+ flagged: intToBool(row.flagged),
26598
+ // Only meaningful when the title came out empty — a row whose body was
26599
+ // expired but whose title fell back to `tool_name` still has something to
26600
+ // render, and flagging it would make the view apologise for nothing.
26601
+ bodyExpired: row.content_expired_at !== null && (row.title ?? "") === ""
25405
26602
  };
25406
26603
  }
25407
26604
  var TIMELINE_COLUMNS = `
@@ -25409,6 +26606,7 @@ var TIMELINE_COLUMNS = `
25409
26606
  event_type,
25410
26607
  started_at,
25411
26608
  coalesce(content, json_extract(attributes, '$.tool_name')) AS title,
26609
+ content_expired_at,
25412
26610
  coalesce(json_extract(attributes, '$.detail'), json_extract(attributes, '$.target')) AS detail,
25413
26611
  coalesce(json_extract(attributes, '$.tool_name'), json_extract(attributes, '$.tool')) AS tool,
25414
26612
  json_extract(attributes, '$.severity') AS severity,
@@ -25451,7 +26649,7 @@ var SESSION_ROOT = `event_type = 'session'`;
25451
26649
  var HAS_ACTIVITY = `EXISTS (
25452
26650
  SELECT 1 FROM audit_events c
25453
26651
  WHERE c.root_session_id = audit_events.id
25454
- AND c.event_type NOT IN ('hook', 'config_scan'))`;
26652
+ AND c.event_type NOT IN ('hook', 'config_scan', 'capture_status'))`;
25455
26653
  var SqliteActivityRepository = class {
25456
26654
  constructor(db, now = () => Date.now()) {
25457
26655
  this.db = db;
@@ -25478,10 +26676,10 @@ var SqliteActivityRepository = class {
25478
26676
  SELECT id FROM audit_events WHERE event_type = 'session' AND started_at >= ?
25479
26677
  UNION
25480
26678
  SELECT root_session_id FROM audit_events INDEXED BY idx_audit_started_at
25481
- WHERE started_at >= ?
26679
+ WHERE started_at >= ? AND event_type <> 'capture_status'
25482
26680
  UNION
25483
26681
  SELECT root_session_id FROM audit_events INDEXED BY idx_audit_ended_at
25484
- WHERE ended_at >= ?)`,
26682
+ WHERE ended_at >= ? AND event_type <> 'capture_status')`,
25485
26683
  [liveThreshold, liveThreshold, liveThreshold]
25486
26684
  );
25487
26685
  const toolCallsToday = countScalar(
@@ -25888,7 +27086,10 @@ var SqliteAuditEventsRepository = class {
25888
27086
  attributes = excluded.attributes,
25889
27087
  ended_at = excluded.ended_at
25890
27088
  WHERE COALESCE(json_extract(excluded.attributes, '$.output_tokens'), 0)
25891
- > COALESCE(json_extract(audit_events.attributes, '$.output_tokens'), 0)`
27089
+ > COALESCE(json_extract(audit_events.attributes, '$.output_tokens'), 0)
27090
+ OR (json_extract(excluded.attributes, '$.usage_source') IS NOT NULL
27091
+ AND json_extract(excluded.attributes, '$.output_tokens') IS NULL
27092
+ AND excluded.attributes <> audit_events.attributes)`
25892
27093
  );
25893
27094
  this.upsertSessionRootStmt = db.prepare(
25894
27095
  `INSERT OR IGNORE INTO audit_events
@@ -26074,6 +27275,169 @@ var SqliteAuditEventsRepository = class {
26074
27275
  }
26075
27276
  };
26076
27277
 
27278
+ // ../../packages/persistence/src/repositories/body-retention.ts
27279
+ var DEFAULT_BATCH_SIZE = 500;
27280
+ var DEFAULT_MAX_ROWS = 5e4;
27281
+ var SYNC_LANE_TYPES_SQL = OUTBOX_CAPTURE_TYPE_LIST;
27282
+ var SqliteBodyRetentionRepository = class {
27283
+ constructor(db) {
27284
+ this.db = db;
27285
+ const select = (laneClause) => `
27286
+ SELECT id, LENGTH(CAST(content AS BLOB)) AS bytes
27287
+ FROM audit_events
27288
+ WHERE content IS NOT NULL
27289
+ AND started_at < :cutoff
27290
+ AND event_type IN (${CAPTURE_EVENT_TYPES_SQL})
27291
+ ${laneClause}
27292
+ ORDER BY started_at
27293
+ LIMIT :limit`;
27294
+ this.candidatesStmt = this.db.prepare(select(""));
27295
+ this.candidatesSyncSafeStmt = this.db.prepare(
27296
+ select(`AND (event_type NOT IN (${SYNC_LANE_TYPES_SQL}) OR synced_at IS NOT NULL)`)
27297
+ );
27298
+ this.heldBySyncStmt = this.db.prepare(`
27299
+ SELECT COUNT(*) AS n
27300
+ FROM audit_events
27301
+ WHERE content IS NOT NULL
27302
+ AND started_at < :cutoff
27303
+ AND event_type IN (${SYNC_LANE_TYPES_SQL})
27304
+ AND synced_at IS NULL`);
27305
+ this.expireStmt = this.db.prepare(
27306
+ `UPDATE audit_events SET content = NULL, content_expired_at = :now WHERE id = :id`
27307
+ );
27308
+ }
27309
+ db;
27310
+ candidatesStmt;
27311
+ candidatesSyncSafeStmt;
27312
+ heldBySyncStmt;
27313
+ expireStmt;
27314
+ /** How many bytes a pass with these options would free, changing nothing. */
27315
+ preview(opts) {
27316
+ const limit = opts.maxRows ?? DEFAULT_MAX_ROWS;
27317
+ const stmt = opts.sweepSyncLane ? this.candidatesStmt : this.candidatesSyncSafeStmt;
27318
+ const rows = stmt.all({ cutoff: opts.cutoff, limit });
27319
+ return {
27320
+ rowsExpired: rows.length,
27321
+ bytesFreed: rows.reduce((sum, r) => sum + r.bytes, 0),
27322
+ rowsHeldBySync: this.countHeldBySync(opts)
27323
+ };
27324
+ }
27325
+ /** Clear eligible bodies, in bounded batches. */
27326
+ expire(opts) {
27327
+ const batchSize = opts.batchSize ?? DEFAULT_BATCH_SIZE;
27328
+ const maxRows = opts.maxRows ?? DEFAULT_MAX_ROWS;
27329
+ const stmt = opts.sweepSyncLane ? this.candidatesStmt : this.candidatesSyncSafeStmt;
27330
+ let rowsExpired = 0;
27331
+ let bytesFreed = 0;
27332
+ let done = true;
27333
+ while (rowsExpired < maxRows) {
27334
+ const remaining = Math.min(batchSize, maxRows - rowsExpired);
27335
+ const batch = stmt.all({ cutoff: opts.cutoff, limit: remaining });
27336
+ if (batch.length === 0) break;
27337
+ withTransaction(
27338
+ this.db,
27339
+ () => {
27340
+ for (const row of batch) this.expireStmt.run({ id: row.id, now: opts.now });
27341
+ },
27342
+ "IMMEDIATE"
27343
+ );
27344
+ rowsExpired += batch.length;
27345
+ bytesFreed += batch.reduce((sum, r) => sum + r.bytes, 0);
27346
+ if (batch.length < remaining) break;
27347
+ if (rowsExpired >= maxRows) {
27348
+ done = stmt.all({ cutoff: opts.cutoff, limit: 1 }).length === 0;
27349
+ }
27350
+ }
27351
+ return { rowsExpired, bytesFreed, rowsHeldBySync: this.countHeldBySync(opts), done };
27352
+ }
27353
+ countHeldBySync(opts) {
27354
+ if (opts.sweepSyncLane) return 0;
27355
+ const row = this.heldBySyncStmt.get({ cutoff: opts.cutoff });
27356
+ return row.n;
27357
+ }
27358
+ };
27359
+
27360
+ // ../../packages/persistence/src/repositories/capture-status.ts
27361
+ var STATUS_LOOKBACK_ROWS = 128;
27362
+ var SqliteCaptureStatusRepository = class {
27363
+ constructor(db) {
27364
+ this.db = db;
27365
+ this.recentStmt = db.prepare(
27366
+ `SELECT a.started_at AS startedAt,
27367
+ a.attributes AS attributes,
27368
+ a.root_session_id AS rootSessionId
27369
+ FROM audit_events a
27370
+ WHERE a.event_type = 'capture_status'
27371
+ AND a.source_tool = ?
27372
+ AND a.started_at >= ?
27373
+ ORDER BY a.started_at DESC, a.id DESC
27374
+ LIMIT ?`
27375
+ );
27376
+ }
27377
+ db;
27378
+ recentStmt;
27379
+ /**
27380
+ * Every document that reported for a site, in registry order by site, from
27381
+ * the last `CAPTURE_STATUS_RECENCY_MS`.
27382
+ *
27383
+ * SEVERAL per site, not one: a browser is many documents and each reports
27384
+ * for itself, so one row per site is a choice about which of them a user
27385
+ * sees — and the newest is the wrong one, since a healthy tab writing a
27386
+ * fresh report would hide a drifting tab's verdict, which is the whole
27387
+ * reason these rows exist. The pick WITHIN a document is made here (the
27388
+ * unchanged `pickReportedCaptureStatus`, over that document's own rows);
27389
+ * choosing between documents belongs where the state semantics live, and
27390
+ * that is `reportedCaptureDocumentForSite` in `@akasecurity/detections` —
27391
+ * this package may not import it.
27392
+ *
27393
+ * `now` is a required argument rather than a `Date.now()` read, so a caller
27394
+ * that already holds a render instant passes THAT one and a test can drive
27395
+ * the window without moving the wall clock.
27396
+ *
27397
+ * A site whose reports have all aged out contributes nothing, so it derives
27398
+ * to `unreported`. That is the point: nothing but the browser extension ever
27399
+ * writes these rows, so an uninstalled extension's last verdict would
27400
+ * otherwise stand as a live claim for ever with no later report able to
27401
+ * clear it.
27402
+ */
27403
+ latest(now) {
27404
+ const since = now - CAPTURE_STATUS_RECENCY_MS;
27405
+ const documents = [];
27406
+ for (const tool of WebSourceTool.options) {
27407
+ const rows = /* @__PURE__ */ new Map();
27408
+ const lastWord = /* @__PURE__ */ new Map();
27409
+ for (const row of allRows(this.recentStmt, [
27410
+ tool,
27411
+ since,
27412
+ STATUS_LOOKBACK_ROWS
27413
+ ])) {
27414
+ const status = fromCaptureStatusAttributes(parseJsonObject(row.attributes));
27415
+ if (status === null) continue;
27416
+ const record2 = { tool, observedAt: epochMillisToIso(row.startedAt), status };
27417
+ const group = rows.get(row.rootSessionId);
27418
+ if (group === void 0) {
27419
+ rows.set(row.rootSessionId, [record2]);
27420
+ lastWord.set(row.rootSessionId, { at: record2.observedAt, closed: status.closed });
27421
+ } else {
27422
+ group.push(record2);
27423
+ }
27424
+ }
27425
+ for (const [root, candidates] of rows) {
27426
+ const picked = pickReportedCaptureStatus(candidates);
27427
+ const last = lastWord.get(root);
27428
+ if (picked === void 0 || last === void 0) continue;
27429
+ documents.push({
27430
+ ...picked,
27431
+ ...root === null ? {} : { rootSessionId: root },
27432
+ lastReportAt: last.at,
27433
+ closed: last.closed
27434
+ });
27435
+ }
27436
+ }
27437
+ return documents;
27438
+ }
27439
+ };
27440
+
26077
27441
  // ../../packages/persistence/src/repositories/classified-data.ts
26078
27442
  var SqliteClassifiedDataRepository = class {
26079
27443
  constructor(db) {
@@ -26902,7 +28266,15 @@ function toFlatFindingRow(r) {
26902
28266
  ...r.tool_name === null ? {} : { toolName: r.tool_name },
26903
28267
  eventId: r.event_id,
26904
28268
  ...r.session_id === null ? {} : { sessionId: r.session_id },
26905
- status: deriveInstanceStatus(r)
28269
+ status: deriveInstanceStatus(r),
28270
+ delivery: deriveFindingDelivery({
28271
+ kind: r.kind,
28272
+ syncedAt: r.synced_at,
28273
+ syncClaimedAt: r.sync_claimed_at,
28274
+ syncFailedAt: r.sync_failed_at,
28275
+ syncFailure: r.sync_failure,
28276
+ outboxOwed: r.outbox_owed
28277
+ })
26906
28278
  };
26907
28279
  }
26908
28280
  function encodeGroupCursor(group) {
@@ -26966,7 +28338,10 @@ var FINDING_ROW_COLUMNS_SQL = `f.id AS id, d.rule_id AS rule_id, d.category AS c
26966
28338
  e.tool_name AS tool_name,
26967
28339
  f.audit_event_id AS event_id, e.root_session_id AS session_id,
26968
28340
  e.event_type AS kind, f.finding_key AS finding_key,
26969
- ${latestResolutionStatusSql("f")} AS latest_status`;
28341
+ ${latestResolutionStatusSql("f")} AS latest_status,
28342
+ e.synced_at AS synced_at, e.sync_claimed_at AS sync_claimed_at,
28343
+ e.sync_failed_at AS sync_failed_at, e.sync_failure AS sync_failure,
28344
+ e.outbox_owed AS outbox_owed`;
26970
28345
  var DAY_MS3 = 864e5;
26971
28346
  var SqliteFindingsRepository = class {
26972
28347
  constructor(db) {
@@ -27211,6 +28586,7 @@ var SqliteFindingsRepository = class {
27211
28586
  providers: query.provider,
27212
28587
  actions: query.action,
27213
28588
  statuses: query.status,
28589
+ deliveries: query.deployment,
27214
28590
  tools: query.tool,
27215
28591
  repo: query.repo,
27216
28592
  file: query.file,
@@ -27278,6 +28654,7 @@ var SqliteFindingsRepository = class {
27278
28654
  providers: query.provider,
27279
28655
  actions: query.action,
27280
28656
  statuses: query.status,
28657
+ deliveries: query.deployment,
27281
28658
  tools: query.tool,
27282
28659
  q: query.q
27283
28660
  };
@@ -27541,7 +28918,9 @@ var SqliteFindingsRepository = class {
27541
28918
  )
27542
28919
  );
27543
28920
  for (const row of grouped) {
27544
- if (row.action_taken in byAction) byAction[row.action_taken] = row.c;
28921
+ if (Object.hasOwn(byAction, row.action_taken)) {
28922
+ byAction[row.action_taken] = row.c;
28923
+ }
27545
28924
  }
27546
28925
  const bySeverity = { critical: 0, high: 0, medium: 0, low: 0 };
27547
28926
  const sevRows = allRows(
@@ -27558,7 +28937,9 @@ var SqliteFindingsRepository = class {
27558
28937
  )
27559
28938
  );
27560
28939
  for (const row of sevRows) {
27561
- if (row.severity in bySeverity) bySeverity[row.severity] = row.c;
28940
+ if (Object.hasOwn(bySeverity, row.severity)) {
28941
+ bySeverity[row.severity] = row.c;
28942
+ }
27562
28943
  }
27563
28944
  const categories = ENFORCEABLE_CATEGORIES;
27564
28945
  const enabledRows = allRows(
@@ -27607,525 +28988,6 @@ function isoDay(ms) {
27607
28988
  return new Date(ms).toISOString().slice(0, 10);
27608
28989
  }
27609
28990
 
27610
- // ../../packages/persistence/src/repositories/history-sync.ts
27611
- var STRUCTURAL_EVENT_TYPES = ["session", "llm_call", "tool_call"];
27612
- var TYPE_LIST = STRUCTURAL_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
27613
- var OUTBOX_CAPTURE_EVENT_TYPES = ["prompt", "response", "tool_use"];
27614
- var CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
27615
- var SKIPPED = -1;
27616
- var ROW_COLUMNS = `id,
27617
- parent_id AS parentId,
27618
- root_session_id AS rootSessionId,
27619
- event_type AS eventType,
27620
- host_id AS hostId,
27621
- harness_id AS harnessId,
27622
- source_project_id AS sourceProjectId,
27623
- started_at AS startedAt,
27624
- ended_at AS endedAt,
27625
- severity,
27626
- priority,
27627
- content,
27628
- content_hash AS contentHash,
27629
- attributes`;
27630
- var SqliteHistorySyncRepository = class {
27631
- constructor(db) {
27632
- this.db = db;
27633
- this.ensureRowStmt = db.prepare(`INSERT OR IGNORE INTO history_sync (id) VALUES (1)`);
27634
- this.sessionsStmt = db.prepare(
27635
- `SELECT COALESCE(root_session_id, id) AS sessionId, MIN(started_at) AS earliest
27636
- FROM audit_events
27637
- WHERE synced_at IS NULL
27638
- AND event_type IN (${TYPE_LIST})
27639
- AND started_at < :before
27640
- GROUP BY sessionId
27641
- ORDER BY earliest
27642
- LIMIT :limit`
27643
- );
27644
- this.rowsStmt = db.prepare(
27645
- `SELECT ${ROW_COLUMNS}
27646
- FROM audit_events
27647
- WHERE synced_at IS NULL
27648
- AND event_type IN (${TYPE_LIST})
27649
- AND started_at < :before
27650
- AND COALESCE(root_session_id, id) = :sessionId
27651
- ORDER BY (event_type = 'session') DESC, started_at
27652
- LIMIT :limit`
27653
- );
27654
- this.captureRowsStmt = db.prepare(
27655
- `SELECT ${ROW_COLUMNS}
27656
- FROM audit_events
27657
- WHERE synced_at IS NULL
27658
- AND sync_claimed_at IS NULL
27659
- AND outbox_owed = 1
27660
- AND event_type IN (${CAPTURE_TYPE_LIST})
27661
- AND started_at < :before
27662
- ORDER BY started_at
27663
- LIMIT :limit`
27664
- );
27665
- this.markOwedStmt = db.prepare(
27666
- `UPDATE audit_events SET outbox_owed = 1 WHERE id = :id AND synced_at IS NULL`
27667
- );
27668
- this.markCaptureBacklogOwedStmt = db.prepare(
27669
- `UPDATE audit_events SET outbox_owed = 1
27670
- WHERE synced_at IS NULL
27671
- AND event_type IN (${CAPTURE_TYPE_LIST})
27672
- AND started_at < :before`
27673
- );
27674
- this.stampStmt = db.prepare(
27675
- `UPDATE audit_events SET synced_at = :at, sync_claimed_at = NULL WHERE id = :id`
27676
- );
27677
- this.claimRowStmt = db.prepare(
27678
- `UPDATE audit_events SET sync_claimed_at = :at WHERE id = :id AND synced_at IS NULL`
27679
- );
27680
- this.releaseRowStmt = db.prepare(
27681
- `UPDATE audit_events SET sync_claimed_at = NULL WHERE id = :id`
27682
- );
27683
- this.releaseStaleClaimsStmt = db.prepare(
27684
- `UPDATE audit_events SET sync_claimed_at = NULL
27685
- WHERE sync_claimed_at IS NOT NULL AND sync_claimed_at < :staleBefore`
27686
- );
27687
- this.partitionStmt = db.prepare(
27688
- `SELECT
27689
- SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NULL THEN 1 ELSE 0 END) AS queued,
27690
- SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NOT NULL THEN 1 ELSE 0 END) AS inProgress,
27691
- SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS synced,
27692
- SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0 THEN 1 ELSE 0 END) AS failed,
27693
- COUNT(*) AS total
27694
- FROM audit_events
27695
- WHERE event_type IN (${TYPE_LIST})`
27696
- );
27697
- this.countsStmt = db.prepare(
27698
- `SELECT
27699
- SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
27700
- SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
27701
- SUM(CASE WHEN synced_at = ${String(SKIPPED)} THEN 1 ELSE 0 END) AS skipped
27702
- FROM audit_events
27703
- WHERE event_type IN (${TYPE_LIST})`
27704
- );
27705
- this.captureSkipCountStmt = db.prepare(
27706
- `SELECT COUNT(*) AS skipped
27707
- FROM audit_events
27708
- WHERE synced_at = ${String(SKIPPED)}
27709
- AND event_type IN (${CAPTURE_TYPE_LIST})`
27710
- );
27711
- this.fingerprintStmt = db.prepare(
27712
- `SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
27713
- FROM history_sync WHERE id = 1`
27714
- );
27715
- this.setFingerprintStmt = db.prepare(
27716
- `UPDATE history_sync
27717
- SET endpoint_fingerprint = :fingerprint, backlog_before = :backlogBefore
27718
- WHERE id = 1`
27719
- );
27720
- this.disownCapturesStmt = db.prepare(
27721
- `UPDATE audit_events SET outbox_owed = NULL
27722
- WHERE outbox_owed IS NOT NULL
27723
- AND event_type IN (${CAPTURE_TYPE_LIST})
27724
- AND started_at < :attachedAt`
27725
- );
27726
- this.rearmStmt = db.prepare(
27727
- `UPDATE audit_events SET synced_at = NULL
27728
- WHERE synced_at > 0 AND event_type IN (${TYPE_LIST})`
27729
- );
27730
- this.claimStmt = db.prepare(
27731
- `UPDATE history_sync
27732
- SET owner_pid = :pid, owner_host = :host, acquired_at = :now, heartbeat_at = :now
27733
- WHERE id = 1
27734
- AND (owner_pid IS NULL
27735
- OR heartbeat_at IS NULL
27736
- OR heartbeat_at < :staleBefore
27737
- OR heartbeat_at > :now)`
27738
- );
27739
- this.heartbeatStmt = db.prepare(
27740
- `UPDATE history_sync SET heartbeat_at = :now WHERE id = 1 AND owner_pid = :pid`
27741
- );
27742
- this.releaseStmt = db.prepare(
27743
- `UPDATE history_sync
27744
- SET owner_pid = NULL, owner_host = NULL, acquired_at = NULL, heartbeat_at = NULL
27745
- WHERE id = 1 AND owner_pid = :pid`
27746
- );
27747
- this.closeWindowStmt = db.prepare(
27748
- `UPDATE audit_events SET synced_at = :at
27749
- WHERE synced_at IS NULL
27750
- AND event_type IN (${TYPE_LIST})
27751
- AND started_at >= :attachedAt`
27752
- );
27753
- this.releaseBoundaryStmt = db.prepare(
27754
- `UPDATE history_sync SET backlog_before = NULL WHERE id = 1`
27755
- );
27756
- this.freezeBoundaryStmt = db.prepare(
27757
- `UPDATE history_sync SET backlog_before = :backlogBefore WHERE id = 1`
27758
- );
27759
- this.leaseStmt = db.prepare(
27760
- `SELECT owner_pid AS ownerPid, owner_host AS ownerHost,
27761
- acquired_at AS acquiredAt, heartbeat_at AS heartbeatAt
27762
- FROM history_sync WHERE id = 1`
27763
- );
27764
- this.inspectionsStmt = db.prepare(
27765
- `SELECT d.rule_id AS ruleId,
27766
- d.name AS ruleName,
27767
- d.version AS ruleVersion,
27768
- d.category AS category,
27769
- d.severity AS severity,
27770
- f.span_start AS spanStart,
27771
- f.span_end AS spanEnd,
27772
- f.masked_match AS maskedMatch,
27773
- f.action_taken AS actionTaken,
27774
- f.confidence AS confidence
27775
- FROM inspection_findings f
27776
- JOIN inspection_definitions d ON d.id = f.inspection_definition_id
27777
- WHERE f.audit_event_id = :auditEventId
27778
- ORDER BY f.span_start, f.id`
27779
- );
27780
- }
27781
- db;
27782
- ensureRowStmt;
27783
- sessionsStmt;
27784
- rowsStmt;
27785
- stampStmt;
27786
- countsStmt;
27787
- fingerprintStmt;
27788
- setFingerprintStmt;
27789
- rearmStmt;
27790
- claimStmt;
27791
- heartbeatStmt;
27792
- releaseStmt;
27793
- leaseStmt;
27794
- inspectionsStmt;
27795
- closeWindowStmt;
27796
- releaseBoundaryStmt;
27797
- freezeBoundaryStmt;
27798
- captureRowsStmt;
27799
- markOwedStmt;
27800
- markCaptureBacklogOwedStmt;
27801
- captureSkipCountStmt;
27802
- disownCapturesStmt;
27803
- partitionStmt;
27804
- claimRowStmt;
27805
- releaseRowStmt;
27806
- releaseStaleClaimsStmt;
27807
- /**
27808
- * The masked detections recorded against one tool call.
27809
- *
27810
- * These travel with the event because a tool call's target is not
27811
- * re-inspectable from the event alone — unlike a capture, where the text
27812
- * itself is re-scannable. What crosses is the masked match and the rule that
27813
- * produced it, never the value.
27814
- */
27815
- inspectionsFor(auditEventId) {
27816
- return allRows(this.inspectionsStmt, { auditEventId });
27817
- }
27818
- /**
27819
- * Sessions with structural rows still to send, oldest first.
27820
- *
27821
- * BOUNDED BY THE BACKLOG BOUNDARY, which is the whole correctness of this
27822
- * read. Anything recorded after the machine attached is the live forward
27823
- * path's to deliver; this drain exists for what was recorded before it, and a
27824
- * row both paths send is at best a duplicate request and at worst — for a
27825
- * session root — an overwrite of the inventory ids the live path resolved.
27826
- */
27827
- pendingSessions(limit, before) {
27828
- return allRows(this.sessionsStmt, { limit, before }).map(
27829
- (r) => r.sessionId
27830
- );
27831
- }
27832
- /** One session's undelivered structural rows within the backlog, root first. */
27833
- pendingRows(sessionId, limit, before) {
27834
- return allRows(this.rowsStmt, { sessionId, limit, before });
27835
- }
27836
- /**
27837
- * Captures this machine still owes the deployment, oldest first.
27838
- *
27839
- * Selected by the `outbox_owed` marker the attached forward path writes, not
27840
- * by a time window — see captureRowsStmt for why a window could not express
27841
- * this. `before` is the grace window that leaves a just-recorded capture to
27842
- * the live path.
27843
- */
27844
- pendingCaptureRows(limit, before) {
27845
- return allRows(this.captureRowsStmt, { limit, before });
27846
- }
27847
- /**
27848
- * Record that a capture is OWED to the deployment.
27849
- *
27850
- * Written by the attached forward path when a live send did not confirm
27851
- * delivery, and read by the drain as the whole of its eligibility test. It is
27852
- * a fact rather than an inference: the machine was attached, the send did not
27853
- * land, so the row is owed — which no time window can state, because the same
27854
- * window that holds the rows a past attachment left owed also holds every
27855
- * capture recorded while the machine was DETACHED, and those were never
27856
- * offered to anyone.
27857
- *
27858
- * Idempotent, and never un-set: `markSynced` settling the row is what takes it
27859
- * out of the drain's read.
27860
- */
27861
- markCaptureOwed(id) {
27862
- this.markOwedStmt.run({ id });
27863
- }
27864
- /**
27865
- * Mark every capture already on disk as owed, as of `before`.
27866
- *
27867
- * The consent-time backfill, called once from `aka attach` when a human
27868
- * grants existing-history consent — never from an ongoing drain pass, and
27869
- * never inferred from a boundary that could later move. `before` is the
27870
- * caller's own "now" at the moment consent was granted, so what this marks
27871
- * is exactly the backlog the consent prompt already counted, not whatever a
27872
- * later re-attach or key rotation might widen it to.
27873
- *
27874
- * Returns how many rows matched, for the caller to log or test against. Not a
27875
- * count of NEWLY marked rows — a row still unsynced from an earlier call
27876
- * matches again and is counted again, the same as `UPDATE`'s own `changes`.
27877
- */
27878
- markCaptureBacklogOwed(before) {
27879
- return Number(this.markCaptureBacklogOwedStmt.run({ before }).changes);
27880
- }
27881
- /** Record delivery. Called only AFTER the far side has accepted the rows. */
27882
- markSynced(ids, atMs) {
27883
- this.stampAll(ids, atMs);
27884
- }
27885
- /**
27886
- * Record that a row will never be sent.
27887
- *
27888
- * Reserved for a local defect — a row that cannot be rebuilt into a valid
27889
- * payload. A row that merely failed to reach the deployment stays NULL, so it
27890
- * is retried; marking those would turn one outage into permanent data loss.
27891
- */
27892
- markSkipped(ids) {
27893
- this.stampAll(ids, SKIPPED);
27894
- }
27895
- eachInTransaction(ids, run) {
27896
- if (ids.length === 0) return;
27897
- withTransaction(
27898
- this.db,
27899
- () => {
27900
- for (const id of ids) run(id);
27901
- },
27902
- "IMMEDIATE"
27903
- );
27904
- }
27905
- stampAll(ids, value) {
27906
- if (ids.length === 0) return;
27907
- withTransaction(
27908
- this.db,
27909
- () => {
27910
- for (const id of ids) this.stampStmt.run({ at: value, id });
27911
- },
27912
- "IMMEDIATE"
27913
- );
27914
- }
27915
- /**
27916
- * Claim rows as in-flight.
27917
- *
27918
- * Advisory in exactly the sense the lease is: it records that a send is in
27919
- * progress so a surface can say so, and a lost claim costs a row showing as
27920
- * queued while it is actually being sent. It is not exclusion — the far side
27921
- * settles a duplicate on the row id.
27922
- */
27923
- claimRows(ids, atMs) {
27924
- this.eachInTransaction(ids, (id) => this.claimRowStmt.run({ at: atMs, id }));
27925
- }
27926
- /** Give back a claim without settling — the send failed, the row is queued again. */
27927
- releaseRows(ids) {
27928
- this.eachInTransaction(ids, (id) => this.releaseRowStmt.run({ id }));
27929
- }
27930
- /**
27931
- * Clear claims older than `staleBefore`, and report how many were cleared.
27932
- *
27933
- * A process killed between claiming and settling leaves rows claimed with
27934
- * nothing left to settle them. Without this they read as "sending" for ever.
27935
- */
27936
- releaseStaleClaims(staleBefore) {
27937
- return Number(this.releaseStaleClaimsStmt.run({ staleBefore }).changes);
27938
- }
27939
- /**
27940
- * Every tracked row in exactly one delivery state.
27941
- *
27942
- * Takes no boundary on purpose. The boundary answers "what should the drain
27943
- * pick up now", which is a different question from "what state is this row
27944
- * in" — and a machine that has never attached has no boundary to pass, so
27945
- * requiring one would force a caller to invent one and report the whole store
27946
- * as queued.
27947
- */
27948
- partition() {
27949
- const row = getRow(this.partitionStmt, {});
27950
- return {
27951
- queued: row?.queued ?? 0,
27952
- inProgress: row?.inProgress ?? 0,
27953
- synced: row?.synced ?? 0,
27954
- failed: row?.failed ?? 0,
27955
- total: row?.total ?? 0
27956
- };
27957
- }
27958
- /** `pending` counts only what is inside the backlog; sent and skipped are totals. */
27959
- counts(before) {
27960
- const row = getRow(
27961
- this.countsStmt,
27962
- { before }
27963
- );
27964
- const captures = getRow(this.captureSkipCountStmt);
27965
- return {
27966
- pending: row?.pending ?? 0,
27967
- sent: row?.sent ?? 0,
27968
- skipped: row?.skipped ?? 0,
27969
- capturesSkipped: captures?.skipped ?? 0
27970
- };
27971
- }
27972
- /**
27973
- * The deployment the current stamps were made against, and where its backlog
27974
- * ends.
27975
- *
27976
- * READ-ONLY. An absent row reads as an absent deployment, which is what a
27977
- * machine that has never drained is — and every writer below seeds the row
27978
- * before it needs one, so nothing depends on this creating it. Keeping the
27979
- * write off the gate path matters because the gate runs on every pass while a
27980
- * write has to take the database's write lock.
27981
- */
27982
- deployment() {
27983
- const row = getRow(
27984
- this.fingerprintStmt
27985
- );
27986
- return {
27987
- fingerprint: row?.fingerprint ?? void 0,
27988
- backlogBefore: row?.backlogBefore ?? void 0
27989
- };
27990
- }
27991
- /**
27992
- * Point the ledger at a different deployment, discarding what it recorded
27993
- * about the previous one.
27994
- *
27995
- * Delivery is a fact about ONE recipient: rows sent to the deployment a
27996
- * machine has just left are undelivered as far as the new one is concerned.
27997
- * All four in one transaction, so a crash between them cannot leave stamps
27998
- * attributed to the wrong deployment, a boundary that belongs to another, or
27999
- * a disown with no re-mark to follow it.
28000
- *
28001
- * The boundary is written HERE and only here, which is what freezes it: a
28002
- * re-attach to the SAME deployment (a key rotation) leaves the fingerprint
28003
- * unchanged, so this never runs and the backlog does not widen back over rows
28004
- * the live path has since delivered.
28005
- *
28006
- * `backfillCapturesBefore` is the caller's OWN "now" at the instant a human
28007
- * granted existing-history consent for the deployment this call is arming —
28008
- * a DIFFERENT instant from `backlogBefore`: the re-mark boundary is the GRANT
28009
- * instant, `backlogBefore` is the ATTACH instant, and the two can be far
28010
- * apart. Passed only when that grant is valid, since this method has no way
28011
- * to check consent itself and must not mark a row owed for a machine that
28012
- * never agreed to it. Applied AFTER the disown above, in the SAME
28013
- * transaction: what the disown clears is every marker below `backlogBefore`,
28014
- * which includes this deployment's OWN pre-attach rows — `aka attach` calls
28015
- * `seedCaptureBacklogOwed` at the attach instant, so every row it marks sits
28016
- * on the cleared side of that bound — and the re-mark in the same
28017
- * transaction is what puts those rows back. A crash between the two cannot
28018
- * strand the ledger disowned with nothing re-marked — the transaction either
28019
- * lands whole or not at all, and a fingerprint mismatch that has not yet
28020
- * committed re-enters this method on the very next pass. Omit it (the
28021
- * structural-only tests do) to exercise the disown in isolation.
28022
- *
28023
- * The disown is bounded by `backlogBefore`, which is what keeps it from
28024
- * touching a marker the NEW deployment's OWN live path has already set: B's
28025
- * live path can mark a capture owed from the moment `aka attach` writes the
28026
- * descriptor, before the drain's first pass ever reaches this method, and
28027
- * such a row sits at or after the bound rather than below it. What keeps the
28028
- * disown from eating THIS SAME CALL's own re-mark is the order, not the
28029
- * bound — disown runs first, re-mark second, both inside the one
28030
- * transaction above.
28031
- */
28032
- rearmFor(fingerprint, backlogBefore, backfillCapturesBefore) {
28033
- this.ensureRowStmt.run();
28034
- withTransaction(
28035
- this.db,
28036
- () => {
28037
- const previous = getRow(this.fingerprintStmt)?.fingerprint;
28038
- this.rearmStmt.run();
28039
- if (previous !== null && previous !== void 0 && previous !== fingerprint) {
28040
- this.disownCapturesStmt.run({ attachedAt: backlogBefore });
28041
- }
28042
- if (backfillCapturesBefore !== void 0) {
28043
- this.markCaptureBacklogOwedStmt.run({ before: backfillCapturesBefore });
28044
- }
28045
- this.setFingerprintStmt.run({ fingerprint, backlogBefore });
28046
- },
28047
- "IMMEDIATE"
28048
- );
28049
- }
28050
- /**
28051
- * End the attached period: hand its rows to the live path, and release the
28052
- * boundary so the next attachment can freeze a new one.
28053
- *
28054
- * WITHOUT THIS, a detach and a re-attach to the same deployment leave a window
28055
- * nothing delivers. The fingerprint is unchanged, so the boundary is never
28056
- * re-frozen and stays at the FIRST attachment — while nothing forwards at all
28057
- * during the detached period, because the machine is not attached. Rows
28058
- * recorded in that window sit after the boundary and before the re-attach, so
28059
- * neither path takes them, and the pending count reports none outstanding.
28060
- *
28061
- * Stamping the attached window is not a claim that every one of those rows
28062
- * reached the deployment — the live path drops on failure and says so
28063
- * elsewhere. It records that they were ITS to deliver, which is exactly the
28064
- * status quo: they sit outside the frozen boundary today and are equally never
28065
- * re-sent. Making it explicit is what lets the boundary move.
28066
- *
28067
- * ONE TRANSACTION, so a crash cannot release the boundary while leaving the
28068
- * window unstamped — that half-state would re-send the whole attached period
28069
- * on the next attach, which is the failure the boundary exists to prevent.
28070
- */
28071
- closeAttachedWindow(attachedAtMs, atMs) {
28072
- this.ensureRowStmt.run();
28073
- withTransaction(
28074
- this.db,
28075
- () => {
28076
- const row = getRow(this.fingerprintStmt);
28077
- const from = row?.backlogBefore ?? attachedAtMs;
28078
- this.closeWindowStmt.run({ at: atMs, attachedAt: from });
28079
- this.releaseBoundaryStmt.run();
28080
- },
28081
- "IMMEDIATE"
28082
- );
28083
- }
28084
- /**
28085
- * Freeze a boundary for the deployment already on file, KEEPING the stamps.
28086
- *
28087
- * The re-attach half of the above. Distinct from `rearmFor`, which is for a
28088
- * different deployment and therefore discards what was delivered to the old
28089
- * one: here the recipient is the same, so everything already sent to it stays
28090
- * sent.
28091
- */
28092
- freezeBoundary(backlogBefore) {
28093
- this.ensureRowStmt.run();
28094
- this.freezeBoundaryStmt.run({ backlogBefore });
28095
- }
28096
- /** Take the claim, or report that someone live already holds it. */
28097
- claim(pid, host, nowMs, staleAfterMs) {
28098
- this.ensureRowStmt.run();
28099
- let taken = false;
28100
- withTransaction(
28101
- this.db,
28102
- () => {
28103
- const result = this.claimStmt.run({
28104
- pid,
28105
- host,
28106
- now: nowMs,
28107
- staleBefore: nowMs - staleAfterMs
28108
- });
28109
- taken = result.changes === 1;
28110
- },
28111
- "IMMEDIATE"
28112
- );
28113
- return taken;
28114
- }
28115
- /** Say the holder is still alive. A no-op once the claim has moved on. */
28116
- heartbeat(pid, nowMs) {
28117
- this.heartbeatStmt.run({ now: nowMs, pid });
28118
- }
28119
- /** Give the claim up. Scoped to this holder, so a taken-over claim is left be. */
28120
- release(pid) {
28121
- this.releaseStmt.run({ pid });
28122
- }
28123
- /** Who holds the claim, if anyone. Read-only, for the same reason as above. */
28124
- lease() {
28125
- return getRow(this.leaseStmt);
28126
- }
28127
- };
28128
-
28129
28991
  // ../../packages/persistence/src/repositories/inspection-definitions.ts
28130
28992
  var SqliteInspectionDefinitionsRepository = class {
28131
28993
  constructor(db) {
@@ -28352,6 +29214,7 @@ function overlayManagedSettings(settings, managed, now = () => /* @__PURE__ */ n
28352
29214
  if (values.vaultInlineReveal !== void 0) merged.vaultInlineReveal = values.vaultInlineReveal;
28353
29215
  if (values.dataSharesInPlace !== void 0) merged.dataSharesInPlace = values.dataSharesInPlace;
28354
29216
  if (values.redactFallback !== void 0) merged.redactFallback = values.redactFallback;
29217
+ if (values.bodyRetention !== void 0) merged.bodyRetention = values.bodyRetention;
28355
29218
  if (values.vaultConsent !== void 0) {
28356
29219
  merged.vaultConsent = values.vaultConsent ? (
28357
29220
  // Keep an existing valid grant so its acknowledgedAt survives; mint one
@@ -30859,7 +31722,7 @@ var SqliteSecurityRepository = class {
30859
31722
  ELSE 0
30860
31723
  END) AS open_at_rest
30861
31724
  FROM inspection_findings f
30862
- JOIN audit_events e ON e.id = f.audit_event_id
31725
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
30863
31726
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
30864
31727
  LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
30865
31728
  ON latest.finding_key = f.finding_key
@@ -31085,7 +31948,7 @@ var SqliteSecurityRepository = class {
31085
31948
  this.db.prepare(
31086
31949
  `SELECT e.repo AS repo, count(*) AS c
31087
31950
  FROM inspection_findings f
31088
- JOIN audit_events e ON e.id = f.audit_event_id
31951
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31089
31952
  WHERE e.started_at >= :from AND e.started_at < :to
31090
31953
  AND e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
31091
31954
  AND e.repo IS NOT NULL
@@ -31209,7 +32072,7 @@ var SqliteSecurityRepository = class {
31209
32072
  d.severity AS severity,
31210
32073
  COUNT(*) AS count
31211
32074
  FROM inspection_findings f
31212
- JOIN audit_events e ON e.id = f.audit_event_id
32075
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31213
32076
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
31214
32077
  LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
31215
32078
  ON latest.finding_key = f.finding_key
@@ -31244,7 +32107,7 @@ var SqliteSecurityRepository = class {
31244
32107
  `SELECT e.started_at AS occurred_at, d.severity AS severity, f.action_taken AS action_taken,
31245
32108
  d.rule_id AS rule_id, d.category AS category
31246
32109
  FROM inspection_findings f
31247
- JOIN audit_events e ON e.id = f.audit_event_id
32110
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31248
32111
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
31249
32112
  WHERE e.started_at >= :from AND e.started_at < :to
31250
32113
  AND e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
@@ -32085,6 +32948,7 @@ function openWithPragmas(file2) {
32085
32948
  db.exec("PRAGMA journal_mode = WAL");
32086
32949
  db.exec("PRAGMA busy_timeout = 2000");
32087
32950
  db.exec("PRAGMA foreign_keys = ON");
32951
+ registerSqlFunctions(db);
32088
32952
  } catch (err) {
32089
32953
  closeQuietly(db);
32090
32954
  throw err;
@@ -32114,7 +32978,7 @@ function backupLegacyStore(db, file2) {
32114
32978
  discardStore(file2, backup);
32115
32979
  return backup;
32116
32980
  }
32117
- function openAndInitialize(file2, base) {
32981
+ function openAndInitialize(file2, base, skipTags) {
32118
32982
  let db = openWithPragmas(file2);
32119
32983
  try {
32120
32984
  if (isForeignSqliteLineage(db)) {
@@ -32124,7 +32988,7 @@ function openAndInitialize(file2, base) {
32124
32988
  `Detected an older, incompatible (tenant-bearing) ${DB_FILENAME}; backed it up to ${backup} and created a fresh store.`
32125
32989
  );
32126
32990
  }
32127
- applyMigrations(db, file2);
32991
+ applyMigrations(db, file2, { skipTags });
32128
32992
  tightenPerms(file2);
32129
32993
  const policies = new SqlitePoliciesRepository(db);
32130
32994
  const installedPacks = new SqliteInstalledPacksRepository(db, base);
@@ -32139,6 +33003,7 @@ function openAndInitialize(file2, base) {
32139
33003
  exceptions: new SqliteExceptionsRepository(db),
32140
33004
  resolutions: new SqliteResolutionsRepository(db),
32141
33005
  ruleProbeCache: new SqliteRuleProbeCacheRepository(db),
33006
+ bodyRetention: new SqliteBodyRetentionRepository(db),
32142
33007
  security: new SqliteSecurityRepository(db),
32143
33008
  detections: new SqliteDetectionsRepository(db),
32144
33009
  shares: new SqliteSharesRepository(db),
@@ -32149,6 +33014,7 @@ function openAndInitialize(file2, base) {
32149
33014
  activity: new SqliteActivityRepository(db),
32150
33015
  sourceProject: new SqliteSourceProjectRepository(db),
32151
33016
  auditEvents: new SqliteAuditEventsRepository(db),
33017
+ captureStatus: new SqliteCaptureStatusRepository(db),
32152
33018
  classifiedData: new SqliteClassifiedDataRepository(db),
32153
33019
  inspectionDefinitions: new SqliteInspectionDefinitionsRepository(db),
32154
33020
  inspectionFindings: new SqliteInspectionFindingsRepository(db),
@@ -32161,7 +33027,8 @@ function openAndInitialize(file2, base) {
32161
33027
  throw err;
32162
33028
  }
32163
33029
  }
32164
- function openLocalDatabase(dir) {
33030
+ var DEFERRED_TAGS = new Set(DEFERRED_MIGRATION_TAGS);
33031
+ function openLocalDatabase(dir, options = {}) {
32165
33032
  ensureDataDirSync(dir);
32166
33033
  const file2 = join7(dir, DB_FILENAME);
32167
33034
  reapStalePartials(file2);
@@ -32173,6 +33040,7 @@ function openLocalDatabase(dir) {
32173
33040
  installedPacks,
32174
33041
  scanLedger,
32175
33042
  historySync,
33043
+ bodyRetention,
32176
33044
  secretVault,
32177
33045
  exceptions,
32178
33046
  resolutions,
@@ -32187,6 +33055,7 @@ function openLocalDatabase(dir) {
32187
33055
  activity,
32188
33056
  sourceProject,
32189
33057
  auditEvents,
33058
+ captureStatus,
32190
33059
  classifiedData,
32191
33060
  inspectionDefinitions,
32192
33061
  inspectionFindings,
@@ -32196,7 +33065,8 @@ function openLocalDatabase(dir) {
32196
33065
  // `dir` is always `<base>/data` — every caller resolves it through
32197
33066
  // `dataDir()` — so its parent is the `~/.aka` base the layout splits into
32198
33067
  // settings/ and data/, and the pack-policy floor needs both halves.
32199
- dirname2(dir)
33068
+ dirname2(dir),
33069
+ options.applyDeferredMigrations === true ? void 0 : DEFERRED_TAGS
32200
33070
  );
32201
33071
  function captureRowId(event) {
32202
33072
  return captureId(
@@ -32389,6 +33259,7 @@ function openLocalDatabase(dir) {
32389
33259
  installedPacks,
32390
33260
  scanLedger,
32391
33261
  historySync,
33262
+ bodyRetention,
32392
33263
  secretVault,
32393
33264
  exceptions,
32394
33265
  resolutions,
@@ -32402,6 +33273,7 @@ function openLocalDatabase(dir) {
32402
33273
  activity,
32403
33274
  sourceProject,
32404
33275
  auditEvents,
33276
+ captureStatus,
32405
33277
  classifiedData,
32406
33278
  inspectionDefinitions,
32407
33279
  inspectionFindings,
@@ -32429,6 +33301,7 @@ function openLocalDatabase(dir) {
32429
33301
 
32430
33302
  // ../../packages/persistence/src/egress-wire.ts
32431
33303
  import { createHash as createHash3 } from "crypto";
33304
+ var SLASH = "/".charCodeAt(0);
32432
33305
 
32433
33306
  // ../../packages/persistence/src/exception-policy.ts
32434
33307
  var UserGrantPolicyProvider = class {
@@ -32576,18 +33449,26 @@ function fingerprintValue(key, raw) {
32576
33449
  return createHmac("sha256", key.material).update(raw, "utf8").digest("hex");
32577
33450
  }
32578
33451
 
33452
+ // ../../packages/persistence/src/forward-health.ts
33453
+ import { readFileSync as readFileSync7 } from "fs";
33454
+ import { join as join9 } from "path";
33455
+
32579
33456
  // ../../packages/persistence/src/history-backfill.ts
32580
33457
  import { existsSync as existsSync4 } from "fs";
32581
- import { join as join9 } from "path";
33458
+ import { join as join10 } from "path";
32582
33459
 
32583
33460
  // ../../packages/persistence/src/history-preview.ts
32584
33461
  import { existsSync as existsSync5 } from "fs";
32585
- import { join as join10 } from "path";
33462
+ import { join as join11 } from "path";
32586
33463
  import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
32587
33464
 
33465
+ // ../../packages/persistence/src/history-sync-state.ts
33466
+ import { readFileSync as readFileSync8 } from "fs";
33467
+ import { join as join12 } from "path";
33468
+
32588
33469
  // ../../packages/persistence/src/store-symlinks.ts
32589
33470
  import { existsSync as existsSync6, lstatSync as lstatSync3, readlinkSync, realpathSync, statSync as statSync4 } from "fs";
32590
- import { dirname as dirname3, join as join11, resolve } from "path";
33471
+ import { dirname as dirname3, join as join13, resolve } from "path";
32591
33472
 
32592
33473
  // ../../packages/persistence/src/vault/crypto.ts
32593
33474
  import {
@@ -32700,8 +33581,8 @@ function formatPointer(category, keyVersion, pointerId, tag) {
32700
33581
  // ../../packages/persistence/src/vault/key-provider.ts
32701
33582
  import { execFileSync } from "child_process";
32702
33583
  import { randomBytes as randomBytes2 } from "crypto";
32703
- import { chmodSync as chmodSync3, readFileSync as readFileSync7, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
32704
- import { join as join12 } from "path";
33584
+ import { chmodSync as chmodSync3, readFileSync as readFileSync9, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
33585
+ import { join as join14 } from "path";
32705
33586
  var VAULT_OCCUPANT_REASON = {
32706
33587
  symlink: "the path is a symlink; remove it so a keyring can be created",
32707
33588
  gone: "the path was occupied but holds no keyring (removed while it was being created)",
@@ -32800,7 +33681,7 @@ function claimRotationLock(lock, owner) {
32800
33681
  throw asError(err);
32801
33682
  }
32802
33683
  try {
32803
- writeFileSync3(join12(lock, LOCK_OWNER_FILE), `${owner}
33684
+ writeFileSync3(join14(lock, LOCK_OWNER_FILE), `${owner}
32804
33685
  `, { mode: DATA_FILE_MODE });
32805
33686
  return true;
32806
33687
  } catch (err) {
@@ -32809,7 +33690,7 @@ function claimRotationLock(lock, owner) {
32809
33690
  }
32810
33691
  }
32811
33692
  function acquireRotationLock(keysDir2) {
32812
- const lock = join12(keysDir2, `${VAULT_KEY_FILENAME}.lock`);
33693
+ const lock = join14(keysDir2, `${VAULT_KEY_FILENAME}.lock`);
32813
33694
  const owner = randomBytes2(16).toString("hex");
32814
33695
  if (claimRotationLock(lock, owner)) return { lock, owner };
32815
33696
  let held;
@@ -32836,7 +33717,7 @@ function acquireRotationLock(keysDir2) {
32836
33717
  }
32837
33718
  function releaseRotationLock(lease) {
32838
33719
  try {
32839
- if (readFileSync7(join12(lease.lock, LOCK_OWNER_FILE), "utf8").trim() !== lease.owner) return;
33720
+ if (readFileSync9(join14(lease.lock, LOCK_OWNER_FILE), "utf8").trim() !== lease.owner) return;
32840
33721
  } catch {
32841
33722
  return;
32842
33723
  }
@@ -32857,7 +33738,7 @@ var FileKeyProvider = class {
32857
33738
  this.#keysDir = keysDir2;
32858
33739
  }
32859
33740
  get filePath() {
32860
- return join12(this.#keysDir, VAULT_KEY_FILENAME);
33741
+ return join14(this.#keysDir, VAULT_KEY_FILENAME);
32861
33742
  }
32862
33743
  loadOrCreate() {
32863
33744
  return asAsync(() => {
@@ -32887,7 +33768,7 @@ var FileKeyProvider = class {
32887
33768
  #read() {
32888
33769
  let raw;
32889
33770
  try {
32890
- raw = readFileSync7(this.filePath, "utf8");
33771
+ raw = readFileSync9(this.filePath, "utf8");
32891
33772
  } catch (err) {
32892
33773
  if (err.code === "ENOENT") return null;
32893
33774
  throw err instanceof Error ? err : new Error(String(err));
@@ -33523,7 +34404,7 @@ var SecretVault = class {
33523
34404
 
33524
34405
  // ../../packages/persistence/src/warn-era-cap.ts
33525
34406
  import { existsSync as existsSync7, writeFileSync as writeFileSync4 } from "fs";
33526
- import { join as join13 } from "path";
34407
+ import { join as join15 } from "path";
33527
34408
 
33528
34409
  // ../../packages/plugin-sdk/src/provider-env.ts
33529
34410
  var DEFAULT_ANTHROPIC_HOST = "api.anthropic.com";
@@ -33577,7 +34458,7 @@ function resolveProvider() {
33577
34458
  function loadConfig(base = defaultDataDir(), resolveProviderFn = resolveProvider) {
33578
34459
  try {
33579
34460
  ensureLayoutDirSync(base);
33580
- const settingsFile = join14(settingsDir(base), "settings.json");
34461
+ const settingsFile = join16(settingsDir(base), "settings.json");
33581
34462
  if (existsSync8(settingsFile)) tightenFile(settingsFile);
33582
34463
  } catch {
33583
34464
  }
@@ -33601,9 +34482,9 @@ function resolveProviderSafe(resolveProviderFn) {
33601
34482
  }
33602
34483
 
33603
34484
  // ../../packages/plugin-sdk/src/config-inventory.ts
33604
- import { readdirSync as readdirSync2, readFileSync as readFileSync9, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
34485
+ import { readdirSync as readdirSync2, readFileSync as readFileSync11, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
33605
34486
  import { homedir as homedir2 } from "os";
33606
- import { basename as basename3, join as join16 } from "path";
34487
+ import { basename as basename3, join as join18 } from "path";
33607
34488
 
33608
34489
  // ../../packages/detections/src/egress/registry.ts
33609
34490
  var EXTRACTOR_VERSION = "1";
@@ -34512,6 +35393,56 @@ var CONFIG_POSTURE_RULES = [
34512
35393
  }
34513
35394
  ];
34514
35395
 
35396
+ // ../../packages/detections/src/posture/web-capture-posture.ts
35397
+ var RULE_VERSION2 = "1";
35398
+ var DRIFT_MIN_PARSE_FAILURES = 2;
35399
+ var WEB_CAPTURE_DRIFT_STATES = /* @__PURE__ */ new Set([
35400
+ "blind",
35401
+ "degraded"
35402
+ ]);
35403
+ var WEB_CAPTURE_DRIFT_RULE = {
35404
+ ruleId: "web-capture-drift",
35405
+ version: RULE_VERSION2,
35406
+ name: "Web chat capture is not reading the site",
35407
+ category: "config",
35408
+ severity: "medium",
35409
+ definition: JSON.stringify({
35410
+ kind: "web-capture-drift",
35411
+ states: [...WEB_CAPTURE_DRIFT_STATES],
35412
+ minParseFailures: DRIFT_MIN_PARSE_FAILURES
35413
+ })
35414
+ };
35415
+ var STATIC_COPY = {
35416
+ active: { headline: "turns are being observed on this site" },
35417
+ unreported: {
35418
+ // Says "recently" rather than "yet": the store read is bounded to
35419
+ // CAPTURE_STATUS_RECENCY_MS, so this state covers a site nothing has ever
35420
+ // reported for AND one whose last report has aged out. The two are the
35421
+ // same fact to a reader — nobody has confirmed anything lately — and the
35422
+ // copy may not claim the stronger of them.
35423
+ headline: `no report in the last ${String(CAPTURE_STATUS_RECENCY_DAYS)} days \u2014 open the site in Chrome with the extension loaded`
35424
+ },
35425
+ standby: {
35426
+ headline: "this build declares no endpoints for the site, so nothing is observed yet"
35427
+ },
35428
+ unpatched: {
35429
+ // Says what the flags say and no more. `patched` is false both for a tap
35430
+ // that installed and hooked neither transport and for one that never ran
35431
+ // at all — a page reports the same status either way, so the copy may not
35432
+ // assert one of them.
35433
+ headline: "the page tap captured neither fetch nor XHR \u2014 it may not have installed; reload the extension at chrome://extensions"
35434
+ },
35435
+ idle: { headline: "watching; no turn has been observed yet" },
35436
+ blind: {
35437
+ headline: "messages were sent in the page that the network capture never saw",
35438
+ remediation: "reload the tab. If it persists after `aka update` and reloading the extension at chrome://extensions, the site's send path has changed and needs a new extension build."
35439
+ },
35440
+ degraded: {
35441
+ headline: "the site's payloads no longer carry the fields the extension reads",
35442
+ remediation: "run `aka update`, then reload the extension at chrome://extensions. If it stays degraded after an update, the site's contract has changed and needs a new extension build."
35443
+ }
35444
+ };
35445
+
34515
35446
  // ../../packages/detections/src/security/redos-probe.ts
34516
35447
  var BUDGET_MS = 100;
34517
35448
  var EXPONENTIAL_UNITS = [
@@ -36561,8 +37492,8 @@ function registerBundledPacks() {
36561
37492
  }
36562
37493
 
36563
37494
  // ../../packages/plugin-sdk/src/repo.ts
36564
- import { existsSync as existsSync9, readFileSync as readFileSync8, statSync as statSync6 } from "fs";
36565
- import { basename as basename2, dirname as dirname4, isAbsolute, join as join15, sep as sep2 } from "path";
37495
+ import { existsSync as existsSync9, readFileSync as readFileSync10, statSync as statSync6 } from "fs";
37496
+ import { basename as basename2, dirname as dirname4, isAbsolute, join as join17, sep as sep2 } from "path";
36566
37497
 
36567
37498
  // ../../packages/plugin-sdk/src/events.ts
36568
37499
  import { createHash as createHash5, randomUUID as randomUUID13 } from "crypto";
@@ -36573,8 +37504,8 @@ import { fileURLToPath } from "url";
36573
37504
  import { Worker } from "worker_threads";
36574
37505
 
36575
37506
  // ../../packages/plugin-sdk/src/host-floor.ts
36576
- import { readFileSync as readFileSync11 } from "fs";
36577
- import { join as join18 } from "path";
37507
+ import { readFileSync as readFileSync13 } from "fs";
37508
+ import { join as join20 } from "path";
36578
37509
 
36579
37510
  // ../../packages/plugin-sdk/src/model-governance.ts
36580
37511
  import {
@@ -36582,11 +37513,11 @@ import {
36582
37513
  fstatSync,
36583
37514
  mkdirSync as mkdirSync2,
36584
37515
  openSync as openSync2,
36585
- readFileSync as readFileSync10,
37516
+ readFileSync as readFileSync12,
36586
37517
  readSync,
36587
37518
  writeFileSync as writeFileSync5
36588
37519
  } from "fs";
36589
- import { join as join17 } from "path";
37520
+ import { join as join19 } from "path";
36590
37521
  var TAIL_BYTES = 256 * 1024;
36591
37522
 
36592
37523
  // ../../packages/plugin-sdk/src/host-floor.ts
@@ -36609,15 +37540,15 @@ var HOST_FLOORS = {
36609
37540
 
36610
37541
  // ../../packages/plugin-sdk/src/ignore-layers.ts
36611
37542
  var import_ignore = __toESM(require_ignore(), 1);
36612
- import { readFileSync as readFileSync12 } from "fs";
36613
- import { join as join19 } from "path";
37543
+ import { readFileSync as readFileSync14 } from "fs";
37544
+ import { join as join21 } from "path";
36614
37545
 
36615
37546
  // ../../packages/plugin-sdk/src/inventory-resolver.ts
36616
37547
  import { arch, hostname as hostname4, platform, release } from "os";
36617
37548
 
36618
37549
  // ../../packages/plugin-sdk/src/nudge.ts
36619
- import { mkdirSync as mkdirSync3, readFileSync as readFileSync13, writeFileSync as writeFileSync6 } from "fs";
36620
- import { join as join20 } from "path";
37550
+ import { mkdirSync as mkdirSync3, readFileSync as readFileSync15, writeFileSync as writeFileSync6 } from "fs";
37551
+ import { join as join22 } from "path";
36621
37552
 
36622
37553
  // ../../packages/plugin-sdk/src/paths.ts
36623
37554
  import { readdirSync as readdirSync3, realpathSync as realpathSync3 } from "fs";
@@ -36625,7 +37556,7 @@ import { basename as basename4, dirname as dirname5, sep as sep3 } from "path";
36625
37556
 
36626
37557
  // ../../packages/plugin-sdk/src/project-files.ts
36627
37558
  import { existsSync as existsSync11, readdirSync as readdirSync4 } from "fs";
36628
- import { basename as basename5, join as join21 } from "path";
37559
+ import { basename as basename5, join as join23 } from "path";
36629
37560
 
36630
37561
  // ../../packages/plugin-sdk/src/provider-env-antigravity.ts
36631
37562
  var optionalBaseUrl2 = external_exports.preprocess((v) => {
@@ -36661,7 +37592,7 @@ var THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1e3;
36661
37592
 
36662
37593
  // ../../packages/plugin-sdk/src/throttle.ts
36663
37594
  import { mkdirSync as mkdirSync4, statSync as statSync8, writeFileSync as writeFileSync7 } from "fs";
36664
- import { join as join22 } from "path";
37595
+ import { join as join24 } from "path";
36665
37596
 
36666
37597
  // ../../packages/plugin-sdk/src/tokenize.ts
36667
37598
  function redactedPlaceholder(category) {
@@ -36991,13 +37922,13 @@ function describePointerSafe(token) {
36991
37922
  import {
36992
37923
  mkdirSync as mkdirSync5,
36993
37924
  readdirSync as readdirSync5,
36994
- readFileSync as readFileSync14,
37925
+ readFileSync as readFileSync16,
36995
37926
  renameSync as renameSync5,
36996
37927
  rmSync as rmSync7,
36997
37928
  statSync as statSync9,
36998
37929
  writeFileSync as writeFileSync8
36999
37930
  } from "fs";
37000
- import { dirname as dirname6, join as join23 } from "path";
37931
+ import { dirname as dirname6, join as join25 } from "path";
37001
37932
  var EMPTY_CARRY = Object.freeze({
37002
37933
  tail: "",
37003
37934
  fence: null,
@@ -37194,7 +38125,7 @@ var CARRY_FILE_PREFIX = "display-carry";
37194
38125
  var STALE_CARRY_MS = 15 * 60 * 1e3;
37195
38126
  function carryFilePath(dataDir2, sessionId) {
37196
38127
  const safe = sessionId.replace(/[^A-Za-z0-9_-]/g, "_").slice(0, 80);
37197
- return join23(dataDir2, `${CARRY_FILE_PREFIX}-${safe === "" ? "session" : safe}.json`);
38128
+ return join25(dataDir2, `${CARRY_FILE_PREFIX}-${safe === "" ? "session" : safe}.json`);
37198
38129
  }
37199
38130
  function parseFence(value) {
37200
38131
  if (typeof value !== "object" || value === null) return null;
@@ -37205,7 +38136,7 @@ function parseFence(value) {
37205
38136
  }
37206
38137
  function loadCarry(file2, keys) {
37207
38138
  try {
37208
- const parsed = JSON.parse(readFileSync14(file2, "utf8"));
38139
+ const parsed = JSON.parse(readFileSync16(file2, "utf8"));
37209
38140
  if (typeof parsed !== "object" || parsed === null) return EMPTY_CARRY;
37210
38141
  const record2 = parsed;
37211
38142
  const revealedCount = record2.messageKey === keys.messageKey && typeof record2.revealedCount === "number" && Number.isFinite(record2.revealedCount) ? record2.revealedCount : 0;
@@ -37258,7 +38189,7 @@ function removeStaleCarryFiles(dir, keep) {
37258
38189
  const cutoff = Date.now() - STALE_CARRY_MS;
37259
38190
  for (const name of readdirSync5(dir)) {
37260
38191
  if (!name.startsWith(CARRY_FILE_PREFIX) || !name.endsWith(".json")) continue;
37261
- const path = join23(dir, name);
38192
+ const path = join25(dir, name);
37262
38193
  if (path === keep) continue;
37263
38194
  try {
37264
38195
  if (statSync9(path).mtimeMs < cutoff) rmSync7(path, { force: true });
@@ -37289,7 +38220,7 @@ function finalizeCarry(file2, keys, carry) {
37289
38220
  }
37290
38221
  let owned = true;
37291
38222
  try {
37292
- const parsed = JSON.parse(readFileSync14(file2, "utf8"));
38223
+ const parsed = JSON.parse(readFileSync16(file2, "utf8"));
37293
38224
  if (typeof parsed === "object" && parsed !== null) {
37294
38225
  const record2 = parsed;
37295
38226
  owned = record2.blockKey === keys.blockKey || record2.messageKey === keys.messageKey;