@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 SLASH2 = "/";
53
+ var SLASH3 = "/";
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(SLASH2).filter(Boolean);
425
+ const slices = path.split(SLASH3).filter(Boolean);
426
426
  slices.pop();
427
427
  if (slices.length) {
428
428
  const parent = this._t(
429
- slices.join(SLASH2) + SLASH2,
429
+ slices.join(SLASH3) + SLASH3,
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(SLASH2).filter(Boolean);
445
+ slices = path.split(SLASH3).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(SLASH2) + SLASH2,
452
+ slices.join(SLASH3) + SLASH3,
453
453
  cache,
454
454
  checkUnignored,
455
455
  slices
@@ -502,6 +502,14 @@ var ATTACHED_HISTORY_SYNC_STATE_FILENAME = "attached-history-sync.json";
502
502
  import { chmodSync as chmodSync2, lstatSync as lstatSync2, readFileSync, rmSync as rmSync3, statSync } from "fs";
503
503
  import { join as join2 } from "path";
504
504
 
505
+ // ../../packages/schema/src/drizzle/deferred-migrations.ts
506
+ var DEFERRED_MIGRATION_TAGS = [
507
+ "0031_audit_capture_by_time_index",
508
+ "0032_audit_capture_by_id_index",
509
+ "0033_audit_capture_location_index",
510
+ "0034_findings_read_indexes"
511
+ ];
512
+
505
513
  // ../../packages/schema/src/drizzle/sqlite-ddl.ts
506
514
  var SQLITE_MIGRATIONS = [
507
515
  {
@@ -619,6 +627,30 @@ var SQLITE_MIGRATIONS = [
619
627
  {
620
628
  tag: "0028_activity_session_probe_indexes",
621
629
  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"
630
+ },
631
+ {
632
+ tag: "0029_audit_capture_rollup_index",
633
+ 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');"
634
+ },
635
+ {
636
+ tag: "0030_audit_content_expiry",
637
+ 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;"
638
+ },
639
+ {
640
+ tag: "0031_audit_capture_by_time_index",
641
+ 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');"
642
+ },
643
+ {
644
+ tag: "0032_audit_capture_by_id_index",
645
+ 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');"
646
+ },
647
+ {
648
+ tag: "0033_audit_capture_location_index",
649
+ 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');"
650
+ },
651
+ {
652
+ tag: "0034_findings_read_indexes",
653
+ 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`);"
622
654
  }
623
655
  ];
624
656
 
@@ -20446,7 +20478,17 @@ var UNPRICEABLE_PROVIDERS = Object.freeze([
20446
20478
  "gateway",
20447
20479
  "unknown",
20448
20480
  "cli",
20449
- "api"
20481
+ "api",
20482
+ // The browser extension's native host records these as `llm_call.provider`
20483
+ // for a web-chat turn — the web tool id, deliberately never the vendor id
20484
+ // (`openai`/`anthropic`) the session root carries. Subscription traffic
20485
+ // burns rate-limit budget, not dollar credits, and listing them here is
20486
+ // what keeps that true structurally: a later maintainer who wants to price
20487
+ // web-chat traffic at API rates has to delete this entry first, and meet
20488
+ // the reason on the way, rather than quietly adding one to
20489
+ // PROVIDER_PLATFORM.
20490
+ "chatgpt",
20491
+ "claude-ai"
20450
20492
  ]);
20451
20493
  function platformForProvider(provider) {
20452
20494
  return PROVIDER_PLATFORM.get(provider.trim().toLowerCase()) ?? null;
@@ -20589,7 +20631,12 @@ var HARNESS = {
20589
20631
  ClaudeDesktop: "claudedesktop",
20590
20632
  ChatGpt: "chatgpt",
20591
20633
  ClaudeAi: "claudeai",
20592
- Api: "api"
20634
+ Api: "api",
20635
+ // Not a coding assistant a person drives — an in-process SDK embedded in an
20636
+ // application, so it has no IDE/CLI/desktop/web surface of its own. Carries
20637
+ // the same id as its SOURCE_TOOL counterpart, unlike every capture-side tool
20638
+ // whose wire spelling differs from its display spelling.
20639
+ AiTcSdk: "ai-tc-sdk"
20593
20640
  };
20594
20641
  var Harness = external_exports.enum(HARNESS).meta({ id: "Harness" });
20595
20642
  var SOURCE_TOOL = {
@@ -20605,9 +20652,15 @@ var SOURCE_TOOL = {
20605
20652
  // whose tool could not be identified both render through the read side's
20606
20653
  // miss path rather than as a harness of their own.
20607
20654
  Cli: "cli",
20608
- Unknown: "unknown"
20655
+ Unknown: "unknown",
20656
+ // The wire id an in-process, request-path SDK stamps on its own structural
20657
+ // rows (`request_decision`) — never a capture of prompt/response/tool text,
20658
+ // since the SDK sits in front of a model call rather than inside a coding
20659
+ // assistant's own hook contract.
20660
+ AiTcSdk: "ai-tc-sdk"
20609
20661
  };
20610
20662
  var SourceTool = external_exports.enum(SOURCE_TOOL).meta({ id: "SourceTool" });
20663
+ var WebSourceTool = SourceTool.extract(["ChatGpt", "ClaudeAi"]);
20611
20664
  var TOOL_TO_HARNESS = {
20612
20665
  [SOURCE_TOOL.ClaudeCode]: HARNESS.ClaudeCode,
20613
20666
  [SOURCE_TOOL.ClaudeDesktop]: HARNESS.ClaudeDesktop,
@@ -20616,7 +20669,12 @@ var TOOL_TO_HARNESS = {
20616
20669
  [SOURCE_TOOL.ChatGpt]: HARNESS.ChatGpt,
20617
20670
  [SOURCE_TOOL.Codex]: HARNESS.Codex,
20618
20671
  [SOURCE_TOOL.Antigravity]: HARNESS.Antigravity,
20619
- [SOURCE_TOOL.ClaudeAi]: HARNESS.ClaudeAi
20672
+ [SOURCE_TOOL.ClaudeAi]: HARNESS.ClaudeAi,
20673
+ // Wire and display id are the same string here, but the row still belongs:
20674
+ // both vocabularies carry the `AiTcSdk` member, and the join is exactly
20675
+ // their intersection — leaving a shared member out would read as an
20676
+ // uninstrumented tool on both surfaces, which this one is not.
20677
+ [SOURCE_TOOL.AiTcSdk]: HARNESS.AiTcSdk
20620
20678
  };
20621
20679
 
20622
20680
  // ../../packages/schema/src/zod/finding.ts
@@ -20650,7 +20708,8 @@ var FindingProvider = Harness.extract([
20650
20708
  "ClaudeAi",
20651
20709
  "Codex",
20652
20710
  "Antigravity",
20653
- "Api"
20711
+ "Api",
20712
+ "AiTcSdk"
20654
20713
  ]).meta({ id: "FindingProvider" });
20655
20714
  var FindingCategory = external_exports.enum([
20656
20715
  "secret",
@@ -20666,6 +20725,15 @@ var FindingCategory = external_exports.enum([
20666
20725
  ]).meta({ id: "FindingCategory" });
20667
20726
  var FindingOrigin = external_exports.enum(["in-flight", "at-rest"]).meta({ id: "FindingOrigin" });
20668
20727
  var FindingStatus = external_exports.enum(["open", "handled", "resolved", "dismissed"]).meta({ id: "FindingStatus" });
20728
+ var SyncFailureReason = external_exports.enum(["deployment_refused", "payload_invalid", "detached_undelivered"]).meta({ id: "SyncFailureReason" });
20729
+ var FindingDeliveryState = external_exports.enum(["sent", "queued", "not_sent", "never_offered", "local_scan"]).meta({ id: "FindingDeliveryState" });
20730
+ var FindingDelivery = external_exports.object({
20731
+ state: FindingDeliveryState,
20732
+ // The delivery time for `sent`; the failure time for `not_sent` when recorded.
20733
+ at: external_exports.iso.datetime().optional(),
20734
+ // Only on `not_sent`, and only when a known reason was recorded.
20735
+ reason: SyncFailureReason.optional()
20736
+ }).meta({ id: "FindingDelivery" });
20669
20737
  var ResolutionMethod = external_exports.enum([
20670
20738
  "enforced-in-flight",
20671
20739
  "fixed-at-source",
@@ -20722,7 +20790,10 @@ var FindingInstance = external_exports.object({
20722
20790
  // The session that event belongs to, when it has one — the seam a
20723
20791
  // per-instance "view session" link needs. Absent for events captured
20724
20792
  // outside a session.
20725
- sessionId: external_exports.string().optional()
20793
+ sessionId: external_exports.string().optional(),
20794
+ // The delivery state of the event above (see FindingDelivery). Optional so
20795
+ // readers that do not project it stay valid.
20796
+ delivery: FindingDelivery.optional()
20726
20797
  }).meta({ id: "FindingInstance" });
20727
20798
  var FindingGroup = external_exports.object({
20728
20799
  id: external_exports.string(),
@@ -20774,7 +20845,10 @@ var FindingFacets = external_exports.object({
20774
20845
  // Host tool (attributes.tool_name). Present only on the instance-level
20775
20846
  // reads, which can filter by it; the type-level read omits the dimension
20776
20847
  // because a group spans tools.
20777
- tool: external_exports.array(FindingFacetItem).optional()
20848
+ tool: external_exports.array(FindingFacetItem).optional(),
20849
+ // Delivery states (FindingDeliveryState). Present only on the
20850
+ // instance-level reads, like `tool`.
20851
+ deployment: external_exports.array(FindingFacetItem).optional()
20778
20852
  }).meta({ id: "FindingFacets" });
20779
20853
  var FindingTypeSummary = FindingGroup.omit({ instances: true, match: true }).meta({
20780
20854
  id: "FindingTypeSummary"
@@ -20885,6 +20959,8 @@ var ListFindingInstancesQuery = external_exports.object({
20885
20959
  // Exact host-tool names (attributes.tool_name, e.g. 'Bash'). A real filter,
20886
20960
  // where the free-text `q` can only match the rendered "via Bash" label.
20887
20961
  tool: external_exports.array(external_exports.string()).optional(),
20962
+ // The delivery state of each finding's event (see FindingDelivery).
20963
+ deployment: external_exports.array(FindingDeliveryState).optional(),
20888
20964
  // Exact repository / file-path matches, for the drill-down out of the
20889
20965
  // locations view. A row whose event carries no repo/file matches neither.
20890
20966
  repo: external_exports.string().optional(),
@@ -20905,6 +20981,10 @@ var ListFindingInstancesResponse = external_exports.object({
20905
20981
  items: external_exports.array(FindingInstanceDetail),
20906
20982
  nextCursor: external_exports.string().nullable()
20907
20983
  }).meta({ id: "ListFindingInstancesResponse" });
20984
+ var ListFindingInstancesPage = external_exports.object({
20985
+ items: external_exports.array(FindingInstanceDetail),
20986
+ nextCursor: external_exports.string().nullable()
20987
+ }).meta({ id: "ListFindingInstancesPage" });
20908
20988
  var FindingLocationSummary = external_exports.object({
20909
20989
  // Opaque, stable, minted from the pair by encodeLocationId. It exists
20910
20990
  // because a location's identity is two values and a URL param carries one:
@@ -20947,6 +21027,8 @@ var ListFindingLocationsQuery = external_exports.object({
20947
21027
  // instances that match, and folds its status from those.
20948
21028
  status: external_exports.array(FindingStatus).optional(),
20949
21029
  tool: external_exports.array(external_exports.string()).optional(),
21030
+ // The delivery state of each finding's event (see FindingDelivery).
21031
+ deployment: external_exports.array(FindingDeliveryState).optional(),
20950
21032
  q: external_exports.string().optional(),
20951
21033
  sessionId: external_exports.string().optional(),
20952
21034
  from: external_exports.iso.datetime().optional(),
@@ -21004,18 +21086,41 @@ var AuditEventType = external_exports.enum([
21004
21086
  // 'tool_call' is the reconciler's structural row for every call, while
21005
21087
  // 'tool_use' exists only where a hook enforced against the arguments.
21006
21088
  "tool_use",
21007
- // One row per model REFUSAL: a switch onto a prohibited model that was
21008
- // denied, or a turn refused because the session was already running on one.
21009
- // A structural row like the ones above rather than a capture — it carries
21010
- // the model that was refused and nothing the user typed, because what is
21011
- // worth recording about a governance decision is the decision, and prompt
21012
- // text is the thing this product exists to keep from travelling.
21089
+ // One row per model REFUSAL, across all four seams a prohibited model can be
21090
+ // stopped at: a switch onto it, a turn already running on it, a subagent
21091
+ // spawn asking for it, or a request-path refusal an embedded request-path
21092
+ // SDK makes in-process before the call leaves the application. Which seam
21093
+ // rides `attributes.refusal_seam`, never this member name. A structural row
21094
+ // like the ones above rather than a capture — it carries the model that was
21095
+ // refused and nothing the user typed, because what is worth recording about
21096
+ // a governance decision is the decision, and prompt text is the thing this
21097
+ // product exists to keep from travelling.
21013
21098
  "model_refusal",
21099
+ // One row per request-path DECISION: a policy check an embedded request-path
21100
+ // SDK performs in-process before a model call leaves the application, or
21101
+ // against that call's non-streamed response. A structural row like
21102
+ // 'model_refusal' rather than a capture — content-free in the same way:
21103
+ // which side, which seam, what action and which field are decided rides
21104
+ // `attributes`, never this member name, and the matched text itself never
21105
+ // travels.
21106
+ //
21107
+ // A prohibited-model refusal on the request path is deliberately NOT this
21108
+ // member: it stays 'model_refusal' with `refusal_seam: 'request'`, so it
21109
+ // shares one bucket with the plugin's switch/turn/spawn refusals rather
21110
+ // than splitting one governance concept across two event types. This
21111
+ // member carries every OTHER request-path decision.
21112
+ "request_decision",
21014
21113
  // One row per config-inventory scan, hung off the session root. It is the
21015
21114
  // fact the posture inspection findings reference (findings require an
21016
21115
  // audit_event_id), and its started_at is the "scanned Nm ago" the read
21017
21116
  // surface renders.
21018
- "config_scan"
21117
+ "config_scan",
21118
+ // One row per reported browser-extension capture status, hung off the web
21119
+ // session root. The durable home of what one tab's network interception
21120
+ // is doing — a write-through of the native host's in-memory tracker, so a
21121
+ // second process (aka extension status) and a restarted host both have
21122
+ // somewhere to read it back from.
21123
+ "capture_status"
21019
21124
  ]).meta({ id: "AuditEventType" });
21020
21125
  var AttributeBag = external_exports.record(external_exports.string(), external_exports.unknown());
21021
21126
  var HostAttributes = external_exports.object({
@@ -21149,6 +21254,10 @@ var CaptureAttributes = external_exports.object({
21149
21254
  // to 'allow' — the enforcement audit trail's link back to the grant that
21150
21255
  // authorized the bypass.
21151
21256
  exception_ids: external_exports.array(external_exports.guid()).optional(),
21257
+ // The persisted spellings of EventMetadata's messageId/conversationId — the
21258
+ // join back to the `llm_call` leaf for the same assistant turn.
21259
+ message_id: external_exports.string().optional(),
21260
+ conversation_id: external_exports.string().optional(),
21152
21261
  // Whole milliseconds this capture's inspection blocked its caller — the
21153
21262
  // plugin's own added latency (see EventMetadata.inspectionMs, whose value
21154
21263
  // this is). Promoted to the `inspection_ms` generated column so the facet is
@@ -21157,7 +21266,33 @@ var CaptureAttributes = external_exports.object({
21157
21266
  // inline json_extract and is not itself an optimization.
21158
21267
  // ABSENT on replayed captures (backfill / worktree scan) and on rows written
21159
21268
  // before the measurement shipped — never present as a placeholder 0.
21160
- inspection_ms: external_exports.number().int().nonnegative().optional()
21269
+ inspection_ms: external_exports.number().int().nonnegative().optional(),
21270
+ // What a `redact` this capture could not carry out became instead (see
21271
+ // EventMetadata.redactDegradedTo, whose value this is). Present only when a
21272
+ // degrade actually happened, so absence is the ordinary case rather than a
21273
+ // reader having to distinguish it from a zero.
21274
+ //
21275
+ // PER CAPTURE, while `inspection_findings.action_taken` is per finding —
21276
+ // so on a multi-finding row this does not say which finding degraded, and
21277
+ // its presence does not mean the fallback decided the capture's action. A
21278
+ // capture denied by another finding's own Block policy carries `block`
21279
+ // here too. The full statement is on EventMetadata.redactDegradedTo; it is
21280
+ // repeated rather than referenced because a store reader opens this file.
21281
+ redact_degraded_to: ActionTaken.optional()
21282
+ }).catchall(external_exports.unknown());
21283
+ var CaptureStatusAttributes = external_exports.object({
21284
+ source_tool: external_exports.string().optional(),
21285
+ patched: external_exports.boolean().optional(),
21286
+ live: external_exports.boolean().optional(),
21287
+ blind: external_exports.boolean().optional(),
21288
+ sends_seen_dom: external_exports.number().int().nonnegative().optional(),
21289
+ exchanges_seen_net: external_exports.number().int().nonnegative().optional(),
21290
+ parse_failures: external_exports.number().int().nonnegative().optional(),
21291
+ unparsed_bodies: external_exports.number().int().nonnegative().optional(),
21292
+ shape_misses: external_exports.array(external_exports.string()).optional(),
21293
+ conversation_endpoints: external_exports.number().int().nonnegative().optional(),
21294
+ closed: external_exports.boolean().optional(),
21295
+ enforcement: external_exports.string().optional()
21161
21296
  }).catchall(external_exports.unknown());
21162
21297
  var ToolCallInspection = external_exports.object({
21163
21298
  ruleId: external_exports.string().min(1),
@@ -21356,7 +21491,17 @@ var AuditEvent = external_exports.object({
21356
21491
  /** `share` to a first-party/internal destination. */
21357
21492
  internal: external_exports.boolean(),
21358
21493
  /** Event needs review (e.g. unverified egress). */
21359
- flagged: external_exports.boolean()
21494
+ flagged: external_exports.boolean(),
21495
+ /**
21496
+ * The body this event's `title` is drawn from was cleared by local body
21497
+ * expiry, so an EMPTY title here means "gone", not "never had one".
21498
+ *
21499
+ * A separate flag rather than a sentinel written into `title`: the title is
21500
+ * rendered text, and a store-layer module that invented display copy for it
21501
+ * would be choosing words the view is supposed to choose. Additive and
21502
+ * defaulted, so an older producer still validates.
21503
+ */
21504
+ bodyExpired: external_exports.boolean().default(false)
21360
21505
  }).meta({ id: "ActivityAuditEvent" });
21361
21506
  var ActivitySessionSummary = external_exports.object({
21362
21507
  id: external_exports.string(),
@@ -22008,6 +22153,30 @@ var AttachedCredential = external_exports.object({
22008
22153
  keyPrefix: external_exports.string().min(1).max(16).optional(),
22009
22154
  mintedAt: external_exports.iso.datetime().optional()
22010
22155
  });
22156
+ var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "::1", "[::1]"]);
22157
+ function unsafeEndpointReason(endpoint) {
22158
+ let parsed2;
22159
+ try {
22160
+ parsed2 = new URL(endpoint);
22161
+ } catch {
22162
+ return "unparseable";
22163
+ }
22164
+ if (parsed2.username !== "" || parsed2.password !== "") return "userinfo";
22165
+ if (parsed2.search !== "" || parsed2.hash !== "") return "query-or-fragment";
22166
+ if (parsed2.protocol === "https:") return null;
22167
+ return parsed2.protocol === "http:" && LOOPBACK_HOSTS.has(parsed2.hostname) ? null : "insecure";
22168
+ }
22169
+ function isSafeEndpoint(endpoint) {
22170
+ return unsafeEndpointReason(endpoint) === null;
22171
+ }
22172
+ function originOnly(endpoint) {
22173
+ try {
22174
+ const parsed2 = new URL(endpoint);
22175
+ return `${parsed2.protocol}//${parsed2.host}`;
22176
+ } catch {
22177
+ return "(unparseable endpoint)";
22178
+ }
22179
+ }
22011
22180
  var MAX_DATE_MS = 253402300799999;
22012
22181
  var MAX_INT4 = 2147483647;
22013
22182
  var StorePosturePack = external_exports.object({
@@ -22162,6 +22331,11 @@ var RemoteFailureKind = external_exports.enum([
22162
22331
  "rejected",
22163
22332
  "unreachable"
22164
22333
  ]);
22334
+ var ControlPlaneFailure = RemoteFailureKind.extract([
22335
+ "unauthorized",
22336
+ "forbidden",
22337
+ "unreachable"
22338
+ ]);
22165
22339
  var AttachDeviceRequest = external_exports.object({
22166
22340
  // This machine's own continuity id, so re-attaching ROTATES the credential
22167
22341
  // on one machine record instead of producing a second one. Client-minted
@@ -22697,6 +22871,17 @@ var EventMetadata = external_exports.object({
22697
22871
  // to 'allow' — the enforcement audit trail's link back to the grant that
22698
22872
  // authorized the bypass. Absent on captures where no exception applied.
22699
22873
  exceptionIds: external_exports.array(external_exports.guid()).optional(),
22874
+ // The assistant message this capture belongs to, and the conversation it sits
22875
+ // in — set by the browser extension's network capture so a stored `response`
22876
+ // row can be joined to the `llm_call` leaf describing the same turn. Absent
22877
+ // on every other capture path, which has no such id.
22878
+ //
22879
+ // Non-empty for the reason WebExchange.messageId is: it is the join key, and
22880
+ // a blank one matches no `llm_call` leaf. That refusal reaches only the
22881
+ // places an event is PARSED; the local write path types the event and parses
22882
+ // nothing, which is why `toCaptureAttributes` omits a blank one separately.
22883
+ messageId: external_exports.string().min(1).optional(),
22884
+ conversationId: external_exports.string().optional(),
22700
22885
  // How long THIS capture's inspection blocked its caller, in whole
22701
22886
  // milliseconds — the plugin's own added latency, NOT the LLM call it sat in
22702
22887
  // front of. Measured inside `capture()` (@akasecurity/plugin-sdk) across
@@ -22709,7 +22894,37 @@ var EventMetadata = external_exports.object({
22709
22894
  // Absent is also what every pre-measurement client writes, and what a
22710
22895
  // clock failure degrades to — a reader must treat absence as "not measured"
22711
22896
  // and never as a zero, which would read as "inspection is free".
22712
- inspectionMs: external_exports.number().int().nonnegative().optional()
22897
+ inspectionMs: external_exports.number().int().nonnegative().optional(),
22898
+ // What a `redact` this capture COULD NOT CARRY OUT became instead — the
22899
+ // workspace's `redactFallback`, applied because the field could not be
22900
+ // masked in place (a shell command, a URL, or any argument on a host whose
22901
+ // hook contract offers no rewrite channel).
22902
+ //
22903
+ // It exists because the action alone cannot say why. A finding recorded as
22904
+ // `warn` reads identically whether its detection was ASSIGNED Warn or was
22905
+ // assigned Redact on a field that could not take one — and those are
22906
+ // different facts about the same row: the first is a policy the user chose,
22907
+ // the second is a masking the host could not perform. Absent means no
22908
+ // degrade happened, which is every ordinary capture.
22909
+ //
22910
+ // TWO LIMITS a reader of a stored row has to know, because the grain here
22911
+ // is the CAPTURE while `actionTaken` is per FINDING:
22912
+ //
22913
+ // - It does not say WHICH finding degraded. A capture carrying a degraded
22914
+ // `redact` alongside a finding ASSIGNED the same action stores both
22915
+ // identically and one reason for the pair; attributing it to both
22916
+ // describes the assigned one wrongly, and to neither loses the degrade.
22917
+ // - PRESENCE IS NOT CAUSATION. The value is the action the lost redact
22918
+ // became, not the reason the capture ended as it did — a capture denied
22919
+ // by some other finding's own Block policy still carries `block` here,
22920
+ // and clearing the workspace's fallback would not have let it through.
22921
+ // Gate on the value against what a fallback can produce; never read the
22922
+ // field's presence as "this was the fallback's doing".
22923
+ //
22924
+ // Both are pinned as behaviour in @akasecurity/plugin-sdk's runtime suite.
22925
+ // Closing either means moving the reason onto the finding row, which
22926
+ // already carries its own action.
22927
+ redactDegradedTo: ActionTaken.optional()
22713
22928
  }).meta({ id: "EventMetadata" });
22714
22929
  var Event = external_exports.object({
22715
22930
  id: external_exports.guid(),
@@ -22819,7 +23034,32 @@ var RotateKeyInput = external_exports.object({
22819
23034
  confirmation: external_exports.string()
22820
23035
  });
22821
23036
 
23037
+ // ../../packages/schema/src/zod/finding-delivery.ts
23038
+ var KNOWN_REASONS = SyncFailureReason.options;
23039
+ function knownReason(value) {
23040
+ return value !== null && KNOWN_REASONS.includes(value) ? value : void 0;
23041
+ }
23042
+ function deriveFindingDelivery(row) {
23043
+ if (row.kind === "code_change") return { state: "local_scan" };
23044
+ if (row.syncedAt !== null && row.syncedAt > 0) {
23045
+ return { state: "sent", at: epochMillisToIso(row.syncedAt) };
23046
+ }
23047
+ if (row.syncedAt !== null) {
23048
+ const reason = knownReason(row.syncFailure);
23049
+ return {
23050
+ state: "not_sent",
23051
+ ...row.syncFailedAt === null ? {} : { at: epochMillisToIso(row.syncFailedAt) },
23052
+ ...reason === void 0 ? {} : { reason }
23053
+ };
23054
+ }
23055
+ if (row.outboxOwed === 1 || row.syncClaimedAt !== null) return { state: "queued" };
23056
+ return { state: "never_offered" };
23057
+ }
23058
+
22822
23059
  // ../../packages/schema/src/zod/findings-group-build.ts
23060
+ function lookupOwn(map2, key) {
23061
+ return Object.hasOwn(map2, key) ? map2[key] : void 0;
23062
+ }
22823
23063
  function toApiAction(dbVal) {
22824
23064
  const map2 = {
22825
23065
  log: "monitored",
@@ -22828,7 +23068,7 @@ function toApiAction(dbVal) {
22828
23068
  warn: "warned",
22829
23069
  allow: "allowed"
22830
23070
  };
22831
- return map2[dbVal] ?? "allowed";
23071
+ return lookupOwn(map2, dbVal) ?? "allowed";
22832
23072
  }
22833
23073
  function toApiCategory(dbVal) {
22834
23074
  if (dbVal === "code_context") return "source_code";
@@ -22836,13 +23076,18 @@ function toApiCategory(dbVal) {
22836
23076
  return parsed2.success ? parsed2.data : "custom";
22837
23077
  }
22838
23078
  function toApiProvider(sourceTool) {
22839
- return TOOL_TO_HARNESS[sourceTool] ?? HARNESS.Api;
23079
+ return lookupOwn(TOOL_TO_HARNESS, sourceTool) ?? HARNESS.Api;
22840
23080
  }
22841
- var STATUS_PRECEDENCE = ["open", "handled", "dismissed", "resolved"];
23081
+ var FINDING_STATUS_PRECEDENCE = [
23082
+ "open",
23083
+ "handled",
23084
+ "dismissed",
23085
+ "resolved"
23086
+ ];
22842
23087
  function foldGroupStatus(instanceStatuses) {
22843
23088
  const statuses = new Set(instanceStatuses.filter((s) => s !== void 0));
22844
23089
  if (statuses.size === 0) return void 0;
22845
- for (const candidate of STATUS_PRECEDENCE) {
23090
+ for (const candidate of FINDING_STATUS_PRECEDENCE) {
22846
23091
  if (statuses.has(candidate)) return candidate;
22847
23092
  }
22848
23093
  return void 0;
@@ -22949,11 +23194,16 @@ function applyFindingFilters(types, opts) {
22949
23194
  }
22950
23195
  return filtered;
22951
23196
  }
22952
- var SEVERITY_ORDER = { critical: 0, high: 1, medium: 2, low: 3 };
22953
- var SEVERITY_RANK = SEVERITY_ORDER;
23197
+ function rankByOrder(members2) {
23198
+ return Object.fromEntries(members2.map((member, index) => [member, index]));
23199
+ }
23200
+ var SEVERITY_RANK = rankByOrder(Severity.options);
23201
+ function severityRank(severity) {
23202
+ return lookupOwn(SEVERITY_RANK, severity);
23203
+ }
22954
23204
  function compareFindingGroupOrder(a, b) {
22955
- const rankA = SEVERITY_RANK[a.severity] ?? -1;
22956
- const rankB = SEVERITY_RANK[b.severity] ?? -1;
23205
+ const rankA = severityRank(a.severity) ?? -1;
23206
+ const rankB = severityRank(b.severity) ?? -1;
22957
23207
  const severityDiff = rankA - rankB;
22958
23208
  if (severityDiff !== 0) return severityDiff;
22959
23209
  const recencyDiff = b.latestDetectedAt.localeCompare(a.latestDetectedAt);
@@ -23028,6 +23278,20 @@ function computeFindingFacets(allTypes, opts) {
23028
23278
  }
23029
23279
 
23030
23280
  // ../../packages/schema/src/zod/findings-flat-build.ts
23281
+ function compareCodePoints(a, b) {
23282
+ const aIter = a[Symbol.iterator]();
23283
+ const bIter = b[Symbol.iterator]();
23284
+ for (; ; ) {
23285
+ const aNext = aIter.next();
23286
+ const bNext = bIter.next();
23287
+ if (aNext.done && bNext.done) return 0;
23288
+ if (aNext.done) return -1;
23289
+ if (bNext.done) return 1;
23290
+ const aPoint = aNext.value.codePointAt(0) ?? 0;
23291
+ const bPoint = bNext.value.codePointAt(0) ?? 0;
23292
+ if (aPoint !== bPoint) return aPoint - bPoint;
23293
+ }
23294
+ }
23031
23295
  function rowHaystack(row) {
23032
23296
  return [
23033
23297
  row.ruleId,
@@ -23052,6 +23316,8 @@ function matchesDimension(row, opts, dimension) {
23052
23316
  return !opts.actions?.length || opts.actions.includes(toApiAction(row.actionTaken));
23053
23317
  case "statuses":
23054
23318
  return !opts.statuses?.length || row.status !== void 0 && opts.statuses.includes(row.status);
23319
+ case "deliveries":
23320
+ return !opts.deliveries?.length || row.delivery !== void 0 && opts.deliveries.includes(row.delivery.state);
23055
23321
  case "tools":
23056
23322
  return !opts.tools?.length || row.toolName !== void 0 && opts.tools.includes(row.toolName);
23057
23323
  // An EMPTY value is a real filter here, not an absent one. The location
@@ -23078,6 +23344,7 @@ var DIMENSIONS = [
23078
23344
  "providers",
23079
23345
  "actions",
23080
23346
  "statuses",
23347
+ "deliveries",
23081
23348
  "tools",
23082
23349
  "repo",
23083
23350
  "file",
@@ -23091,10 +23358,19 @@ function matchesInstanceFilters(row, opts, except) {
23091
23358
  return true;
23092
23359
  }
23093
23360
  function toItems(counts) {
23094
- return [...counts.entries()].map(([value, count]) => ({ value, count })).sort((a, b) => b.count - a.count || a.value.localeCompare(b.value));
23361
+ return [...counts.entries()].map(([value, count]) => ({ value, count })).sort(
23362
+ (a, b) => b.count - a.count || a.value.localeCompare(b.value) || // localeCompare reports canonically-equivalent strings (an NFC and an
23363
+ // NFD spelling of the same text) as equal, so a count tie between
23364
+ // them would otherwise be ordered by whichever the Map iteration
23365
+ // produced. compareCodePoints breaks that tie deterministically, which
23366
+ // makes this a TOTAL order — not one that agrees with SQL collation,
23367
+ // which it need not: foldFacetTuples runs this same sort over grouped
23368
+ // tuples, so both paths order facets identically by construction.
23369
+ compareCodePoints(a.value, b.value)
23370
+ );
23095
23371
  }
23096
- function bump(counts, value) {
23097
- counts.set(value, (counts.get(value) ?? 0) + 1);
23372
+ function bump(counts, value, by = 1) {
23373
+ counts.set(value, (counts.get(value) ?? 0) + by);
23098
23374
  }
23099
23375
  function createInstanceFacetAccumulator(opts) {
23100
23376
  const severity = /* @__PURE__ */ new Map();
@@ -23103,6 +23379,7 @@ function createInstanceFacetAccumulator(opts) {
23103
23379
  const action = /* @__PURE__ */ new Map();
23104
23380
  const status = /* @__PURE__ */ new Map();
23105
23381
  const tool = /* @__PURE__ */ new Map();
23382
+ const deployment = /* @__PURE__ */ new Map();
23106
23383
  return {
23107
23384
  add(row) {
23108
23385
  if (matchesInstanceFilters(row, opts, "severity")) bump(severity, row.severity);
@@ -23117,6 +23394,9 @@ function createInstanceFacetAccumulator(opts) {
23117
23394
  if (row.toolName !== void 0 && matchesInstanceFilters(row, opts, "tools")) {
23118
23395
  bump(tool, row.toolName);
23119
23396
  }
23397
+ if (row.delivery !== void 0 && matchesInstanceFilters(row, opts, "deliveries")) {
23398
+ bump(deployment, row.delivery.state);
23399
+ }
23120
23400
  },
23121
23401
  facets: () => ({
23122
23402
  severity: toItems(severity),
@@ -23124,7 +23404,8 @@ function createInstanceFacetAccumulator(opts) {
23124
23404
  provider: toItems(provider),
23125
23405
  action: toItems(action),
23126
23406
  status: toItems(status),
23127
- tool: toItems(tool)
23407
+ tool: toItems(tool),
23408
+ deployment: toItems(deployment)
23128
23409
  })
23129
23410
  };
23130
23411
  }
@@ -23138,6 +23419,7 @@ function toInstanceDetail(row) {
23138
23419
  ...row.toolName === void 0 ? {} : { toolName: row.toolName },
23139
23420
  eventId: row.eventId,
23140
23421
  ...row.sessionId === void 0 ? {} : { sessionId: row.sessionId },
23422
+ ...row.delivery === void 0 ? {} : { delivery: row.delivery },
23141
23423
  ...row.user === void 0 ? {} : { user: row.user },
23142
23424
  action: toApiAction(row.actionTaken),
23143
23425
  detectedAt: row.occurredAt,
@@ -23152,12 +23434,6 @@ function toInstanceDetail(row) {
23152
23434
  policy: { id: `category:${category}`, name: category }
23153
23435
  };
23154
23436
  }
23155
- var SEVERITY_ORDER2 = {
23156
- critical: 0,
23157
- high: 1,
23158
- medium: 2,
23159
- low: 3
23160
- };
23161
23437
  function newLocationAccumulator() {
23162
23438
  return {
23163
23439
  instanceCount: 0,
@@ -23172,7 +23448,7 @@ function newLocationAccumulator() {
23172
23448
  }
23173
23449
  function addToLocation(acc, row) {
23174
23450
  acc.instanceCount += 1;
23175
- const rank = SEVERITY_ORDER2[row.severity] ?? Number.MAX_SAFE_INTEGER - 1;
23451
+ const rank = severityRank(row.severity) ?? Number.MAX_SAFE_INTEGER - 1;
23176
23452
  if (rank < acc.maxSeverityRank) {
23177
23453
  acc.maxSeverityRank = rank;
23178
23454
  acc.maxSeverity = row.severity;
@@ -23182,15 +23458,15 @@ function addToLocation(acc, row) {
23182
23458
  acc.ruleIds.add(row.ruleId);
23183
23459
  }
23184
23460
  function compareLocationOrder(a, b) {
23185
- const rankA = SEVERITY_ORDER2[a.maxSeverity] ?? -1;
23186
- const rankB = SEVERITY_ORDER2[b.maxSeverity] ?? -1;
23461
+ const rankA = severityRank(a.maxSeverity) ?? -1;
23462
+ const rankB = severityRank(b.maxSeverity) ?? -1;
23187
23463
  if (rankA !== rankB) return rankA - rankB;
23188
23464
  if (a.latestDetectedAt !== b.latestDetectedAt) {
23189
23465
  return a.latestDetectedAt < b.latestDetectedAt ? 1 : -1;
23190
23466
  }
23191
- if (a.repo !== b.repo) return a.repo < b.repo ? -1 : 1;
23192
- if (a.file !== b.file) return a.file < b.file ? -1 : 1;
23193
- return 0;
23467
+ const repoDiff = compareCodePoints(a.repo, b.repo);
23468
+ if (repoDiff !== 0) return repoDiff;
23469
+ return compareCodePoints(a.file, b.file);
23194
23470
  }
23195
23471
  function encodeLocationId(repo, file2) {
23196
23472
  return `${encodePart(repo)}/${encodePart(file2)}`;
@@ -23265,6 +23541,11 @@ var Policy = external_exports.object({
23265
23541
  // test `prohibitedModels` passes and `reversibleRuleIds` fails.
23266
23542
  provenance: PolicyProvenance.optional()
23267
23543
  }).meta({ id: "Policy" });
23544
+ var KNOWN_BUILTIN_IDS = ["monitor", "warn", "redact", "vault", "block"];
23545
+ var BuiltinPolicyId = external_exports.enum(KNOWN_BUILTIN_IDS).meta({ id: "BuiltinPolicyId" });
23546
+ var RedactFallback = BuiltinPolicyId.extract(["monitor", "warn", "block"]).meta({
23547
+ id: "RedactFallback"
23548
+ });
23268
23549
  var PolicyBundle = external_exports.object({
23269
23550
  version: external_exports.string(),
23270
23551
  policies: external_exports.array(Policy),
@@ -23312,6 +23593,16 @@ var PolicyBundle = external_exports.object({
23312
23593
  // control plane), so no name resolution stands between the decision and the
23313
23594
  // comparison.
23314
23595
  prohibitedModels: external_exports.array(external_exports.string()).optional(),
23596
+ // What a resolved `redact` becomes on a field the host cannot rewrite, as
23597
+ // the ORGANIZATION would have it. Merged raise-only against the device's own
23598
+ // `WorkspaceSettings.redactFallback` (see strongerRedactFallback below), so
23599
+ // a control plane can tighten a machine and never loosen one — the same
23600
+ // direction `mergeRaiseOnly` enforces for policies.
23601
+ //
23602
+ // Optional so an older backend, and an older on-disk cache, still parses;
23603
+ // absent leaves the device's own setting in force, which is the behaviour
23604
+ // that predates the field and the safe direction to default.
23605
+ redactFallback: RedactFallback.optional(),
23315
23606
  customKeywords: external_exports.array(external_exports.string()),
23316
23607
  fetchedAt: external_exports.iso.datetime()
23317
23608
  }).meta({ id: "PolicyBundle" });
@@ -23341,11 +23632,6 @@ function severityFloorPolicy(category) {
23341
23632
  const peak = CATEGORY_PEAK_SEVERITY[category];
23342
23633
  return peak === "critical" || peak === "high" ? "warn" : "monitor";
23343
23634
  }
23344
- var KNOWN_BUILTIN_IDS = ["monitor", "warn", "redact", "vault", "block"];
23345
- var BuiltinPolicyId = external_exports.enum(KNOWN_BUILTIN_IDS).meta({ id: "BuiltinPolicyId" });
23346
- var RedactFallback = BuiltinPolicyId.extract(["monitor", "warn", "block"]).meta({
23347
- id: "RedactFallback"
23348
- });
23349
23635
  var BUILTIN_ORDER = KNOWN_BUILTIN_IDS;
23350
23636
  var BUILTIN_POLICY_SPECS = {
23351
23637
  monitor: {
@@ -23638,7 +23924,7 @@ var VaultConsent = external_exports.object({
23638
23924
  });
23639
23925
 
23640
23926
  // ../../packages/schema/src/zod/local.ts
23641
- var WORKSPACE_SETTINGS_SPEC_VERSION = 7;
23927
+ var WORKSPACE_SETTINGS_SPEC_VERSION = 8;
23642
23928
  var MODEL_JUDGE_PAYLOAD_VERSION = 1;
23643
23929
  var HISTORY_SYNC_PAYLOAD_VERSION = 3;
23644
23930
  var RunMode = external_exports.enum(["standalone", "attached"]);
@@ -23663,6 +23949,27 @@ function isHistorySyncConsentValid(consent, endpoint) {
23663
23949
  if (consent === void 0 || endpoint === void 0) return false;
23664
23950
  return consent.payloadVersion === HISTORY_SYNC_PAYLOAD_VERSION && consent.endpoint === endpoint;
23665
23951
  }
23952
+ var WebChatCaptureConsent = external_exports.object({
23953
+ acknowledgedAt: external_exports.iso.datetime(),
23954
+ version: external_exports.number().int().positive()
23955
+ });
23956
+ var WebChatResponseCapture = external_exports.enum(["with-findings", "always", "never"]);
23957
+ var WebChatCapture = external_exports.object({
23958
+ responses: WebChatResponseCapture.default("with-findings"),
23959
+ account: external_exports.boolean().default(false),
23960
+ // Absent until granted. Presence alone does not authorize anything — see
23961
+ // isWebChatCaptureConsentValid.
23962
+ consent: WebChatCaptureConsent.optional()
23963
+ });
23964
+ var BODY_RETENTION_DEFAULT_DAYS = 30;
23965
+ var BodyRetention = external_exports.object({
23966
+ enabled: external_exports.boolean().default(false),
23967
+ // Never 0, and the ceiling is a fat-finger guard rather than a policy
23968
+ // limit — `enabled` is the real gate. A low value cannot reach a row the
23969
+ // sync ledger still owes: the sweep's age filter only ever NARROWS a
23970
+ // candidate set that is already bounded by "delivered, or never owed".
23971
+ retainDays: external_exports.number().int().min(1).max(3650).default(BODY_RETENTION_DEFAULT_DAYS)
23972
+ }).meta({ id: "BodyRetention" });
23666
23973
  var WorkspaceSettings = external_exports.object({
23667
23974
  specVersion: external_exports.number().int().positive().default(WORKSPACE_SETTINGS_SPEC_VERSION),
23668
23975
  runMode: RunMode.default("standalone"),
@@ -23711,7 +24018,23 @@ var WorkspaceSettings = external_exports.object({
23711
24018
  // carry prompt/reply/tool-output text in `content`; the key name predates
23712
24019
  // both widenings. Absent until granted, and a grant for a different endpoint
23713
24020
  // or an older payload no longer counts.
23714
- historySyncConsent: HistorySyncConsent.optional()
24021
+ historySyncConsent: HistorySyncConsent.optional(),
24022
+ // What the browser extension may record from a web chat, and the grant that
24023
+ // authorizes it. Absent until the user answers: recording something that was
24024
+ // never recorded before is never an assumed grant on upgrade, so the whole
24025
+ // block is optional rather than defaulted in. What an absent block means is
24026
+ // webChatCaptureOf's answer, in one place.
24027
+ //
24028
+ // Enforcement is NOT gated on this. A machine that has never answered still
24029
+ // blocks, redacts and warns on what a user sends; the grant covers what is
24030
+ // written down.
24031
+ webChatCapture: WebChatCapture.optional(),
24032
+ // Local body expiry (see BodyRetention). Off until switched on; expiring a
24033
+ // body never removes the row or its findings.
24034
+ bodyRetention: BodyRetention.default({
24035
+ enabled: false,
24036
+ retainDays: BODY_RETENTION_DEFAULT_DAYS
24037
+ })
23715
24038
  });
23716
24039
  function defaultWorkspaceSettings() {
23717
24040
  return WorkspaceSettings.parse({});
@@ -23806,12 +24129,18 @@ function toCaptureAttributes(event) {
23806
24129
  ...metadata?.traceId !== void 0 ? { trace_id: metadata.traceId } : {},
23807
24130
  ...metadata?.exceptionIds !== void 0 ? { exception_ids: metadata.exceptionIds } : {},
23808
24131
  ...metadata?.inspectionMs !== void 0 ? { inspection_ms: metadata.inspectionMs } : {},
24132
+ ...metadata?.redactDegradedTo !== void 0 ? { redact_degraded_to: metadata.redactDegradedTo } : {},
23809
24133
  // `model`/`turnIndex` have no dedicated CaptureAttributes field (no writer
23810
24134
  // has ever populated either), but every legacy metadata key still rides
23811
24135
  // the bag rather than being silently dropped — CaptureAttributes'
23812
24136
  // `.catchall(z.unknown())` carries the long tail.
23813
24137
  ...metadata?.model !== void 0 ? { model: metadata.model } : {},
23814
- ...metadata?.turnIndex !== void 0 ? { turn_index: metadata.turnIndex } : {}
24138
+ ...metadata?.turnIndex !== void 0 ? { turn_index: metadata.turnIndex } : {},
24139
+ // A blank id is omitted rather than stored: it is a join key and `''` joins
24140
+ // nothing. This runs on the local write path, which types the event but
24141
+ // never parses it, so EventMetadata's own `.min(1)` does not reach here.
24142
+ ...metadata?.messageId !== void 0 && metadata.messageId !== "" ? { message_id: metadata.messageId } : {},
24143
+ ...metadata?.conversationId !== void 0 ? { conversation_id: metadata.conversationId } : {}
23815
24144
  };
23816
24145
  }
23817
24146
  function captureDefinitionVersion(finding) {
@@ -23839,13 +24168,22 @@ var ManagedSettingKey = external_exports.enum([
23839
24168
  "vaultInlineReveal",
23840
24169
  "modelJudgeConsent",
23841
24170
  "dataSharesInPlace",
23842
- "redactFallback"
24171
+ "redactFallback",
24172
+ // Pins the toggle and the day count together — see BodyRetention on why the
24173
+ // two are one unit. An administrator mandating a window wants the count
24174
+ // enforced with it, not one a user can widen while the toggle stays on.
24175
+ "bodyRetention"
23843
24176
  ]).meta({ id: "ManagedSettingKey" });
23844
24177
  function isManagedSettingKey(value) {
23845
24178
  return ManagedSettingKey.safeParse(value).success;
23846
24179
  }
23847
24180
  var ManagedSettingsValues = external_exports.object({
23848
24181
  runMode: external_exports.enum(["standalone", "attached"]).optional(),
24182
+ // `controlPlane` and `bodyRetention` are the two nested values, and both are
24183
+ // plain, non-strict objects: a key under either that this build does not know
24184
+ // is stripped and nothing reports it. The unknown-value split in
24185
+ // ManagedSettings below classifies top-level names only, so it stops at
24186
+ // these boundaries.
23849
24187
  controlPlane: external_exports.object({
23850
24188
  endpoint: external_exports.string().min(1),
23851
24189
  label: external_exports.string().min(1).optional()
@@ -23856,7 +24194,8 @@ var ManagedSettingsValues = external_exports.object({
23856
24194
  vaultInlineReveal: external_exports.enum(["masked", "full", "off"]).optional(),
23857
24195
  modelJudgeConsent: external_exports.boolean().optional(),
23858
24196
  dataSharesInPlace: external_exports.boolean().optional(),
23859
- redactFallback: RedactFallback.optional()
24197
+ redactFallback: RedactFallback.optional(),
24198
+ bodyRetention: BodyRetention.optional()
23860
24199
  }).meta({ id: "ManagedSettingsValues" });
23861
24200
  var ManagedSettings = external_exports.object({
23862
24201
  specVersion: external_exports.number().int().positive().default(MANAGED_SETTINGS_SPEC_VERSION),
@@ -23864,7 +24203,21 @@ var ManagedSettings = external_exports.object({
23864
24203
  // decision from a bug. Absent renders as a generic "your organization".
23865
24204
  organization: external_exports.string().min(1).optional(),
23866
24205
  // What the administrator pinned.
23867
- values: ManagedSettingsValues.default({}),
24206
+ //
24207
+ // Parsed as a RECORD rather than as the nested schema, and split below for
24208
+ // the same reason `lockedFields` is parsed as names: a plain `z.object`
24209
+ // drops an unrecognised key and succeeds, so a pin this build does not know
24210
+ // vanished and nothing anywhere said so. A pin with no lock is a supported
24211
+ // shape — it is a DEFAULT the user may still change — so that silence hit
24212
+ // exactly the file an administrator is most likely to write while a fleet
24213
+ // is mid-upgrade.
24214
+ //
24215
+ // Splitting here rather than calling `.strict()`: strict would REFUSE the
24216
+ // file, which is the outcome the lock half already rejected — an older
24217
+ // build then runs entirely unmanaged, every pin and lock gone. A bad KNOWN
24218
+ // value still fails, because the nested schema is re-run over the known
24219
+ // subset and its issues are re-raised on this parse.
24220
+ values: external_exports.record(external_exports.string(), external_exports.unknown()).default({}),
23868
24221
  // Which of those the user may not change. A key here with no matching value
23869
24222
  // freezes whatever the user last chose; a value with no lock is a DEFAULT
23870
24223
  // the user may still override. The two are separable on purpose.
@@ -23877,17 +24230,31 @@ var ManagedSettings = external_exports.object({
23877
24230
  // the fleets most likely to carry a version skew. A name outside the enum
23878
24231
  // is still never HONOURED: the lockable set stays explicit above.
23879
24232
  lockedFields: external_exports.array(external_exports.string()).default([])
23880
- }).transform(({ lockedFields, ...rest }) => {
24233
+ }).transform(({ lockedFields, values, ...rest }, ctx) => {
23881
24234
  const known = [];
23882
24235
  const unknown2 = [];
23883
24236
  for (const name of lockedFields) {
23884
24237
  if (isManagedSettingKey(name)) known.push(name);
23885
24238
  else unknown2.push(name);
23886
24239
  }
24240
+ const knownValues = /* @__PURE__ */ Object.create(null);
24241
+ const unknownValues = [];
24242
+ for (const [name, value] of Object.entries(values)) {
24243
+ if (Object.hasOwn(ManagedSettingsValues.shape, name)) knownValues[name] = value;
24244
+ else unknownValues.push(name);
24245
+ }
24246
+ const pinned = ManagedSettingsValues.safeParse(knownValues);
24247
+ if (!pinned.success) {
24248
+ for (const issue2 of pinned.error.issues)
24249
+ ctx.addIssue({ ...issue2, path: ["values", ...issue2.path] });
24250
+ return external_exports.NEVER;
24251
+ }
23887
24252
  return {
23888
24253
  ...rest,
24254
+ values: pinned.data,
23889
24255
  lockedFields: known,
23890
- ...unknown2.length > 0 ? { unknownLockedFields: unknown2 } : {}
24256
+ ...unknown2.length > 0 ? { unknownLockedFields: unknown2 } : {},
24257
+ ...unknownValues.length > 0 ? { unknownValueFields: unknownValues } : {}
23891
24258
  };
23892
24259
  }).meta({ id: "ManagedSettings" });
23893
24260
 
@@ -24146,12 +24513,30 @@ var RecommendedActionIdParam = external_exports.object({ id: external_exports.st
24146
24513
  // ../../packages/schema/src/zod/settings-action.ts
24147
24514
  var HistorySyncConsentChoice = external_exports.enum(["granted", "revoked", "unchanged"]).meta({ id: "HistorySyncConsentChoice" });
24148
24515
  var ModelJudgeConsentChoice = external_exports.enum(["granted", "revoked", "unchanged"]).meta({ id: "ModelJudgeConsentChoice" });
24516
+ var WebChatCaptureConsentChoice = external_exports.enum(["granted", "revoked", "unchanged"]).meta({ id: "WebChatCaptureConsentChoice" });
24149
24517
  var SaveSettingsInput = external_exports.object({
24150
24518
  historicalAccess: external_exports.string(),
24151
24519
  modelJudgeConsent: ModelJudgeConsentChoice,
24152
24520
  historySyncConsent: HistorySyncConsentChoice,
24153
24521
  vaultConsent: external_exports.string(),
24154
- vaultInlineReveal: external_exports.string()
24522
+ vaultInlineReveal: external_exports.string(),
24523
+ webChatCaptureConsent: WebChatCaptureConsentChoice,
24524
+ // Widened to `string` like its neighbours rather than typed as
24525
+ // `RedactFallback`, on this module's own layering rule: shape here, VALUE at
24526
+ // the call site, so the domain check receives the type it was written for.
24527
+ //
24528
+ // NOT because a narrower schema would reject differently. `parseActionInput`
24529
+ // is a `safeParse` wrapper and throws for no field schema, so either spelling
24530
+ // reaches a recoverable `{ ok: false }` and there is no rejected promise to
24531
+ // trade against. The real cost runs the other way and is the part worth
24532
+ // knowing: a value this schema admits and the domain enum then rejects lands
24533
+ // on the action's shared refusal, which names NO field, where a shape
24534
+ // rejection reaches `malformedInput` and names the schema key.
24535
+ redactFallback: external_exports.string(),
24536
+ // Shape only, the way the enum fields above are strings only: the RANGE is
24537
+ // `BodyRetention`'s and the action checks it there, so there is one place
24538
+ // that decides what a legal horizon is rather than two that can drift.
24539
+ bodyRetention: external_exports.object({ enabled: external_exports.boolean(), retainDays: external_exports.number() })
24155
24540
  });
24156
24541
  var AttachInput = external_exports.object({
24157
24542
  endpoint: external_exports.string(),
@@ -24323,6 +24708,123 @@ function reviewSeverityRank(reasons) {
24323
24708
  return Math.min(...reasons.map((r) => REVIEW_SEVERITY_RANK[r]));
24324
24709
  }
24325
24710
 
24711
+ // ../../packages/schema/src/zod/web-capture.ts
24712
+ var WebUsageSource = external_exports.enum(["site", "estimated", "none"]);
24713
+ var WebUsage = external_exports.object({
24714
+ inputTokens: external_exports.number().int().nonnegative().optional(),
24715
+ outputTokens: external_exports.number().int().nonnegative().optional(),
24716
+ cacheReadInputTokens: external_exports.number().int().nonnegative().optional(),
24717
+ cacheCreationInputTokens: external_exports.number().int().nonnegative().optional()
24718
+ });
24719
+ var WebToolCall = external_exports.object({
24720
+ toolUseId: external_exports.string().min(1),
24721
+ toolName: external_exports.string().min(1),
24722
+ target: external_exports.string().optional(),
24723
+ isError: external_exports.boolean().optional(),
24724
+ inputSize: external_exports.number().int().nonnegative().optional(),
24725
+ outputSize: external_exports.number().int().nonnegative().optional()
24726
+ });
24727
+ var WebExchange = external_exports.object({
24728
+ messageId: external_exports.string().min(1),
24729
+ startedAt: external_exports.iso.datetime(),
24730
+ model: external_exports.string().optional(),
24731
+ usage: WebUsage.optional(),
24732
+ usageSource: WebUsageSource,
24733
+ stopReason: external_exports.string().optional(),
24734
+ conversationId: external_exports.string().optional(),
24735
+ turnIndex: external_exports.number().int().nonnegative().optional(),
24736
+ toolCalls: external_exports.array(WebToolCall).default([]),
24737
+ // Absent when the adapter recovered no text. Capped by the caller at
24738
+ // RESPONSE_TEXT_MAX_BYTES, so a short capture is never mistaken for a short
24739
+ // reply.
24740
+ responseText: external_exports.string().optional(),
24741
+ // The stored text is short of the reply. It does NOT say which of the two
24742
+ // ceilings on this path cut it: the caller applies its own cap on the raw
24743
+ // bytes it reads off the wire, which can be reached by a stream whose
24744
+ // recovered text stays well under RESPONSE_TEXT_MAX_BYTES, and applies that
24745
+ // one to the text. A reader cannot tell them apart, and nothing downstream
24746
+ // should branch as though it could.
24747
+ truncated: external_exports.boolean().default(false)
24748
+ });
24749
+ var WebEnforcementState = external_exports.enum([
24750
+ "watching",
24751
+ "composer-only",
24752
+ "button-only",
24753
+ "unattached",
24754
+ "unknown"
24755
+ ]);
24756
+ var RESPONSE_TEXT_MAX_BYTES = 2 * 1024 * 1024;
24757
+ var WebCaptureStatus = external_exports.object({
24758
+ patched: external_exports.boolean(),
24759
+ live: external_exports.boolean(),
24760
+ blind: external_exports.boolean(),
24761
+ sendsSeenDom: external_exports.number().int().nonnegative(),
24762
+ exchangesSeenNet: external_exports.number().int().nonnegative(),
24763
+ parseFailures: external_exports.number().int().nonnegative(),
24764
+ unparsedBodies: external_exports.number().int().nonnegative(),
24765
+ // The adapter-declared JSON key paths that were absent from a real payload —
24766
+ // the earliest signal that a site's contract moved.
24767
+ shapeMisses: external_exports.array(external_exports.string()).default([]),
24768
+ // How many `kind: 'conversation'` endpoints the reporting tab's adapter
24769
+ // compiled. Zero means this build declares none for the site, so observing
24770
+ // nothing is the design rather than a fault — the one fact that separates a
24771
+ // site nobody has surveyed yet from one whose contract moved. Defaulted so a
24772
+ // build predating the field is read as declaring nothing rather than refused.
24773
+ conversationEndpoints: external_exports.number().int().nonnegative().default(0),
24774
+ // The document that sent this report is going away. The bridge sets it on
24775
+ // its `pagehide` report and nowhere else.
24776
+ //
24777
+ // A property of the REPORT rather than of capture health, which is why
24778
+ // nothing in `deriveWebCaptureState` reads it and why it stays out of the
24779
+ // bridge's own report signature — a closing tab's last word must not be
24780
+ // suppressed for carrying the same health as the report before it. What
24781
+ // reads it is the per-site fold: a document that said it was unloading stops
24782
+ // voting on the site's state, so the reload the `blind` remediation asks for
24783
+ // can actually clear the verdict it was shown. A document that dies without
24784
+ // sending one is covered by CAPTURE_STATUS_DOCUMENT_QUIET_MS instead.
24785
+ //
24786
+ // Defaulted so a build predating the field reads as a document that never
24787
+ // said it was closing — which keeps it voting, the same as every report that
24788
+ // is not a final one.
24789
+ closed: external_exports.boolean().default(false),
24790
+ // What the DOM enforcement path is doing, which none of the counters above
24791
+ // can say: `sendsSeenDom` rises only once a send has COMPLETED, so a tab
24792
+ // whose watcher never bound reports zero exactly like a tab nobody typed in.
24793
+ // Defaulted to 'unknown' rather than 'watching' so a status from a build
24794
+ // predating the field is not read as reporting a healthy one.
24795
+ enforcement: WebEnforcementState.default("unknown")
24796
+ });
24797
+ function webCaptureStatusObservedTurnPath(status) {
24798
+ if (!status.patched) return true;
24799
+ if (status.conversationEndpoints === 0) return true;
24800
+ return status.blind || status.shapeMisses.length > 0 || status.parseFailures > 0 || status.unparsedBodies > 0 || status.exchangesSeenNet > 0;
24801
+ }
24802
+ function pickReportedCaptureStatus(candidates) {
24803
+ return candidates.find((c) => webCaptureStatusObservedTurnPath(c.status)) ?? candidates[0];
24804
+ }
24805
+ var CAPTURE_STATUS_RECENCY_MS = 30 * 24 * 60 * 60 * 1e3;
24806
+ var CAPTURE_STATUS_RECENCY_DAYS = CAPTURE_STATUS_RECENCY_MS / (24 * 60 * 60 * 1e3);
24807
+ var CAPTURE_STATUS_DOCUMENT_QUIET_MS = 12 * 60 * 60 * 1e3;
24808
+ function fromCaptureStatusAttributes(bag) {
24809
+ const parsedBag = CaptureStatusAttributes.safeParse(bag);
24810
+ if (!parsedBag.success) return null;
24811
+ const b = parsedBag.data;
24812
+ const parsedStatus = WebCaptureStatus.safeParse({
24813
+ patched: b.patched,
24814
+ live: b.live,
24815
+ blind: b.blind,
24816
+ sendsSeenDom: b.sends_seen_dom,
24817
+ exchangesSeenNet: b.exchanges_seen_net,
24818
+ parseFailures: b.parse_failures,
24819
+ unparsedBodies: b.unparsed_bodies,
24820
+ shapeMisses: b.shape_misses,
24821
+ conversationEndpoints: b.conversation_endpoints,
24822
+ closed: b.closed,
24823
+ enforcement: b.enforcement
24824
+ });
24825
+ return parsedStatus.success ? parsedStatus.data : null;
24826
+ }
24827
+
24326
24828
  // ../../packages/persistence/src/paths.ts
24327
24829
  import {
24328
24830
  chmodSync,
@@ -24395,17 +24897,6 @@ function writeOwnerOnlyFileSync(file2, data) {
24395
24897
  function controlPlaneCredentialPath(settingsDir2) {
24396
24898
  return join2(settingsDir2, ATTACHED_CREDENTIAL_FILENAME);
24397
24899
  }
24398
- var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "::1", "[::1]"]);
24399
- function isSafeEndpoint(endpoint) {
24400
- let parsed2;
24401
- try {
24402
- parsed2 = new URL(endpoint);
24403
- } catch {
24404
- return false;
24405
- }
24406
- if (parsed2.protocol === "https:") return true;
24407
- return parsed2.protocol === "http:" && LOOPBACK_HOSTS.has(parsed2.hostname);
24408
- }
24409
24900
  function repairOrRefuseMode(file2) {
24410
24901
  const link = lstatSync2(file2, { throwIfNoEntry: false });
24411
24902
  if (link === void 0) return "absent";
@@ -24611,6 +25102,22 @@ function discardStore(file2, backup) {
24611
25102
  }
24612
25103
  }
24613
25104
 
25105
+ // ../../packages/persistence/src/internal/sql-functions.ts
25106
+ var utf8 = new TextDecoder();
25107
+ function akaLower(value) {
25108
+ if (value === null) return null;
25109
+ if (typeof value === "string") return value.toLowerCase();
25110
+ if (typeof value === "number" || typeof value === "bigint") return String(value).toLowerCase();
25111
+ return utf8.decode(value).toLowerCase();
25112
+ }
25113
+ function registerSqlFunctions(db) {
25114
+ db.function(
25115
+ "aka_lower",
25116
+ { deterministic: true, directOnly: true, useBigIntArguments: true },
25117
+ akaLower
25118
+ );
25119
+ }
25120
+
24614
25121
  // ../../packages/persistence/src/internal/sql-text.ts
24615
25122
  function escapeLikePattern(s) {
24616
25123
  return s.replace(/\\/g, "\\\\").replace(/%/g, "\\%").replace(/_/g, "\\_");
@@ -24695,6 +25202,11 @@ function schemaObjectExists(db, kind, name) {
24695
25202
  function indexExists(db, name) {
24696
25203
  return schemaObjectExists(db, "index", name);
24697
25204
  }
25205
+ function indexColumns(db, name) {
25206
+ if (!indexExists(db, name)) return [];
25207
+ const columns = db.prepare(`PRAGMA index_info(${name})`).all();
25208
+ return columns.map((c) => c.name).filter((c) => c !== null);
25209
+ }
24698
25210
  function columnNames(db, table, opts) {
24699
25211
  const pragma = opts?.includeGenerated ? "table_xinfo" : "table_info";
24700
25212
  const columns = db.prepare(`PRAGMA ${pragma}(${table})`).all();
@@ -24756,135 +25268,778 @@ function mapRowsTolerant(rows, map2) {
24756
25268
  return out;
24757
25269
  }
24758
25270
 
24759
- // ../../packages/persistence/src/migrations.ts
24760
- function describeObject(object2) {
24761
- return object2.kind === "column" ? `column ${object2.table}.${object2.name}` : `table ${object2.name}`;
24762
- }
24763
- function splitStatements(sql) {
24764
- return sql.split(/-->\s*statement-breakpoint/).map((s) => s.trim()).filter((s) => s.length > 0);
24765
- }
24766
- function createdIndexName(statement) {
24767
- const body = statement.replace(/^(?:\s*--[^\n]*\n?)+/, "").trimStart();
24768
- return /^CREATE (?:UNIQUE )?INDEX (?:IF NOT EXISTS )?`([^`]+)`/.exec(body)?.[1];
25271
+ // ../../packages/persistence/src/internal/outbox-lane.ts
25272
+ var OUTBOX_CAPTURE_EVENT_TYPES = ["prompt", "response", "tool_use"];
25273
+ var OUTBOX_CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25274
+
25275
+ // ../../packages/persistence/src/sync-failure.ts
25276
+ var SYNC_FAILURE_REASONS = SyncFailureReason.options;
25277
+ function syncFailureRejectCondition(column = "sync_failure") {
25278
+ const members2 = SYNC_FAILURE_REASONS.map((r) => `'${r}'`).join(", ");
25279
+ return `NEW.${column} IS NOT NULL AND NEW.${column} NOT IN (${members2})`;
24769
25280
  }
24770
- var LEGACY_DROP_MIGRATION_TAG = "0014_drop_legacy_events_findings";
24771
- function applyMigrations(db, file2) {
24772
- const legacyCount = db.prepare("PRAGMA user_version").get().user_version;
24773
- db.exec(
24774
- "CREATE TABLE IF NOT EXISTS migration_ledger (tag TEXT PRIMARY KEY, applied_at INTEGER NOT NULL)"
24775
- );
24776
- const applied = new Set(
24777
- db.prepare("SELECT tag FROM migration_ledger").all().map((r) => r.tag)
24778
- );
24779
- const preLedgerStore = applied.size === 0 && legacyCount > 0;
24780
- const record2 = db.prepare(
24781
- "INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)"
24782
- );
24783
- for (const [index, migration] of SQLITE_MIGRATIONS.entries()) {
24784
- if (applied.has(migration.tag)) continue;
24785
- if (migration.tag === LEGACY_DROP_MIGRATION_TAG) continue;
24786
- const evidence = evidenceObjects(migration.sql);
24787
- const present = evidence.filter((o) => evidenceExists(db, o));
24788
- if (present.length > 0 && present.length < evidence.length) {
24789
- const missing = evidence.filter((o) => !present.includes(o));
24790
- 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.`;
24791
- akaWarn(message);
24792
- throw new Error(`[aka] ${message}`);
24793
- }
24794
- const alreadyApplied = evidence.length > 0 ? present.length === evidence.length : preLedgerStore && index < legacyCount;
24795
- const wantsFkOff = /PRAGMA foreign_keys\s*=\s*OFF/i.test(migration.sql);
24796
- const statements = splitStatements(migration.sql);
24797
- if (wantsFkOff) db.exec("PRAGMA foreign_keys = OFF");
24798
- try {
24799
- withTransaction(
24800
- db,
24801
- () => {
24802
- for (const statement of statements) {
24803
- const indexName = createdIndexName(statement);
24804
- if (indexName === void 0) {
24805
- if (alreadyApplied) continue;
24806
- } else if (indexExists(db, indexName)) {
24807
- continue;
24808
- }
24809
- db.exec(statement);
24810
- }
24811
- if (wantsFkOff && !alreadyApplied) {
24812
- const violations = db.prepare("PRAGMA foreign_key_check").all();
24813
- if (violations.length > 0) {
24814
- throw new Error(
24815
- `[aka] sqlite migration ${migration.tag} left ${String(violations.length)} foreign-key violation(s); rolling back.`
24816
- );
24817
- }
24818
- }
24819
- record2.run(migration.tag, Date.now());
24820
- },
24821
- "IMMEDIATE"
24822
- );
24823
- } finally {
24824
- if (wantsFkOff) db.exec("PRAGMA foreign_keys = ON");
24825
- }
25281
+
25282
+ // ../../packages/persistence/src/repositories/history-sync.ts
25283
+ var STRUCTURAL_EVENT_TYPES = ["session", "llm_call", "tool_call"];
25284
+ var TYPE_LIST = STRUCTURAL_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25285
+ var CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_TYPE_LIST;
25286
+ var COUNTED_EVENT_TYPES = [
25287
+ ...STRUCTURAL_EVENT_TYPES,
25288
+ ...OUTBOX_CAPTURE_EVENT_TYPES
25289
+ ];
25290
+ var COUNTED_TYPE_LIST = COUNTED_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25291
+ var PARTITION_BUCKETS = `
25292
+ SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NULL THEN 1 ELSE 0 END) AS queued,
25293
+ SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NOT NULL THEN 1 ELSE 0 END) AS inProgress,
25294
+ SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS synced,
25295
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25296
+ AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
25297
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25298
+ AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached,
25299
+ -- Spelled as what it INCLUDES rather than what it excludes, so a reason
25300
+ -- added later lands in no bucket and fails the sum assertion, instead
25301
+ -- of silently joining this one.
25302
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25303
+ AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
25304
+ THEN 1 ELSE 0 END) AS failed,
25305
+ COUNT(*) AS total`;
25306
+ var COUNTED_SCOPE = `
25307
+ WHERE event_type IN (${COUNTED_TYPE_LIST})
25308
+ AND (
25309
+ event_type IN (${TYPE_LIST})
25310
+ OR synced_at IS NOT NULL
25311
+ OR outbox_owed = 1
25312
+ )`;
25313
+ var SKIPPED = -1;
25314
+ var HISTORY_SYNC_LEASE_STALE_MS = 6e4;
25315
+ var ROW_COLUMNS = `id,
25316
+ parent_id AS parentId,
25317
+ root_session_id AS rootSessionId,
25318
+ event_type AS eventType,
25319
+ host_id AS hostId,
25320
+ harness_id AS harnessId,
25321
+ source_project_id AS sourceProjectId,
25322
+ started_at AS startedAt,
25323
+ ended_at AS endedAt,
25324
+ severity,
25325
+ priority,
25326
+ content,
25327
+ content_hash AS contentHash,
25328
+ attributes`;
25329
+ var SqliteHistorySyncRepository = class {
25330
+ constructor(db) {
25331
+ this.db = db;
25332
+ this.ensureRowStmt = db.prepare(`INSERT OR IGNORE INTO history_sync (id) VALUES (1)`);
25333
+ this.sessionsStmt = db.prepare(
25334
+ `SELECT COALESCE(root_session_id, id) AS sessionId, MIN(started_at) AS earliest
25335
+ FROM audit_events
25336
+ WHERE synced_at IS NULL
25337
+ AND event_type IN (${TYPE_LIST})
25338
+ AND started_at < :before
25339
+ GROUP BY sessionId
25340
+ ORDER BY earliest
25341
+ LIMIT :limit`
25342
+ );
25343
+ this.rowsStmt = db.prepare(
25344
+ `SELECT ${ROW_COLUMNS}
25345
+ FROM audit_events
25346
+ WHERE synced_at IS NULL
25347
+ AND event_type IN (${TYPE_LIST})
25348
+ AND started_at < :before
25349
+ AND COALESCE(root_session_id, id) = :sessionId
25350
+ ORDER BY (event_type = 'session') DESC, started_at
25351
+ LIMIT :limit`
25352
+ );
25353
+ this.captureRowsStmt = db.prepare(
25354
+ `SELECT ${ROW_COLUMNS}
25355
+ FROM audit_events
25356
+ WHERE synced_at IS NULL
25357
+ AND sync_claimed_at IS NULL
25358
+ AND outbox_owed = 1
25359
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25360
+ AND started_at < :before
25361
+ ORDER BY started_at
25362
+ LIMIT :limit`
25363
+ );
25364
+ this.markOwedStmt = db.prepare(
25365
+ `UPDATE audit_events SET outbox_owed = 1 WHERE id = :id AND synced_at IS NULL`
25366
+ );
25367
+ this.markCaptureBacklogOwedStmt = db.prepare(
25368
+ `UPDATE audit_events SET outbox_owed = 1
25369
+ WHERE synced_at IS NULL
25370
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25371
+ AND started_at < :before`
25372
+ );
25373
+ this.stampStmt = db.prepare(
25374
+ `UPDATE audit_events
25375
+ SET synced_at = :at,
25376
+ sync_claimed_at = NULL,
25377
+ sync_failed_at = :failedAt,
25378
+ sync_failure = :failure
25379
+ WHERE id = :id`
25380
+ );
25381
+ this.claimRowStmt = db.prepare(
25382
+ `UPDATE audit_events SET sync_claimed_at = :at WHERE id = :id AND synced_at IS NULL`
25383
+ );
25384
+ this.releaseRowStmt = db.prepare(
25385
+ `UPDATE audit_events SET sync_claimed_at = NULL WHERE id = :id`
25386
+ );
25387
+ this.releaseStaleClaimsStmt = db.prepare(
25388
+ `UPDATE audit_events SET sync_claimed_at = NULL
25389
+ WHERE sync_claimed_at IS NOT NULL AND sync_claimed_at < :staleBefore`
25390
+ );
25391
+ this.partitionStmt = db.prepare(`SELECT${PARTITION_BUCKETS}
25392
+ FROM audit_events${COUNTED_SCOPE}`);
25393
+ this.partitionByKindStmt = db.prepare(
25394
+ `SELECT event_type AS kind,${PARTITION_BUCKETS}
25395
+ FROM audit_events INDEXED BY idx_audit_events_sync${COUNTED_SCOPE}
25396
+ GROUP BY event_type`
25397
+ );
25398
+ this.countsStmt = db.prepare(
25399
+ `SELECT
25400
+ SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
25401
+ SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
25402
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25403
+ AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
25404
+ THEN 1 ELSE 0 END) AS skipped,
25405
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25406
+ AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
25407
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25408
+ AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached
25409
+ FROM audit_events
25410
+ WHERE event_type IN (${TYPE_LIST})`
25411
+ );
25412
+ this.captureSkipCountStmt = db.prepare(
25413
+ // EVERY sentinel capture, whatever the reason — deliberately NOT split the
25414
+ // way the structural totals are. The split exists because a refusal is
25415
+ // terminal only against the deployment that gave it, and the structural
25416
+ // re-arm frees it on a change of deployment. The capture lane has no such
25417
+ // escape: re-arming a capture would offer one deployment's undelivered
25418
+ // prompts, with their text, to a deployment that never saw them, which is
25419
+ // exactly what disownCapturesStmt exists to prevent. So on this lane both
25420
+ // reasons mean the same thing — this row will not be sent — and splitting
25421
+ // them would put refused captures in a bucket nothing reads and nothing
25422
+ // frees.
25423
+ `SELECT COUNT(*) AS skipped
25424
+ FROM audit_events
25425
+ WHERE synced_at = ${String(SKIPPED)}
25426
+ AND event_type IN (${CAPTURE_TYPE_LIST})`
25427
+ );
25428
+ this.fingerprintStmt = db.prepare(
25429
+ `SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
25430
+ FROM history_sync WHERE id = 1`
25431
+ );
25432
+ this.setFingerprintStmt = db.prepare(
25433
+ `UPDATE history_sync
25434
+ SET endpoint_fingerprint = :fingerprint, backlog_before = :backlogBefore
25435
+ WHERE id = 1`
25436
+ );
25437
+ this.disownCapturesStmt = db.prepare(
25438
+ `UPDATE audit_events SET outbox_owed = NULL
25439
+ WHERE outbox_owed IS NOT NULL
25440
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25441
+ AND started_at < :attachedAt`
25442
+ );
25443
+ this.rearmStmt = db.prepare(
25444
+ `UPDATE audit_events
25445
+ SET synced_at = NULL, sync_failed_at = NULL, sync_failure = NULL
25446
+ WHERE (synced_at > 0
25447
+ OR sync_failure IN ('deployment_refused', 'detached_undelivered'))
25448
+ AND event_type IN (${TYPE_LIST})`
25449
+ );
25450
+ this.claimStmt = db.prepare(
25451
+ `UPDATE history_sync
25452
+ SET owner_pid = :pid, owner_host = :host, acquired_at = :now, heartbeat_at = :now
25453
+ WHERE id = 1
25454
+ AND (owner_pid IS NULL
25455
+ OR heartbeat_at IS NULL
25456
+ OR heartbeat_at < :staleBefore
25457
+ OR heartbeat_at > :now)`
25458
+ );
25459
+ this.heartbeatStmt = db.prepare(
25460
+ `UPDATE history_sync SET heartbeat_at = :now WHERE id = 1 AND owner_pid = :pid`
25461
+ );
25462
+ this.releaseStmt = db.prepare(
25463
+ `UPDATE history_sync
25464
+ SET owner_pid = NULL, owner_host = NULL, acquired_at = NULL, heartbeat_at = NULL
25465
+ WHERE id = 1 AND owner_pid = :pid`
25466
+ );
25467
+ this.closeWindowStmt = db.prepare(
25468
+ `UPDATE audit_events
25469
+ SET synced_at = ${String(SKIPPED)},
25470
+ sync_failed_at = :at,
25471
+ sync_failure = 'detached_undelivered'
25472
+ WHERE synced_at IS NULL
25473
+ AND event_type IN (${TYPE_LIST})
25474
+ AND started_at >= :attachedAt`
25475
+ );
25476
+ this.releaseBoundaryStmt = db.prepare(
25477
+ `UPDATE history_sync SET backlog_before = NULL WHERE id = 1`
25478
+ );
25479
+ this.freezeBoundaryStmt = db.prepare(
25480
+ `UPDATE history_sync SET backlog_before = :backlogBefore WHERE id = 1`
25481
+ );
25482
+ this.leaseStmt = db.prepare(
25483
+ `SELECT owner_pid AS ownerPid, owner_host AS ownerHost,
25484
+ acquired_at AS acquiredAt, heartbeat_at AS heartbeatAt
25485
+ FROM history_sync WHERE id = 1`
25486
+ );
25487
+ this.inspectionsStmt = db.prepare(
25488
+ `SELECT d.rule_id AS ruleId,
25489
+ d.name AS ruleName,
25490
+ d.version AS ruleVersion,
25491
+ d.category AS category,
25492
+ d.severity AS severity,
25493
+ f.span_start AS spanStart,
25494
+ f.span_end AS spanEnd,
25495
+ f.masked_match AS maskedMatch,
25496
+ f.action_taken AS actionTaken,
25497
+ f.confidence AS confidence
25498
+ FROM inspection_findings f
25499
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
25500
+ WHERE f.audit_event_id = :auditEventId
25501
+ ORDER BY f.span_start, f.id`
25502
+ );
24826
25503
  }
24827
- if (legacyCount < SQLITE_MIGRATIONS.length) {
24828
- db.exec(`PRAGMA user_version = ${String(SQLITE_MIGRATIONS.length)}`);
25504
+ db;
25505
+ ensureRowStmt;
25506
+ sessionsStmt;
25507
+ rowsStmt;
25508
+ stampStmt;
25509
+ countsStmt;
25510
+ fingerprintStmt;
25511
+ setFingerprintStmt;
25512
+ rearmStmt;
25513
+ claimStmt;
25514
+ heartbeatStmt;
25515
+ releaseStmt;
25516
+ leaseStmt;
25517
+ inspectionsStmt;
25518
+ closeWindowStmt;
25519
+ releaseBoundaryStmt;
25520
+ freezeBoundaryStmt;
25521
+ captureRowsStmt;
25522
+ markOwedStmt;
25523
+ markCaptureBacklogOwedStmt;
25524
+ captureSkipCountStmt;
25525
+ disownCapturesStmt;
25526
+ partitionStmt;
25527
+ partitionByKindStmt;
25528
+ claimRowStmt;
25529
+ releaseRowStmt;
25530
+ releaseStaleClaimsStmt;
25531
+ /**
25532
+ * The masked detections recorded against one tool call.
25533
+ *
25534
+ * These travel with the event because a tool call's target is not
25535
+ * re-inspectable from the event alone — unlike a capture, where the text
25536
+ * itself is re-scannable. What crosses is the masked match and the rule that
25537
+ * produced it, never the value.
25538
+ */
25539
+ inspectionsFor(auditEventId) {
25540
+ return allRows(this.inspectionsStmt, { auditEventId });
24829
25541
  }
24830
- ensureSyncedAtColumn(db, "audit_events");
24831
- ensureScanLedgerTable(db);
24832
- ensureHistorySyncTable(db);
24833
- ensureBlockedDetectionsTable(db);
24834
- ensureRuleProbeCacheTable(db);
24835
- ensureWriteGateTrigger(db);
24836
- ensureTokenUsageColumns(db);
24837
- reconcileSourceProjectIds(db);
24838
- if (!applied.has(LEGACY_DROP_MIGRATION_TAG)) {
24839
- const drained = runLegacyHistoryBackfill(db);
24840
- if (drained) applyLegacyDropMigration(db, file2);
25542
+ /**
25543
+ * Sessions with structural rows still to send, oldest first.
25544
+ *
25545
+ * BOUNDED BY THE BACKLOG BOUNDARY, which is the whole correctness of this
25546
+ * read. Anything recorded after the machine attached is the live forward
25547
+ * path's to deliver; this drain exists for what was recorded before it, and a
25548
+ * row both paths send is at best a duplicate request and at worst — for a
25549
+ * session root — an overwrite of the inventory ids the live path resolved.
25550
+ */
25551
+ pendingSessions(limit, before) {
25552
+ return allRows(this.sessionsStmt, { limit, before }).map(
25553
+ (r) => r.sessionId
25554
+ );
24841
25555
  }
24842
- }
24843
- function readLegacyTables(db) {
24844
- let holdsRows = false;
24845
- const marks = [];
24846
- for (const table of ["events", "findings"]) {
24847
- try {
24848
- const row = db.prepare(`SELECT count(*) AS n, ifnull(max(rowid), -1) AS hi FROM ${table}`).get();
24849
- if (row === void 0) {
24850
- holdsRows = true;
24851
- marks.push(`${table}:unreadable`);
24852
- continue;
24853
- }
24854
- if (row.n > 0) holdsRows = true;
24855
- marks.push(`${table}:${String(row.n)}:${String(row.hi)}`);
24856
- } catch {
24857
- holdsRows = true;
24858
- marks.push(`${table}:unreadable`);
24859
- }
25556
+ /** One session's undelivered structural rows within the backlog, root first. */
25557
+ pendingRows(sessionId, limit, before) {
25558
+ return allRows(this.rowsStmt, { sessionId, limit, before });
24860
25559
  }
24861
- return { holdsRows, mark: marks.join("|") };
24862
- }
24863
- function applyLegacyDropMigration(db, file2) {
24864
- const migration = SQLITE_MIGRATIONS.find((m) => m.tag === LEGACY_DROP_MIGRATION_TAG);
24865
- if (!migration) return;
24866
- const before = file2 === void 0 ? void 0 : readLegacyTables(db);
24867
- if (file2 !== void 0 && before?.holdsRows === true) {
24868
- try {
24869
- backupBeforeLegacyDrop(db, file2);
24870
- } catch (error61) {
24871
- akaWarn(`legacy events/findings backup failed; deferring the drop: ${String(error61)}`);
24872
- return;
24873
- }
25560
+ /**
25561
+ * Captures this machine still owes the deployment, oldest first.
25562
+ *
25563
+ * Selected by the `outbox_owed` marker the attached forward path writes, not
25564
+ * by a time window — see captureRowsStmt for why a window could not express
25565
+ * this. `before` is the grace window that leaves a just-recorded capture to
25566
+ * the live path.
25567
+ */
25568
+ pendingCaptureRows(limit, before) {
25569
+ return allRows(this.captureRowsStmt, { limit, before });
24874
25570
  }
24875
- try {
25571
+ /**
25572
+ * Record that a capture is OWED to the deployment.
25573
+ *
25574
+ * Written by the attached forward path when a live send did not confirm
25575
+ * delivery, and read by the drain as the whole of its eligibility test. It is
25576
+ * a fact rather than an inference: the machine was attached, the send did not
25577
+ * land, so the row is owed — which no time window can state, because the same
25578
+ * window that holds the rows a past attachment left owed also holds every
25579
+ * capture recorded while the machine was DETACHED, and those were never
25580
+ * offered to anyone.
25581
+ *
25582
+ * Idempotent, and never un-set: `markSynced` settling the row is what takes it
25583
+ * out of the drain's read.
25584
+ */
25585
+ markCaptureOwed(id) {
25586
+ this.markOwedStmt.run({ id });
25587
+ }
25588
+ /**
25589
+ * Mark every capture already on disk as owed, as of `before`.
25590
+ *
25591
+ * The consent-time backfill, called once from `aka attach` when a human
25592
+ * grants existing-history consent — never from an ongoing drain pass, and
25593
+ * never inferred from a boundary that could later move. `before` is the
25594
+ * caller's own "now" at the moment consent was granted, so what this marks
25595
+ * is exactly the backlog the consent prompt already counted, not whatever a
25596
+ * later re-attach or key rotation might widen it to.
25597
+ *
25598
+ * Returns how many rows matched, for the caller to log or test against. Not a
25599
+ * count of NEWLY marked rows — a row still unsynced from an earlier call
25600
+ * matches again and is counted again, the same as `UPDATE`'s own `changes`.
25601
+ */
25602
+ markCaptureBacklogOwed(before) {
25603
+ return Number(this.markCaptureBacklogOwedStmt.run({ before }).changes);
25604
+ }
25605
+ /**
25606
+ * Record delivery. Called only AFTER the far side has accepted the rows.
25607
+ *
25608
+ * CLEARS any failure reason in the same statement. A row that failed against
25609
+ * one deployment and then landed is delivered, and leaving the reason behind
25610
+ * would leave the store holding two contradictory answers about one row —
25611
+ * with the surface free to render either.
25612
+ */
25613
+ markSynced(ids, atMs) {
25614
+ this.stampAll(ids, atMs, null);
25615
+ }
25616
+ /**
25617
+ * Record that THIS MACHINE cannot express the row on the wire.
25618
+ *
25619
+ * Reserved for a local defect — a row that cannot be rebuilt into a valid
25620
+ * payload, or a body the client itself refused to send. It fails identically
25621
+ * against every deployment, so it is terminal everywhere and the re-arm leaves
25622
+ * it alone. A row that merely failed to REACH the deployment stays NULL, so it
25623
+ * is retried; marking those would turn one outage into permanent data loss.
25624
+ */
25625
+ markSkipped(ids, atMs) {
25626
+ this.stampAll(ids, SKIPPED, "payload_invalid", atMs);
25627
+ }
25628
+ /**
25629
+ * Record that THIS DEPLOYMENT refused the row.
25630
+ *
25631
+ * The same sentinel as `markSkipped`, and deliberately so: both stop the row
25632
+ * being re-offered on this lane, and `synced_at` goes on answering whether a
25633
+ * row is outstanding rather than why. What separates them is the reason, and
25634
+ * what the reason buys is the re-arm — a refusal is one deployment's verdict
25635
+ * on one body, so it is terminal only for as long as this machine points at
25636
+ * that deployment, and `rearmFor` clears it when the deployment changes.
25637
+ *
25638
+ * Leaving such a row NULL instead would be worse than the loss it replaces:
25639
+ * these reads carry no cursor, so an unstamped row the deployment refuses is
25640
+ * the head of every subsequent page, and the lane stalls behind it for ever.
25641
+ */
25642
+ markRefused(ids, atMs) {
25643
+ this.stampAll(ids, SKIPPED, "deployment_refused", atMs);
25644
+ }
25645
+ eachInTransaction(ids, run) {
25646
+ if (ids.length === 0) return;
24876
25647
  withTransaction(
24877
- db,
25648
+ this.db,
24878
25649
  () => {
24879
- const alreadyDropped = db.prepare("SELECT 1 FROM migration_ledger WHERE tag = ?").get(migration.tag);
24880
- if (alreadyDropped) return;
24881
- if (before !== void 0 && readLegacyTables(db).mark !== before.mark) {
24882
- akaWarn(
24883
- "legacy events/findings rows changed after the pre-drop snapshot decision; deferring the drop so the next open can copy them first."
24884
- );
24885
- return;
24886
- }
24887
- for (const statement of splitStatements(migration.sql)) {
25650
+ for (const id of ids) run(id);
25651
+ },
25652
+ "IMMEDIATE"
25653
+ );
25654
+ }
25655
+ stampAll(ids, value, failure, failedAtMs) {
25656
+ if (ids.length === 0) return;
25657
+ const failedAt = failure === null ? null : failedAtMs ?? null;
25658
+ withTransaction(
25659
+ this.db,
25660
+ () => {
25661
+ for (const id of ids) this.stampStmt.run({ at: value, failedAt, failure, id });
25662
+ },
25663
+ "IMMEDIATE"
25664
+ );
25665
+ }
25666
+ /**
25667
+ * Claim rows as in-flight.
25668
+ *
25669
+ * Advisory in exactly the sense the lease is: it records that a send is in
25670
+ * progress so a surface can say so, and a lost claim costs a row showing as
25671
+ * queued while it is actually being sent. It is not exclusion — the far side
25672
+ * settles a duplicate on the row id.
25673
+ */
25674
+ claimRows(ids, atMs) {
25675
+ this.eachInTransaction(ids, (id) => this.claimRowStmt.run({ at: atMs, id }));
25676
+ }
25677
+ /** Give back a claim without settling — the send failed, the row is queued again. */
25678
+ releaseRows(ids) {
25679
+ this.eachInTransaction(ids, (id) => this.releaseRowStmt.run({ id }));
25680
+ }
25681
+ /**
25682
+ * Clear claims older than `staleBefore`, and report how many were cleared.
25683
+ *
25684
+ * A process killed between claiming and settling leaves rows claimed with
25685
+ * nothing left to settle them. Without this they read as "sending" for ever.
25686
+ */
25687
+ releaseStaleClaims(staleBefore) {
25688
+ return Number(this.releaseStaleClaimsStmt.run({ staleBefore }).changes);
25689
+ }
25690
+ /**
25691
+ * Every tracked row in exactly one delivery state.
25692
+ *
25693
+ * Takes no boundary on purpose. The boundary answers "what should the drain
25694
+ * pick up now", which is a different question from "what state is this row
25695
+ * in" — and a machine that has never attached has no boundary to pass, so
25696
+ * requiring one would force a caller to invent one and report the whole store
25697
+ * as queued.
25698
+ */
25699
+ /**
25700
+ * The same partition, one row per kind that a lane carries.
25701
+ *
25702
+ * A kind with nothing to report is ABSENT rather than a row of zeros: the
25703
+ * scope decides which rows exist at all, so a kind that has never been
25704
+ * recorded — or whose captures nobody ever owed — produces no group. A caller
25705
+ * rendering a fixed list of kinds must therefore treat a missing one as "no
25706
+ * rows", never as "zero sent"; the two look identical in a bar and mean
25707
+ * different things.
25708
+ */
25709
+ partitionByKind() {
25710
+ return allRows(
25711
+ this.partitionByKindStmt,
25712
+ {}
25713
+ ).map((row) => ({
25714
+ kind: row.kind,
25715
+ queued: row.queued ?? 0,
25716
+ inProgress: row.inProgress ?? 0,
25717
+ synced: row.synced ?? 0,
25718
+ failed: row.failed ?? 0,
25719
+ refused: row.refused ?? 0,
25720
+ detached: row.detached ?? 0,
25721
+ total: row.total ?? 0
25722
+ }));
25723
+ }
25724
+ partition() {
25725
+ const row = getRow(this.partitionStmt, {});
25726
+ return {
25727
+ queued: row?.queued ?? 0,
25728
+ inProgress: row?.inProgress ?? 0,
25729
+ synced: row?.synced ?? 0,
25730
+ failed: row?.failed ?? 0,
25731
+ refused: row?.refused ?? 0,
25732
+ detached: row?.detached ?? 0,
25733
+ total: row?.total ?? 0
25734
+ };
25735
+ }
25736
+ /** `pending` counts only what is inside the backlog; sent and skipped are totals. */
25737
+ counts(before) {
25738
+ const row = getRow(this.countsStmt, { before });
25739
+ const captures = getRow(this.captureSkipCountStmt);
25740
+ return {
25741
+ pending: row?.pending ?? 0,
25742
+ sent: row?.sent ?? 0,
25743
+ skipped: row?.skipped ?? 0,
25744
+ refused: row?.refused ?? 0,
25745
+ detached: row?.detached ?? 0,
25746
+ capturesSkipped: captures?.skipped ?? 0
25747
+ };
25748
+ }
25749
+ /**
25750
+ * The deployment the current stamps were made against, and where its backlog
25751
+ * ends.
25752
+ *
25753
+ * READ-ONLY. An absent row reads as an absent deployment, which is what a
25754
+ * machine that has never drained is — and every writer below seeds the row
25755
+ * before it needs one, so nothing depends on this creating it. Keeping the
25756
+ * write off the gate path matters because the gate runs on every pass while a
25757
+ * write has to take the database's write lock.
25758
+ */
25759
+ deployment() {
25760
+ const row = getRow(
25761
+ this.fingerprintStmt
25762
+ );
25763
+ return {
25764
+ fingerprint: row?.fingerprint ?? void 0,
25765
+ backlogBefore: row?.backlogBefore ?? void 0
25766
+ };
25767
+ }
25768
+ /**
25769
+ * Point the ledger at a different deployment, discarding what it recorded
25770
+ * about the previous one.
25771
+ *
25772
+ * Delivery is a fact about ONE recipient: rows sent to the deployment a
25773
+ * machine has just left are undelivered as far as the new one is concerned.
25774
+ * All four in one transaction, so a crash between them cannot leave stamps
25775
+ * attributed to the wrong deployment, a boundary that belongs to another, or
25776
+ * a disown with no re-mark to follow it.
25777
+ *
25778
+ * The boundary is written HERE and only here, which is what freezes it: a
25779
+ * re-attach to the SAME deployment (a key rotation) leaves the fingerprint
25780
+ * unchanged, so this never runs and the backlog does not widen back over rows
25781
+ * the live path has since delivered.
25782
+ *
25783
+ * `backfillCapturesBefore` is the caller's OWN "now" at the instant a human
25784
+ * granted existing-history consent for the deployment this call is arming —
25785
+ * a DIFFERENT instant from `backlogBefore`: the re-mark boundary is the GRANT
25786
+ * instant, `backlogBefore` is the ATTACH instant, and the two can be far
25787
+ * apart. Passed only when that grant is valid, since this method has no way
25788
+ * to check consent itself and must not mark a row owed for a machine that
25789
+ * never agreed to it. Applied AFTER the disown above, in the SAME
25790
+ * transaction: what the disown clears is every marker below `backlogBefore`,
25791
+ * which includes this deployment's OWN pre-attach rows — `aka attach` calls
25792
+ * `seedCaptureBacklogOwed` at the attach instant, so every row it marks sits
25793
+ * on the cleared side of that bound — and the re-mark in the same
25794
+ * transaction is what puts those rows back. A crash between the two cannot
25795
+ * strand the ledger disowned with nothing re-marked — the transaction either
25796
+ * lands whole or not at all, and a fingerprint mismatch that has not yet
25797
+ * committed re-enters this method on the very next pass. Omit it (the
25798
+ * structural-only tests do) to exercise the disown in isolation.
25799
+ *
25800
+ * The disown is bounded by `backlogBefore`, which is what keeps it from
25801
+ * touching a marker the NEW deployment's OWN live path has already set: B's
25802
+ * live path can mark a capture owed from the moment `aka attach` writes the
25803
+ * descriptor, before the drain's first pass ever reaches this method, and
25804
+ * such a row sits at or after the bound rather than below it. What keeps the
25805
+ * disown from eating THIS SAME CALL's own re-mark is the order, not the
25806
+ * bound — disown runs first, re-mark second, both inside the one
25807
+ * transaction above.
25808
+ */
25809
+ rearmFor(fingerprint, backlogBefore, backfillCapturesBefore) {
25810
+ this.ensureRowStmt.run();
25811
+ withTransaction(
25812
+ this.db,
25813
+ () => {
25814
+ const previous = getRow(this.fingerprintStmt)?.fingerprint;
25815
+ this.rearmStmt.run();
25816
+ if (previous !== null && previous !== void 0 && previous !== fingerprint) {
25817
+ this.disownCapturesStmt.run({ attachedAt: backlogBefore });
25818
+ }
25819
+ if (backfillCapturesBefore !== void 0) {
25820
+ this.markCaptureBacklogOwedStmt.run({ before: backfillCapturesBefore });
25821
+ }
25822
+ this.setFingerprintStmt.run({ fingerprint, backlogBefore });
25823
+ },
25824
+ "IMMEDIATE"
25825
+ );
25826
+ }
25827
+ /**
25828
+ * End the attached period: hand its rows to the live path, and release the
25829
+ * boundary so the next attachment can freeze a new one.
25830
+ *
25831
+ * WITHOUT THIS, a detach and a re-attach to the same deployment leave a window
25832
+ * nothing delivers. The fingerprint is unchanged, so the boundary is never
25833
+ * re-frozen and stays at the FIRST attachment — while nothing forwards at all
25834
+ * during the detached period, because the machine is not attached. Rows
25835
+ * recorded in that window sit after the boundary and before the re-attach, so
25836
+ * neither path takes them, and the pending count reports none outstanding.
25837
+ *
25838
+ * WHAT IT RECORDS, and what it deliberately does not. These rows were the
25839
+ * closing attachment's to deliver and are no longer outstanding — that is what
25840
+ * lets the boundary move. It is NOT a claim that any of them arrived, and the
25841
+ * distinction is not academic: this used to write a delivery TIME, which every
25842
+ * read treats as delivery, so one detach turned a window of undelivered rows
25843
+ * into a window of delivered ones and no surface could tell. It writes the
25844
+ * skip sentinel and a reason of its own instead, so "no longer owed" and
25845
+ * "received" stop being the same fact.
25846
+ *
25847
+ * A change of deployment still frees them (see the re-arm), because the next
25848
+ * deployment has seen none of this machine's history — so the rows reach it
25849
+ * exactly as they did when this wrote a delivery time.
25850
+ *
25851
+ * ONE TRANSACTION, so a crash cannot release the boundary while leaving the
25852
+ * window unstamped — that half-state would re-send the whole attached period
25853
+ * on the next attach, which is the failure the boundary exists to prevent.
25854
+ */
25855
+ closeAttachedWindow(attachedAtMs, atMs) {
25856
+ this.ensureRowStmt.run();
25857
+ withTransaction(
25858
+ this.db,
25859
+ () => {
25860
+ const row = getRow(this.fingerprintStmt);
25861
+ const from = row?.backlogBefore ?? attachedAtMs;
25862
+ this.closeWindowStmt.run({ at: atMs, attachedAt: from });
25863
+ this.releaseBoundaryStmt.run();
25864
+ },
25865
+ "IMMEDIATE"
25866
+ );
25867
+ }
25868
+ /**
25869
+ * Freeze a boundary for the deployment already on file, KEEPING the stamps.
25870
+ *
25871
+ * The re-attach half of the above. Distinct from `rearmFor`, which is for a
25872
+ * different deployment and therefore discards what was delivered to the old
25873
+ * one: here the recipient is the same, so everything already sent to it stays
25874
+ * sent.
25875
+ */
25876
+ freezeBoundary(backlogBefore) {
25877
+ this.ensureRowStmt.run();
25878
+ this.freezeBoundaryStmt.run({ backlogBefore });
25879
+ }
25880
+ /** Take the claim, or report that someone live already holds it. */
25881
+ claim(pid, host, nowMs, staleAfterMs) {
25882
+ this.ensureRowStmt.run();
25883
+ let taken = false;
25884
+ withTransaction(
25885
+ this.db,
25886
+ () => {
25887
+ const result = this.claimStmt.run({
25888
+ pid,
25889
+ host,
25890
+ now: nowMs,
25891
+ staleBefore: nowMs - staleAfterMs
25892
+ });
25893
+ taken = result.changes === 1;
25894
+ },
25895
+ "IMMEDIATE"
25896
+ );
25897
+ return taken;
25898
+ }
25899
+ /** Say the holder is still alive. A no-op once the claim has moved on. */
25900
+ heartbeat(pid, nowMs) {
25901
+ this.heartbeatStmt.run({ now: nowMs, pid });
25902
+ }
25903
+ /** Give the claim up. Scoped to this holder, so a taken-over claim is left be. */
25904
+ release(pid) {
25905
+ this.releaseStmt.run({ pid });
25906
+ }
25907
+ /** Who holds the claim, if anyone. Read-only, for the same reason as above. */
25908
+ lease() {
25909
+ return getRow(this.leaseStmt);
25910
+ }
25911
+ };
25912
+
25913
+ // ../../packages/persistence/src/migrations.ts
25914
+ function describeObject(object2) {
25915
+ return object2.kind === "column" ? `column ${object2.table}.${object2.name}` : `table ${object2.name}`;
25916
+ }
25917
+ function splitStatements(sql) {
25918
+ return sql.split(/-->\s*statement-breakpoint/).map((s) => s.trim()).filter((s) => s.length > 0);
25919
+ }
25920
+ function createdIndexName(statement) {
25921
+ const body = statement.replace(/^(?:\s*--[^\n]*\n?)+/, "").trimStart();
25922
+ return /^CREATE (?:UNIQUE )?INDEX (?:IF NOT EXISTS )?`([^`]+)`/.exec(body)?.[1];
25923
+ }
25924
+ var LEGACY_DROP_MIGRATION_TAG = "0014_drop_legacy_events_findings";
25925
+ function applyMigrations(db, file2, options = {}) {
25926
+ const legacyCount = db.prepare("PRAGMA user_version").get().user_version;
25927
+ db.exec(
25928
+ "CREATE TABLE IF NOT EXISTS migration_ledger (tag TEXT PRIMARY KEY, applied_at INTEGER NOT NULL)"
25929
+ );
25930
+ const applied = new Set(
25931
+ db.prepare("SELECT tag FROM migration_ledger").all().map((r) => r.tag)
25932
+ );
25933
+ const preLedgerStore = applied.size === 0 && legacyCount > 0;
25934
+ const record2 = db.prepare(
25935
+ "INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)"
25936
+ );
25937
+ for (const [index, migration] of SQLITE_MIGRATIONS.entries()) {
25938
+ if (applied.has(migration.tag)) continue;
25939
+ if (options.skipTags?.has(migration.tag) === true) continue;
25940
+ if (migration.tag === LEGACY_DROP_MIGRATION_TAG) continue;
25941
+ const evidence = evidenceObjects(migration.sql);
25942
+ const present = evidence.filter((o) => evidenceExists(db, o));
25943
+ if (present.length > 0 && present.length < evidence.length) {
25944
+ const missing = evidence.filter((o) => !present.includes(o));
25945
+ 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.`;
25946
+ akaWarn(message);
25947
+ throw new Error(`[aka] ${message}`);
25948
+ }
25949
+ const alreadyApplied = evidence.length > 0 ? present.length === evidence.length : preLedgerStore && index < legacyCount;
25950
+ const wantsFkOff = /PRAGMA foreign_keys\s*=\s*OFF/i.test(migration.sql);
25951
+ const statements = splitStatements(migration.sql);
25952
+ if (wantsFkOff) db.exec("PRAGMA foreign_keys = OFF");
25953
+ try {
25954
+ withTransaction(
25955
+ db,
25956
+ () => {
25957
+ for (const statement of statements) {
25958
+ const indexName = createdIndexName(statement);
25959
+ if (indexName === void 0) {
25960
+ if (alreadyApplied) continue;
25961
+ } else if (indexExists(db, indexName)) {
25962
+ continue;
25963
+ }
25964
+ db.exec(statement);
25965
+ }
25966
+ if (wantsFkOff && !alreadyApplied) {
25967
+ const violations = db.prepare("PRAGMA foreign_key_check").all();
25968
+ if (violations.length > 0) {
25969
+ throw new Error(
25970
+ `[aka] sqlite migration ${migration.tag} left ${String(violations.length)} foreign-key violation(s); rolling back.`
25971
+ );
25972
+ }
25973
+ }
25974
+ record2.run(migration.tag, Date.now());
25975
+ },
25976
+ "IMMEDIATE"
25977
+ );
25978
+ } finally {
25979
+ if (wantsFkOff) db.exec("PRAGMA foreign_keys = ON");
25980
+ }
25981
+ }
25982
+ if (legacyCount < SQLITE_MIGRATIONS.length) {
25983
+ db.exec(`PRAGMA user_version = ${String(SQLITE_MIGRATIONS.length)}`);
25984
+ }
25985
+ ensureSyncedAtColumn(db, "audit_events");
25986
+ ensureScanLedgerTable(db);
25987
+ ensureHistorySyncTable(db);
25988
+ ensureBlockedDetectionsTable(db);
25989
+ ensureRuleProbeCacheTable(db);
25990
+ ensureWriteGateTrigger(db);
25991
+ ensureTokenUsageColumns(db);
25992
+ reconcileSourceProjectIds(db);
25993
+ if (!applied.has(LEGACY_DROP_MIGRATION_TAG)) {
25994
+ const drained = runLegacyHistoryBackfill(db);
25995
+ if (drained) applyLegacyDropMigration(db, file2);
25996
+ }
25997
+ }
25998
+ function readLegacyTables(db) {
25999
+ let holdsRows = false;
26000
+ const marks = [];
26001
+ for (const table of ["events", "findings"]) {
26002
+ try {
26003
+ const row = db.prepare(`SELECT count(*) AS n, ifnull(max(rowid), -1) AS hi FROM ${table}`).get();
26004
+ if (row === void 0) {
26005
+ holdsRows = true;
26006
+ marks.push(`${table}:unreadable`);
26007
+ continue;
26008
+ }
26009
+ if (row.n > 0) holdsRows = true;
26010
+ marks.push(`${table}:${String(row.n)}:${String(row.hi)}`);
26011
+ } catch {
26012
+ holdsRows = true;
26013
+ marks.push(`${table}:unreadable`);
26014
+ }
26015
+ }
26016
+ return { holdsRows, mark: marks.join("|") };
26017
+ }
26018
+ function applyLegacyDropMigration(db, file2) {
26019
+ const migration = SQLITE_MIGRATIONS.find((m) => m.tag === LEGACY_DROP_MIGRATION_TAG);
26020
+ if (!migration) return;
26021
+ const before = file2 === void 0 ? void 0 : readLegacyTables(db);
26022
+ if (file2 !== void 0 && before?.holdsRows === true) {
26023
+ try {
26024
+ backupBeforeLegacyDrop(db, file2);
26025
+ } catch (error61) {
26026
+ akaWarn(`legacy events/findings backup failed; deferring the drop: ${String(error61)}`);
26027
+ return;
26028
+ }
26029
+ }
26030
+ try {
26031
+ withTransaction(
26032
+ db,
26033
+ () => {
26034
+ const alreadyDropped = db.prepare("SELECT 1 FROM migration_ledger WHERE tag = ?").get(migration.tag);
26035
+ if (alreadyDropped) return;
26036
+ if (before !== void 0 && readLegacyTables(db).mark !== before.mark) {
26037
+ akaWarn(
26038
+ "legacy events/findings rows changed after the pre-drop snapshot decision; deferring the drop so the next open can copy them first."
26039
+ );
26040
+ return;
26041
+ }
26042
+ for (const statement of splitStatements(migration.sql)) {
24888
26043
  db.exec(statement);
24889
26044
  }
24890
26045
  db.prepare("INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)").run(
@@ -25188,10 +26343,62 @@ function ensureSyncedAtColumn(db, table) {
25188
26343
  if (!columns.includes("outbox_owed")) {
25189
26344
  db.exec(`ALTER TABLE ${table} ADD COLUMN outbox_owed integer`);
25190
26345
  }
26346
+ if (!columns.includes("sync_failed_at")) {
26347
+ db.exec(`ALTER TABLE ${table} ADD COLUMN sync_failed_at integer`);
26348
+ }
26349
+ if (!columns.includes("sync_failure")) {
26350
+ withTransaction(
26351
+ db,
26352
+ () => {
26353
+ db.exec(`ALTER TABLE ${table} ADD COLUMN sync_failure text`);
26354
+ db.exec(
26355
+ `UPDATE ${table} SET synced_at = NULL
26356
+ WHERE synced_at = -1
26357
+ AND event_type IN (${COUNTED_EVENT_TYPES.map((t) => `'${t}'`).join(", ")})`
26358
+ );
26359
+ },
26360
+ "IMMEDIATE"
26361
+ );
26362
+ }
25191
26363
  db.exec(
25192
- `CREATE INDEX IF NOT EXISTS idx_audit_events_sync
25193
- ON audit_events (event_type, synced_at, sync_claimed_at, started_at)`
26364
+ `CREATE TRIGGER IF NOT EXISTS aka_sync_failure_guard
26365
+ BEFORE UPDATE OF sync_failure ON ${table}
26366
+ WHEN ${syncFailureRejectCondition()}
26367
+ BEGIN SELECT RAISE(ABORT, 'sync_failure is not one of the recorded reasons'); END`
25194
26368
  );
26369
+ const syncIndexColumns = [
26370
+ "event_type",
26371
+ "synced_at",
26372
+ "sync_claimed_at",
26373
+ "started_at",
26374
+ // Appended LAST on purpose. The delivery-state read now projects it, so it
26375
+ // has to be in the index for the read to stay covered — but putting it
26376
+ // ahead of `started_at` would reorder the prefix the structural drain's
26377
+ // reads match on.
26378
+ "sync_failure"
26379
+ // `outbox_owed` is DELIBERATELY ABSENT, and it was measured both ways.
26380
+ //
26381
+ // The delivery-state read tests it — a capture's state depends on whether a
26382
+ // live forward marked it owed — so carrying it here makes that read covering
26383
+ // rather than a row fetch per row: 16 ms against 40 ms on a real 6 GB store.
26384
+ // But a sixth column changes what the planner charges for this index, and
26385
+ // with no ANALYZE statistics it plans from schema shape alone: measured, it
26386
+ // then stops choosing the per-session index for the token rollup and walks
26387
+ // every `llm_call` in the store through the event-type index instead. That
26388
+ // read grows with the store; this one does not.
26389
+ //
26390
+ // 40 ms on the largest store measured, once per render, is a cost worth
26391
+ // paying to leave every other read's plan where it was.
26392
+ ];
26393
+ const currentSyncIndex = indexColumns(db, "idx_audit_events_sync");
26394
+ const syncIndexMatches = currentSyncIndex.length === syncIndexColumns.length && currentSyncIndex.every((column, i) => column === syncIndexColumns[i]);
26395
+ if (!syncIndexMatches) {
26396
+ db.exec("DROP INDEX IF EXISTS idx_audit_events_sync");
26397
+ db.exec(
26398
+ `CREATE INDEX idx_audit_events_sync
26399
+ ON audit_events (${syncIndexColumns.join(", ")})`
26400
+ );
26401
+ }
25195
26402
  db.exec(
25196
26403
  `CREATE INDEX IF NOT EXISTS idx_audit_outbox_owed
25197
26404
  ON audit_events (event_type, synced_at, sync_claimed_at, started_at) WHERE outbox_owed = 1`
@@ -25413,7 +26620,11 @@ function buildAuditEvent(row) {
25413
26620
  link: linkParsed?.success ? linkParsed.data : null,
25414
26621
  targetId: row.target_id,
25415
26622
  internal: intToBool(row.internal),
25416
- flagged: intToBool(row.flagged)
26623
+ flagged: intToBool(row.flagged),
26624
+ // Only meaningful when the title came out empty — a row whose body was
26625
+ // expired but whose title fell back to `tool_name` still has something to
26626
+ // render, and flagging it would make the view apologise for nothing.
26627
+ bodyExpired: row.content_expired_at !== null && (row.title ?? "") === ""
25417
26628
  };
25418
26629
  }
25419
26630
  var TIMELINE_COLUMNS = `
@@ -25421,6 +26632,7 @@ var TIMELINE_COLUMNS = `
25421
26632
  event_type,
25422
26633
  started_at,
25423
26634
  coalesce(content, json_extract(attributes, '$.tool_name')) AS title,
26635
+ content_expired_at,
25424
26636
  coalesce(json_extract(attributes, '$.detail'), json_extract(attributes, '$.target')) AS detail,
25425
26637
  coalesce(json_extract(attributes, '$.tool_name'), json_extract(attributes, '$.tool')) AS tool,
25426
26638
  json_extract(attributes, '$.severity') AS severity,
@@ -25463,7 +26675,7 @@ var SESSION_ROOT = `event_type = 'session'`;
25463
26675
  var HAS_ACTIVITY = `EXISTS (
25464
26676
  SELECT 1 FROM audit_events c
25465
26677
  WHERE c.root_session_id = audit_events.id
25466
- AND c.event_type NOT IN ('hook', 'config_scan'))`;
26678
+ AND c.event_type NOT IN ('hook', 'config_scan', 'capture_status'))`;
25467
26679
  var SqliteActivityRepository = class {
25468
26680
  constructor(db, now = () => Date.now()) {
25469
26681
  this.db = db;
@@ -25490,10 +26702,10 @@ var SqliteActivityRepository = class {
25490
26702
  SELECT id FROM audit_events WHERE event_type = 'session' AND started_at >= ?
25491
26703
  UNION
25492
26704
  SELECT root_session_id FROM audit_events INDEXED BY idx_audit_started_at
25493
- WHERE started_at >= ?
26705
+ WHERE started_at >= ? AND event_type <> 'capture_status'
25494
26706
  UNION
25495
26707
  SELECT root_session_id FROM audit_events INDEXED BY idx_audit_ended_at
25496
- WHERE ended_at >= ?)`,
26708
+ WHERE ended_at >= ? AND event_type <> 'capture_status')`,
25497
26709
  [liveThreshold, liveThreshold, liveThreshold]
25498
26710
  );
25499
26711
  const toolCallsToday = countScalar(
@@ -25900,7 +27112,10 @@ var SqliteAuditEventsRepository = class {
25900
27112
  attributes = excluded.attributes,
25901
27113
  ended_at = excluded.ended_at
25902
27114
  WHERE COALESCE(json_extract(excluded.attributes, '$.output_tokens'), 0)
25903
- > COALESCE(json_extract(audit_events.attributes, '$.output_tokens'), 0)`
27115
+ > COALESCE(json_extract(audit_events.attributes, '$.output_tokens'), 0)
27116
+ OR (json_extract(excluded.attributes, '$.usage_source') IS NOT NULL
27117
+ AND json_extract(excluded.attributes, '$.output_tokens') IS NULL
27118
+ AND excluded.attributes <> audit_events.attributes)`
25904
27119
  );
25905
27120
  this.upsertSessionRootStmt = db.prepare(
25906
27121
  `INSERT OR IGNORE INTO audit_events
@@ -26086,6 +27301,169 @@ var SqliteAuditEventsRepository = class {
26086
27301
  }
26087
27302
  };
26088
27303
 
27304
+ // ../../packages/persistence/src/repositories/body-retention.ts
27305
+ var DEFAULT_BATCH_SIZE = 500;
27306
+ var DEFAULT_MAX_ROWS = 5e4;
27307
+ var SYNC_LANE_TYPES_SQL = OUTBOX_CAPTURE_TYPE_LIST;
27308
+ var SqliteBodyRetentionRepository = class {
27309
+ constructor(db) {
27310
+ this.db = db;
27311
+ const select = (laneClause) => `
27312
+ SELECT id, LENGTH(CAST(content AS BLOB)) AS bytes
27313
+ FROM audit_events
27314
+ WHERE content IS NOT NULL
27315
+ AND started_at < :cutoff
27316
+ AND event_type IN (${CAPTURE_EVENT_TYPES_SQL})
27317
+ ${laneClause}
27318
+ ORDER BY started_at
27319
+ LIMIT :limit`;
27320
+ this.candidatesStmt = this.db.prepare(select(""));
27321
+ this.candidatesSyncSafeStmt = this.db.prepare(
27322
+ select(`AND (event_type NOT IN (${SYNC_LANE_TYPES_SQL}) OR synced_at IS NOT NULL)`)
27323
+ );
27324
+ this.heldBySyncStmt = this.db.prepare(`
27325
+ SELECT COUNT(*) AS n
27326
+ FROM audit_events
27327
+ WHERE content IS NOT NULL
27328
+ AND started_at < :cutoff
27329
+ AND event_type IN (${SYNC_LANE_TYPES_SQL})
27330
+ AND synced_at IS NULL`);
27331
+ this.expireStmt = this.db.prepare(
27332
+ `UPDATE audit_events SET content = NULL, content_expired_at = :now WHERE id = :id`
27333
+ );
27334
+ }
27335
+ db;
27336
+ candidatesStmt;
27337
+ candidatesSyncSafeStmt;
27338
+ heldBySyncStmt;
27339
+ expireStmt;
27340
+ /** How many bytes a pass with these options would free, changing nothing. */
27341
+ preview(opts) {
27342
+ const limit = opts.maxRows ?? DEFAULT_MAX_ROWS;
27343
+ const stmt = opts.sweepSyncLane ? this.candidatesStmt : this.candidatesSyncSafeStmt;
27344
+ const rows = stmt.all({ cutoff: opts.cutoff, limit });
27345
+ return {
27346
+ rowsExpired: rows.length,
27347
+ bytesFreed: rows.reduce((sum, r) => sum + r.bytes, 0),
27348
+ rowsHeldBySync: this.countHeldBySync(opts)
27349
+ };
27350
+ }
27351
+ /** Clear eligible bodies, in bounded batches. */
27352
+ expire(opts) {
27353
+ const batchSize = opts.batchSize ?? DEFAULT_BATCH_SIZE;
27354
+ const maxRows = opts.maxRows ?? DEFAULT_MAX_ROWS;
27355
+ const stmt = opts.sweepSyncLane ? this.candidatesStmt : this.candidatesSyncSafeStmt;
27356
+ let rowsExpired = 0;
27357
+ let bytesFreed = 0;
27358
+ let done = true;
27359
+ while (rowsExpired < maxRows) {
27360
+ const remaining = Math.min(batchSize, maxRows - rowsExpired);
27361
+ const batch = stmt.all({ cutoff: opts.cutoff, limit: remaining });
27362
+ if (batch.length === 0) break;
27363
+ withTransaction(
27364
+ this.db,
27365
+ () => {
27366
+ for (const row of batch) this.expireStmt.run({ id: row.id, now: opts.now });
27367
+ },
27368
+ "IMMEDIATE"
27369
+ );
27370
+ rowsExpired += batch.length;
27371
+ bytesFreed += batch.reduce((sum, r) => sum + r.bytes, 0);
27372
+ if (batch.length < remaining) break;
27373
+ if (rowsExpired >= maxRows) {
27374
+ done = stmt.all({ cutoff: opts.cutoff, limit: 1 }).length === 0;
27375
+ }
27376
+ }
27377
+ return { rowsExpired, bytesFreed, rowsHeldBySync: this.countHeldBySync(opts), done };
27378
+ }
27379
+ countHeldBySync(opts) {
27380
+ if (opts.sweepSyncLane) return 0;
27381
+ const row = this.heldBySyncStmt.get({ cutoff: opts.cutoff });
27382
+ return row.n;
27383
+ }
27384
+ };
27385
+
27386
+ // ../../packages/persistence/src/repositories/capture-status.ts
27387
+ var STATUS_LOOKBACK_ROWS = 128;
27388
+ var SqliteCaptureStatusRepository = class {
27389
+ constructor(db) {
27390
+ this.db = db;
27391
+ this.recentStmt = db.prepare(
27392
+ `SELECT a.started_at AS startedAt,
27393
+ a.attributes AS attributes,
27394
+ a.root_session_id AS rootSessionId
27395
+ FROM audit_events a
27396
+ WHERE a.event_type = 'capture_status'
27397
+ AND a.source_tool = ?
27398
+ AND a.started_at >= ?
27399
+ ORDER BY a.started_at DESC, a.id DESC
27400
+ LIMIT ?`
27401
+ );
27402
+ }
27403
+ db;
27404
+ recentStmt;
27405
+ /**
27406
+ * Every document that reported for a site, in registry order by site, from
27407
+ * the last `CAPTURE_STATUS_RECENCY_MS`.
27408
+ *
27409
+ * SEVERAL per site, not one: a browser is many documents and each reports
27410
+ * for itself, so one row per site is a choice about which of them a user
27411
+ * sees — and the newest is the wrong one, since a healthy tab writing a
27412
+ * fresh report would hide a drifting tab's verdict, which is the whole
27413
+ * reason these rows exist. The pick WITHIN a document is made here (the
27414
+ * unchanged `pickReportedCaptureStatus`, over that document's own rows);
27415
+ * choosing between documents belongs where the state semantics live, and
27416
+ * that is `reportedCaptureDocumentForSite` in `@akasecurity/detections` —
27417
+ * this package may not import it.
27418
+ *
27419
+ * `now` is a required argument rather than a `Date.now()` read, so a caller
27420
+ * that already holds a render instant passes THAT one and a test can drive
27421
+ * the window without moving the wall clock.
27422
+ *
27423
+ * A site whose reports have all aged out contributes nothing, so it derives
27424
+ * to `unreported`. That is the point: nothing but the browser extension ever
27425
+ * writes these rows, so an uninstalled extension's last verdict would
27426
+ * otherwise stand as a live claim for ever with no later report able to
27427
+ * clear it.
27428
+ */
27429
+ latest(now) {
27430
+ const since = now - CAPTURE_STATUS_RECENCY_MS;
27431
+ const documents = [];
27432
+ for (const tool of WebSourceTool.options) {
27433
+ const rows = /* @__PURE__ */ new Map();
27434
+ const lastWord = /* @__PURE__ */ new Map();
27435
+ for (const row of allRows(this.recentStmt, [
27436
+ tool,
27437
+ since,
27438
+ STATUS_LOOKBACK_ROWS
27439
+ ])) {
27440
+ const status = fromCaptureStatusAttributes(parseJsonObject(row.attributes));
27441
+ if (status === null) continue;
27442
+ const record2 = { tool, observedAt: epochMillisToIso(row.startedAt), status };
27443
+ const group = rows.get(row.rootSessionId);
27444
+ if (group === void 0) {
27445
+ rows.set(row.rootSessionId, [record2]);
27446
+ lastWord.set(row.rootSessionId, { at: record2.observedAt, closed: status.closed });
27447
+ } else {
27448
+ group.push(record2);
27449
+ }
27450
+ }
27451
+ for (const [root, candidates] of rows) {
27452
+ const picked = pickReportedCaptureStatus(candidates);
27453
+ const last = lastWord.get(root);
27454
+ if (picked === void 0 || last === void 0) continue;
27455
+ documents.push({
27456
+ ...picked,
27457
+ ...root === null ? {} : { rootSessionId: root },
27458
+ lastReportAt: last.at,
27459
+ closed: last.closed
27460
+ });
27461
+ }
27462
+ }
27463
+ return documents;
27464
+ }
27465
+ };
27466
+
26089
27467
  // ../../packages/persistence/src/repositories/classified-data.ts
26090
27468
  var SqliteClassifiedDataRepository = class {
26091
27469
  constructor(db) {
@@ -26914,7 +28292,15 @@ function toFlatFindingRow(r) {
26914
28292
  ...r.tool_name === null ? {} : { toolName: r.tool_name },
26915
28293
  eventId: r.event_id,
26916
28294
  ...r.session_id === null ? {} : { sessionId: r.session_id },
26917
- status: deriveInstanceStatus(r)
28295
+ status: deriveInstanceStatus(r),
28296
+ delivery: deriveFindingDelivery({
28297
+ kind: r.kind,
28298
+ syncedAt: r.synced_at,
28299
+ syncClaimedAt: r.sync_claimed_at,
28300
+ syncFailedAt: r.sync_failed_at,
28301
+ syncFailure: r.sync_failure,
28302
+ outboxOwed: r.outbox_owed
28303
+ })
26918
28304
  };
26919
28305
  }
26920
28306
  function encodeGroupCursor(group) {
@@ -26978,7 +28364,10 @@ var FINDING_ROW_COLUMNS_SQL = `f.id AS id, d.rule_id AS rule_id, d.category AS c
26978
28364
  e.tool_name AS tool_name,
26979
28365
  f.audit_event_id AS event_id, e.root_session_id AS session_id,
26980
28366
  e.event_type AS kind, f.finding_key AS finding_key,
26981
- ${latestResolutionStatusSql("f")} AS latest_status`;
28367
+ ${latestResolutionStatusSql("f")} AS latest_status,
28368
+ e.synced_at AS synced_at, e.sync_claimed_at AS sync_claimed_at,
28369
+ e.sync_failed_at AS sync_failed_at, e.sync_failure AS sync_failure,
28370
+ e.outbox_owed AS outbox_owed`;
26982
28371
  var DAY_MS3 = 864e5;
26983
28372
  var SqliteFindingsRepository = class {
26984
28373
  constructor(db) {
@@ -27223,6 +28612,7 @@ var SqliteFindingsRepository = class {
27223
28612
  providers: query.provider,
27224
28613
  actions: query.action,
27225
28614
  statuses: query.status,
28615
+ deliveries: query.deployment,
27226
28616
  tools: query.tool,
27227
28617
  repo: query.repo,
27228
28618
  file: query.file,
@@ -27290,6 +28680,7 @@ var SqliteFindingsRepository = class {
27290
28680
  providers: query.provider,
27291
28681
  actions: query.action,
27292
28682
  statuses: query.status,
28683
+ deliveries: query.deployment,
27293
28684
  tools: query.tool,
27294
28685
  q: query.q
27295
28686
  };
@@ -27553,7 +28944,9 @@ var SqliteFindingsRepository = class {
27553
28944
  )
27554
28945
  );
27555
28946
  for (const row of grouped) {
27556
- if (row.action_taken in byAction) byAction[row.action_taken] = row.c;
28947
+ if (Object.hasOwn(byAction, row.action_taken)) {
28948
+ byAction[row.action_taken] = row.c;
28949
+ }
27557
28950
  }
27558
28951
  const bySeverity = { critical: 0, high: 0, medium: 0, low: 0 };
27559
28952
  const sevRows = allRows(
@@ -27570,7 +28963,9 @@ var SqliteFindingsRepository = class {
27570
28963
  )
27571
28964
  );
27572
28965
  for (const row of sevRows) {
27573
- if (row.severity in bySeverity) bySeverity[row.severity] = row.c;
28966
+ if (Object.hasOwn(bySeverity, row.severity)) {
28967
+ bySeverity[row.severity] = row.c;
28968
+ }
27574
28969
  }
27575
28970
  const categories = ENFORCEABLE_CATEGORIES;
27576
28971
  const enabledRows = allRows(
@@ -27619,525 +29014,6 @@ function isoDay(ms) {
27619
29014
  return new Date(ms).toISOString().slice(0, 10);
27620
29015
  }
27621
29016
 
27622
- // ../../packages/persistence/src/repositories/history-sync.ts
27623
- var STRUCTURAL_EVENT_TYPES = ["session", "llm_call", "tool_call"];
27624
- var TYPE_LIST = STRUCTURAL_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
27625
- var OUTBOX_CAPTURE_EVENT_TYPES = ["prompt", "response", "tool_use"];
27626
- var CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
27627
- var SKIPPED = -1;
27628
- var ROW_COLUMNS = `id,
27629
- parent_id AS parentId,
27630
- root_session_id AS rootSessionId,
27631
- event_type AS eventType,
27632
- host_id AS hostId,
27633
- harness_id AS harnessId,
27634
- source_project_id AS sourceProjectId,
27635
- started_at AS startedAt,
27636
- ended_at AS endedAt,
27637
- severity,
27638
- priority,
27639
- content,
27640
- content_hash AS contentHash,
27641
- attributes`;
27642
- var SqliteHistorySyncRepository = class {
27643
- constructor(db) {
27644
- this.db = db;
27645
- this.ensureRowStmt = db.prepare(`INSERT OR IGNORE INTO history_sync (id) VALUES (1)`);
27646
- this.sessionsStmt = db.prepare(
27647
- `SELECT COALESCE(root_session_id, id) AS sessionId, MIN(started_at) AS earliest
27648
- FROM audit_events
27649
- WHERE synced_at IS NULL
27650
- AND event_type IN (${TYPE_LIST})
27651
- AND started_at < :before
27652
- GROUP BY sessionId
27653
- ORDER BY earliest
27654
- LIMIT :limit`
27655
- );
27656
- this.rowsStmt = db.prepare(
27657
- `SELECT ${ROW_COLUMNS}
27658
- FROM audit_events
27659
- WHERE synced_at IS NULL
27660
- AND event_type IN (${TYPE_LIST})
27661
- AND started_at < :before
27662
- AND COALESCE(root_session_id, id) = :sessionId
27663
- ORDER BY (event_type = 'session') DESC, started_at
27664
- LIMIT :limit`
27665
- );
27666
- this.captureRowsStmt = db.prepare(
27667
- `SELECT ${ROW_COLUMNS}
27668
- FROM audit_events
27669
- WHERE synced_at IS NULL
27670
- AND sync_claimed_at IS NULL
27671
- AND outbox_owed = 1
27672
- AND event_type IN (${CAPTURE_TYPE_LIST})
27673
- AND started_at < :before
27674
- ORDER BY started_at
27675
- LIMIT :limit`
27676
- );
27677
- this.markOwedStmt = db.prepare(
27678
- `UPDATE audit_events SET outbox_owed = 1 WHERE id = :id AND synced_at IS NULL`
27679
- );
27680
- this.markCaptureBacklogOwedStmt = db.prepare(
27681
- `UPDATE audit_events SET outbox_owed = 1
27682
- WHERE synced_at IS NULL
27683
- AND event_type IN (${CAPTURE_TYPE_LIST})
27684
- AND started_at < :before`
27685
- );
27686
- this.stampStmt = db.prepare(
27687
- `UPDATE audit_events SET synced_at = :at, sync_claimed_at = NULL WHERE id = :id`
27688
- );
27689
- this.claimRowStmt = db.prepare(
27690
- `UPDATE audit_events SET sync_claimed_at = :at WHERE id = :id AND synced_at IS NULL`
27691
- );
27692
- this.releaseRowStmt = db.prepare(
27693
- `UPDATE audit_events SET sync_claimed_at = NULL WHERE id = :id`
27694
- );
27695
- this.releaseStaleClaimsStmt = db.prepare(
27696
- `UPDATE audit_events SET sync_claimed_at = NULL
27697
- WHERE sync_claimed_at IS NOT NULL AND sync_claimed_at < :staleBefore`
27698
- );
27699
- this.partitionStmt = db.prepare(
27700
- `SELECT
27701
- SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NULL THEN 1 ELSE 0 END) AS queued,
27702
- SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NOT NULL THEN 1 ELSE 0 END) AS inProgress,
27703
- SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS synced,
27704
- SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0 THEN 1 ELSE 0 END) AS failed,
27705
- COUNT(*) AS total
27706
- FROM audit_events
27707
- WHERE event_type IN (${TYPE_LIST})`
27708
- );
27709
- this.countsStmt = db.prepare(
27710
- `SELECT
27711
- SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
27712
- SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
27713
- SUM(CASE WHEN synced_at = ${String(SKIPPED)} THEN 1 ELSE 0 END) AS skipped
27714
- FROM audit_events
27715
- WHERE event_type IN (${TYPE_LIST})`
27716
- );
27717
- this.captureSkipCountStmt = db.prepare(
27718
- `SELECT COUNT(*) AS skipped
27719
- FROM audit_events
27720
- WHERE synced_at = ${String(SKIPPED)}
27721
- AND event_type IN (${CAPTURE_TYPE_LIST})`
27722
- );
27723
- this.fingerprintStmt = db.prepare(
27724
- `SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
27725
- FROM history_sync WHERE id = 1`
27726
- );
27727
- this.setFingerprintStmt = db.prepare(
27728
- `UPDATE history_sync
27729
- SET endpoint_fingerprint = :fingerprint, backlog_before = :backlogBefore
27730
- WHERE id = 1`
27731
- );
27732
- this.disownCapturesStmt = db.prepare(
27733
- `UPDATE audit_events SET outbox_owed = NULL
27734
- WHERE outbox_owed IS NOT NULL
27735
- AND event_type IN (${CAPTURE_TYPE_LIST})
27736
- AND started_at < :attachedAt`
27737
- );
27738
- this.rearmStmt = db.prepare(
27739
- `UPDATE audit_events SET synced_at = NULL
27740
- WHERE synced_at > 0 AND event_type IN (${TYPE_LIST})`
27741
- );
27742
- this.claimStmt = db.prepare(
27743
- `UPDATE history_sync
27744
- SET owner_pid = :pid, owner_host = :host, acquired_at = :now, heartbeat_at = :now
27745
- WHERE id = 1
27746
- AND (owner_pid IS NULL
27747
- OR heartbeat_at IS NULL
27748
- OR heartbeat_at < :staleBefore
27749
- OR heartbeat_at > :now)`
27750
- );
27751
- this.heartbeatStmt = db.prepare(
27752
- `UPDATE history_sync SET heartbeat_at = :now WHERE id = 1 AND owner_pid = :pid`
27753
- );
27754
- this.releaseStmt = db.prepare(
27755
- `UPDATE history_sync
27756
- SET owner_pid = NULL, owner_host = NULL, acquired_at = NULL, heartbeat_at = NULL
27757
- WHERE id = 1 AND owner_pid = :pid`
27758
- );
27759
- this.closeWindowStmt = db.prepare(
27760
- `UPDATE audit_events SET synced_at = :at
27761
- WHERE synced_at IS NULL
27762
- AND event_type IN (${TYPE_LIST})
27763
- AND started_at >= :attachedAt`
27764
- );
27765
- this.releaseBoundaryStmt = db.prepare(
27766
- `UPDATE history_sync SET backlog_before = NULL WHERE id = 1`
27767
- );
27768
- this.freezeBoundaryStmt = db.prepare(
27769
- `UPDATE history_sync SET backlog_before = :backlogBefore WHERE id = 1`
27770
- );
27771
- this.leaseStmt = db.prepare(
27772
- `SELECT owner_pid AS ownerPid, owner_host AS ownerHost,
27773
- acquired_at AS acquiredAt, heartbeat_at AS heartbeatAt
27774
- FROM history_sync WHERE id = 1`
27775
- );
27776
- this.inspectionsStmt = db.prepare(
27777
- `SELECT d.rule_id AS ruleId,
27778
- d.name AS ruleName,
27779
- d.version AS ruleVersion,
27780
- d.category AS category,
27781
- d.severity AS severity,
27782
- f.span_start AS spanStart,
27783
- f.span_end AS spanEnd,
27784
- f.masked_match AS maskedMatch,
27785
- f.action_taken AS actionTaken,
27786
- f.confidence AS confidence
27787
- FROM inspection_findings f
27788
- JOIN inspection_definitions d ON d.id = f.inspection_definition_id
27789
- WHERE f.audit_event_id = :auditEventId
27790
- ORDER BY f.span_start, f.id`
27791
- );
27792
- }
27793
- db;
27794
- ensureRowStmt;
27795
- sessionsStmt;
27796
- rowsStmt;
27797
- stampStmt;
27798
- countsStmt;
27799
- fingerprintStmt;
27800
- setFingerprintStmt;
27801
- rearmStmt;
27802
- claimStmt;
27803
- heartbeatStmt;
27804
- releaseStmt;
27805
- leaseStmt;
27806
- inspectionsStmt;
27807
- closeWindowStmt;
27808
- releaseBoundaryStmt;
27809
- freezeBoundaryStmt;
27810
- captureRowsStmt;
27811
- markOwedStmt;
27812
- markCaptureBacklogOwedStmt;
27813
- captureSkipCountStmt;
27814
- disownCapturesStmt;
27815
- partitionStmt;
27816
- claimRowStmt;
27817
- releaseRowStmt;
27818
- releaseStaleClaimsStmt;
27819
- /**
27820
- * The masked detections recorded against one tool call.
27821
- *
27822
- * These travel with the event because a tool call's target is not
27823
- * re-inspectable from the event alone — unlike a capture, where the text
27824
- * itself is re-scannable. What crosses is the masked match and the rule that
27825
- * produced it, never the value.
27826
- */
27827
- inspectionsFor(auditEventId) {
27828
- return allRows(this.inspectionsStmt, { auditEventId });
27829
- }
27830
- /**
27831
- * Sessions with structural rows still to send, oldest first.
27832
- *
27833
- * BOUNDED BY THE BACKLOG BOUNDARY, which is the whole correctness of this
27834
- * read. Anything recorded after the machine attached is the live forward
27835
- * path's to deliver; this drain exists for what was recorded before it, and a
27836
- * row both paths send is at best a duplicate request and at worst — for a
27837
- * session root — an overwrite of the inventory ids the live path resolved.
27838
- */
27839
- pendingSessions(limit, before) {
27840
- return allRows(this.sessionsStmt, { limit, before }).map(
27841
- (r) => r.sessionId
27842
- );
27843
- }
27844
- /** One session's undelivered structural rows within the backlog, root first. */
27845
- pendingRows(sessionId, limit, before) {
27846
- return allRows(this.rowsStmt, { sessionId, limit, before });
27847
- }
27848
- /**
27849
- * Captures this machine still owes the deployment, oldest first.
27850
- *
27851
- * Selected by the `outbox_owed` marker the attached forward path writes, not
27852
- * by a time window — see captureRowsStmt for why a window could not express
27853
- * this. `before` is the grace window that leaves a just-recorded capture to
27854
- * the live path.
27855
- */
27856
- pendingCaptureRows(limit, before) {
27857
- return allRows(this.captureRowsStmt, { limit, before });
27858
- }
27859
- /**
27860
- * Record that a capture is OWED to the deployment.
27861
- *
27862
- * Written by the attached forward path when a live send did not confirm
27863
- * delivery, and read by the drain as the whole of its eligibility test. It is
27864
- * a fact rather than an inference: the machine was attached, the send did not
27865
- * land, so the row is owed — which no time window can state, because the same
27866
- * window that holds the rows a past attachment left owed also holds every
27867
- * capture recorded while the machine was DETACHED, and those were never
27868
- * offered to anyone.
27869
- *
27870
- * Idempotent, and never un-set: `markSynced` settling the row is what takes it
27871
- * out of the drain's read.
27872
- */
27873
- markCaptureOwed(id) {
27874
- this.markOwedStmt.run({ id });
27875
- }
27876
- /**
27877
- * Mark every capture already on disk as owed, as of `before`.
27878
- *
27879
- * The consent-time backfill, called once from `aka attach` when a human
27880
- * grants existing-history consent — never from an ongoing drain pass, and
27881
- * never inferred from a boundary that could later move. `before` is the
27882
- * caller's own "now" at the moment consent was granted, so what this marks
27883
- * is exactly the backlog the consent prompt already counted, not whatever a
27884
- * later re-attach or key rotation might widen it to.
27885
- *
27886
- * Returns how many rows matched, for the caller to log or test against. Not a
27887
- * count of NEWLY marked rows — a row still unsynced from an earlier call
27888
- * matches again and is counted again, the same as `UPDATE`'s own `changes`.
27889
- */
27890
- markCaptureBacklogOwed(before) {
27891
- return Number(this.markCaptureBacklogOwedStmt.run({ before }).changes);
27892
- }
27893
- /** Record delivery. Called only AFTER the far side has accepted the rows. */
27894
- markSynced(ids, atMs) {
27895
- this.stampAll(ids, atMs);
27896
- }
27897
- /**
27898
- * Record that a row will never be sent.
27899
- *
27900
- * Reserved for a local defect — a row that cannot be rebuilt into a valid
27901
- * payload. A row that merely failed to reach the deployment stays NULL, so it
27902
- * is retried; marking those would turn one outage into permanent data loss.
27903
- */
27904
- markSkipped(ids) {
27905
- this.stampAll(ids, SKIPPED);
27906
- }
27907
- eachInTransaction(ids, run) {
27908
- if (ids.length === 0) return;
27909
- withTransaction(
27910
- this.db,
27911
- () => {
27912
- for (const id of ids) run(id);
27913
- },
27914
- "IMMEDIATE"
27915
- );
27916
- }
27917
- stampAll(ids, value) {
27918
- if (ids.length === 0) return;
27919
- withTransaction(
27920
- this.db,
27921
- () => {
27922
- for (const id of ids) this.stampStmt.run({ at: value, id });
27923
- },
27924
- "IMMEDIATE"
27925
- );
27926
- }
27927
- /**
27928
- * Claim rows as in-flight.
27929
- *
27930
- * Advisory in exactly the sense the lease is: it records that a send is in
27931
- * progress so a surface can say so, and a lost claim costs a row showing as
27932
- * queued while it is actually being sent. It is not exclusion — the far side
27933
- * settles a duplicate on the row id.
27934
- */
27935
- claimRows(ids, atMs) {
27936
- this.eachInTransaction(ids, (id) => this.claimRowStmt.run({ at: atMs, id }));
27937
- }
27938
- /** Give back a claim without settling — the send failed, the row is queued again. */
27939
- releaseRows(ids) {
27940
- this.eachInTransaction(ids, (id) => this.releaseRowStmt.run({ id }));
27941
- }
27942
- /**
27943
- * Clear claims older than `staleBefore`, and report how many were cleared.
27944
- *
27945
- * A process killed between claiming and settling leaves rows claimed with
27946
- * nothing left to settle them. Without this they read as "sending" for ever.
27947
- */
27948
- releaseStaleClaims(staleBefore) {
27949
- return Number(this.releaseStaleClaimsStmt.run({ staleBefore }).changes);
27950
- }
27951
- /**
27952
- * Every tracked row in exactly one delivery state.
27953
- *
27954
- * Takes no boundary on purpose. The boundary answers "what should the drain
27955
- * pick up now", which is a different question from "what state is this row
27956
- * in" — and a machine that has never attached has no boundary to pass, so
27957
- * requiring one would force a caller to invent one and report the whole store
27958
- * as queued.
27959
- */
27960
- partition() {
27961
- const row = getRow(this.partitionStmt, {});
27962
- return {
27963
- queued: row?.queued ?? 0,
27964
- inProgress: row?.inProgress ?? 0,
27965
- synced: row?.synced ?? 0,
27966
- failed: row?.failed ?? 0,
27967
- total: row?.total ?? 0
27968
- };
27969
- }
27970
- /** `pending` counts only what is inside the backlog; sent and skipped are totals. */
27971
- counts(before) {
27972
- const row = getRow(
27973
- this.countsStmt,
27974
- { before }
27975
- );
27976
- const captures = getRow(this.captureSkipCountStmt);
27977
- return {
27978
- pending: row?.pending ?? 0,
27979
- sent: row?.sent ?? 0,
27980
- skipped: row?.skipped ?? 0,
27981
- capturesSkipped: captures?.skipped ?? 0
27982
- };
27983
- }
27984
- /**
27985
- * The deployment the current stamps were made against, and where its backlog
27986
- * ends.
27987
- *
27988
- * READ-ONLY. An absent row reads as an absent deployment, which is what a
27989
- * machine that has never drained is — and every writer below seeds the row
27990
- * before it needs one, so nothing depends on this creating it. Keeping the
27991
- * write off the gate path matters because the gate runs on every pass while a
27992
- * write has to take the database's write lock.
27993
- */
27994
- deployment() {
27995
- const row = getRow(
27996
- this.fingerprintStmt
27997
- );
27998
- return {
27999
- fingerprint: row?.fingerprint ?? void 0,
28000
- backlogBefore: row?.backlogBefore ?? void 0
28001
- };
28002
- }
28003
- /**
28004
- * Point the ledger at a different deployment, discarding what it recorded
28005
- * about the previous one.
28006
- *
28007
- * Delivery is a fact about ONE recipient: rows sent to the deployment a
28008
- * machine has just left are undelivered as far as the new one is concerned.
28009
- * All four in one transaction, so a crash between them cannot leave stamps
28010
- * attributed to the wrong deployment, a boundary that belongs to another, or
28011
- * a disown with no re-mark to follow it.
28012
- *
28013
- * The boundary is written HERE and only here, which is what freezes it: a
28014
- * re-attach to the SAME deployment (a key rotation) leaves the fingerprint
28015
- * unchanged, so this never runs and the backlog does not widen back over rows
28016
- * the live path has since delivered.
28017
- *
28018
- * `backfillCapturesBefore` is the caller's OWN "now" at the instant a human
28019
- * granted existing-history consent for the deployment this call is arming —
28020
- * a DIFFERENT instant from `backlogBefore`: the re-mark boundary is the GRANT
28021
- * instant, `backlogBefore` is the ATTACH instant, and the two can be far
28022
- * apart. Passed only when that grant is valid, since this method has no way
28023
- * to check consent itself and must not mark a row owed for a machine that
28024
- * never agreed to it. Applied AFTER the disown above, in the SAME
28025
- * transaction: what the disown clears is every marker below `backlogBefore`,
28026
- * which includes this deployment's OWN pre-attach rows — `aka attach` calls
28027
- * `seedCaptureBacklogOwed` at the attach instant, so every row it marks sits
28028
- * on the cleared side of that bound — and the re-mark in the same
28029
- * transaction is what puts those rows back. A crash between the two cannot
28030
- * strand the ledger disowned with nothing re-marked — the transaction either
28031
- * lands whole or not at all, and a fingerprint mismatch that has not yet
28032
- * committed re-enters this method on the very next pass. Omit it (the
28033
- * structural-only tests do) to exercise the disown in isolation.
28034
- *
28035
- * The disown is bounded by `backlogBefore`, which is what keeps it from
28036
- * touching a marker the NEW deployment's OWN live path has already set: B's
28037
- * live path can mark a capture owed from the moment `aka attach` writes the
28038
- * descriptor, before the drain's first pass ever reaches this method, and
28039
- * such a row sits at or after the bound rather than below it. What keeps the
28040
- * disown from eating THIS SAME CALL's own re-mark is the order, not the
28041
- * bound — disown runs first, re-mark second, both inside the one
28042
- * transaction above.
28043
- */
28044
- rearmFor(fingerprint, backlogBefore, backfillCapturesBefore) {
28045
- this.ensureRowStmt.run();
28046
- withTransaction(
28047
- this.db,
28048
- () => {
28049
- const previous = getRow(this.fingerprintStmt)?.fingerprint;
28050
- this.rearmStmt.run();
28051
- if (previous !== null && previous !== void 0 && previous !== fingerprint) {
28052
- this.disownCapturesStmt.run({ attachedAt: backlogBefore });
28053
- }
28054
- if (backfillCapturesBefore !== void 0) {
28055
- this.markCaptureBacklogOwedStmt.run({ before: backfillCapturesBefore });
28056
- }
28057
- this.setFingerprintStmt.run({ fingerprint, backlogBefore });
28058
- },
28059
- "IMMEDIATE"
28060
- );
28061
- }
28062
- /**
28063
- * End the attached period: hand its rows to the live path, and release the
28064
- * boundary so the next attachment can freeze a new one.
28065
- *
28066
- * WITHOUT THIS, a detach and a re-attach to the same deployment leave a window
28067
- * nothing delivers. The fingerprint is unchanged, so the boundary is never
28068
- * re-frozen and stays at the FIRST attachment — while nothing forwards at all
28069
- * during the detached period, because the machine is not attached. Rows
28070
- * recorded in that window sit after the boundary and before the re-attach, so
28071
- * neither path takes them, and the pending count reports none outstanding.
28072
- *
28073
- * Stamping the attached window is not a claim that every one of those rows
28074
- * reached the deployment — the live path drops on failure and says so
28075
- * elsewhere. It records that they were ITS to deliver, which is exactly the
28076
- * status quo: they sit outside the frozen boundary today and are equally never
28077
- * re-sent. Making it explicit is what lets the boundary move.
28078
- *
28079
- * ONE TRANSACTION, so a crash cannot release the boundary while leaving the
28080
- * window unstamped — that half-state would re-send the whole attached period
28081
- * on the next attach, which is the failure the boundary exists to prevent.
28082
- */
28083
- closeAttachedWindow(attachedAtMs, atMs) {
28084
- this.ensureRowStmt.run();
28085
- withTransaction(
28086
- this.db,
28087
- () => {
28088
- const row = getRow(this.fingerprintStmt);
28089
- const from = row?.backlogBefore ?? attachedAtMs;
28090
- this.closeWindowStmt.run({ at: atMs, attachedAt: from });
28091
- this.releaseBoundaryStmt.run();
28092
- },
28093
- "IMMEDIATE"
28094
- );
28095
- }
28096
- /**
28097
- * Freeze a boundary for the deployment already on file, KEEPING the stamps.
28098
- *
28099
- * The re-attach half of the above. Distinct from `rearmFor`, which is for a
28100
- * different deployment and therefore discards what was delivered to the old
28101
- * one: here the recipient is the same, so everything already sent to it stays
28102
- * sent.
28103
- */
28104
- freezeBoundary(backlogBefore) {
28105
- this.ensureRowStmt.run();
28106
- this.freezeBoundaryStmt.run({ backlogBefore });
28107
- }
28108
- /** Take the claim, or report that someone live already holds it. */
28109
- claim(pid, host, nowMs, staleAfterMs) {
28110
- this.ensureRowStmt.run();
28111
- let taken = false;
28112
- withTransaction(
28113
- this.db,
28114
- () => {
28115
- const result = this.claimStmt.run({
28116
- pid,
28117
- host,
28118
- now: nowMs,
28119
- staleBefore: nowMs - staleAfterMs
28120
- });
28121
- taken = result.changes === 1;
28122
- },
28123
- "IMMEDIATE"
28124
- );
28125
- return taken;
28126
- }
28127
- /** Say the holder is still alive. A no-op once the claim has moved on. */
28128
- heartbeat(pid, nowMs) {
28129
- this.heartbeatStmt.run({ now: nowMs, pid });
28130
- }
28131
- /** Give the claim up. Scoped to this holder, so a taken-over claim is left be. */
28132
- release(pid) {
28133
- this.releaseStmt.run({ pid });
28134
- }
28135
- /** Who holds the claim, if anyone. Read-only, for the same reason as above. */
28136
- lease() {
28137
- return getRow(this.leaseStmt);
28138
- }
28139
- };
28140
-
28141
29017
  // ../../packages/persistence/src/repositories/inspection-definitions.ts
28142
29018
  var SqliteInspectionDefinitionsRepository = class {
28143
29019
  constructor(db) {
@@ -28340,6 +29216,7 @@ function overlayManagedSettings(settings, managed, now = () => /* @__PURE__ */ n
28340
29216
  if (values.vaultInlineReveal !== void 0) merged.vaultInlineReveal = values.vaultInlineReveal;
28341
29217
  if (values.dataSharesInPlace !== void 0) merged.dataSharesInPlace = values.dataSharesInPlace;
28342
29218
  if (values.redactFallback !== void 0) merged.redactFallback = values.redactFallback;
29219
+ if (values.bodyRetention !== void 0) merged.bodyRetention = values.bodyRetention;
28343
29220
  if (values.vaultConsent !== void 0) {
28344
29221
  merged.vaultConsent = values.vaultConsent ? (
28345
29222
  // Keep an existing valid grant so its acknowledgedAt survives; mint one
@@ -30847,7 +31724,7 @@ var SqliteSecurityRepository = class {
30847
31724
  ELSE 0
30848
31725
  END) AS open_at_rest
30849
31726
  FROM inspection_findings f
30850
- JOIN audit_events e ON e.id = f.audit_event_id
31727
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
30851
31728
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
30852
31729
  LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
30853
31730
  ON latest.finding_key = f.finding_key
@@ -31073,7 +31950,7 @@ var SqliteSecurityRepository = class {
31073
31950
  this.db.prepare(
31074
31951
  `SELECT e.repo AS repo, count(*) AS c
31075
31952
  FROM inspection_findings f
31076
- JOIN audit_events e ON e.id = f.audit_event_id
31953
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31077
31954
  WHERE e.started_at >= :from AND e.started_at < :to
31078
31955
  AND e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
31079
31956
  AND e.repo IS NOT NULL
@@ -31197,7 +32074,7 @@ var SqliteSecurityRepository = class {
31197
32074
  d.severity AS severity,
31198
32075
  COUNT(*) AS count
31199
32076
  FROM inspection_findings f
31200
- JOIN audit_events e ON e.id = f.audit_event_id
32077
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31201
32078
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
31202
32079
  LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
31203
32080
  ON latest.finding_key = f.finding_key
@@ -31232,7 +32109,7 @@ var SqliteSecurityRepository = class {
31232
32109
  `SELECT e.started_at AS occurred_at, d.severity AS severity, f.action_taken AS action_taken,
31233
32110
  d.rule_id AS rule_id, d.category AS category
31234
32111
  FROM inspection_findings f
31235
- JOIN audit_events e ON e.id = f.audit_event_id
32112
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31236
32113
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
31237
32114
  WHERE e.started_at >= :from AND e.started_at < :to
31238
32115
  AND e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
@@ -32073,6 +32950,7 @@ function openWithPragmas(file2) {
32073
32950
  db.exec("PRAGMA journal_mode = WAL");
32074
32951
  db.exec("PRAGMA busy_timeout = 2000");
32075
32952
  db.exec("PRAGMA foreign_keys = ON");
32953
+ registerSqlFunctions(db);
32076
32954
  } catch (err) {
32077
32955
  closeQuietly(db);
32078
32956
  throw err;
@@ -32102,7 +32980,7 @@ function backupLegacyStore(db, file2) {
32102
32980
  discardStore(file2, backup);
32103
32981
  return backup;
32104
32982
  }
32105
- function openAndInitialize(file2, base) {
32983
+ function openAndInitialize(file2, base, skipTags) {
32106
32984
  let db = openWithPragmas(file2);
32107
32985
  try {
32108
32986
  if (isForeignSqliteLineage(db)) {
@@ -32112,7 +32990,7 @@ function openAndInitialize(file2, base) {
32112
32990
  `Detected an older, incompatible (tenant-bearing) ${DB_FILENAME}; backed it up to ${backup} and created a fresh store.`
32113
32991
  );
32114
32992
  }
32115
- applyMigrations(db, file2);
32993
+ applyMigrations(db, file2, { skipTags });
32116
32994
  tightenPerms(file2);
32117
32995
  const policies = new SqlitePoliciesRepository(db);
32118
32996
  const installedPacks = new SqliteInstalledPacksRepository(db, base);
@@ -32127,6 +33005,7 @@ function openAndInitialize(file2, base) {
32127
33005
  exceptions: new SqliteExceptionsRepository(db),
32128
33006
  resolutions: new SqliteResolutionsRepository(db),
32129
33007
  ruleProbeCache: new SqliteRuleProbeCacheRepository(db),
33008
+ bodyRetention: new SqliteBodyRetentionRepository(db),
32130
33009
  security: new SqliteSecurityRepository(db),
32131
33010
  detections: new SqliteDetectionsRepository(db),
32132
33011
  shares: new SqliteSharesRepository(db),
@@ -32137,6 +33016,7 @@ function openAndInitialize(file2, base) {
32137
33016
  activity: new SqliteActivityRepository(db),
32138
33017
  sourceProject: new SqliteSourceProjectRepository(db),
32139
33018
  auditEvents: new SqliteAuditEventsRepository(db),
33019
+ captureStatus: new SqliteCaptureStatusRepository(db),
32140
33020
  classifiedData: new SqliteClassifiedDataRepository(db),
32141
33021
  inspectionDefinitions: new SqliteInspectionDefinitionsRepository(db),
32142
33022
  inspectionFindings: new SqliteInspectionFindingsRepository(db),
@@ -32149,7 +33029,8 @@ function openAndInitialize(file2, base) {
32149
33029
  throw err;
32150
33030
  }
32151
33031
  }
32152
- function openLocalDatabase(dir) {
33032
+ var DEFERRED_TAGS = new Set(DEFERRED_MIGRATION_TAGS);
33033
+ function openLocalDatabase(dir, options = {}) {
32153
33034
  ensureDataDirSync(dir);
32154
33035
  const file2 = join7(dir, DB_FILENAME);
32155
33036
  reapStalePartials(file2);
@@ -32161,6 +33042,7 @@ function openLocalDatabase(dir) {
32161
33042
  installedPacks,
32162
33043
  scanLedger,
32163
33044
  historySync,
33045
+ bodyRetention,
32164
33046
  secretVault,
32165
33047
  exceptions,
32166
33048
  resolutions,
@@ -32175,6 +33057,7 @@ function openLocalDatabase(dir) {
32175
33057
  activity,
32176
33058
  sourceProject,
32177
33059
  auditEvents,
33060
+ captureStatus,
32178
33061
  classifiedData,
32179
33062
  inspectionDefinitions,
32180
33063
  inspectionFindings,
@@ -32184,7 +33067,8 @@ function openLocalDatabase(dir) {
32184
33067
  // `dir` is always `<base>/data` — every caller resolves it through
32185
33068
  // `dataDir()` — so its parent is the `~/.aka` base the layout splits into
32186
33069
  // settings/ and data/, and the pack-policy floor needs both halves.
32187
- dirname2(dir)
33070
+ dirname2(dir),
33071
+ options.applyDeferredMigrations === true ? void 0 : DEFERRED_TAGS
32188
33072
  );
32189
33073
  function captureRowId(event) {
32190
33074
  return captureId(
@@ -32377,6 +33261,7 @@ function openLocalDatabase(dir) {
32377
33261
  installedPacks,
32378
33262
  scanLedger,
32379
33263
  historySync,
33264
+ bodyRetention,
32380
33265
  secretVault,
32381
33266
  exceptions,
32382
33267
  resolutions,
@@ -32390,6 +33275,7 @@ function openLocalDatabase(dir) {
32390
33275
  activity,
32391
33276
  sourceProject,
32392
33277
  auditEvents,
33278
+ captureStatus,
32393
33279
  classifiedData,
32394
33280
  inspectionDefinitions,
32395
33281
  inspectionFindings,
@@ -32417,6 +33303,7 @@ function openLocalDatabase(dir) {
32417
33303
 
32418
33304
  // ../../packages/persistence/src/egress-wire.ts
32419
33305
  import { createHash as createHash3 } from "crypto";
33306
+ var SLASH = "/".charCodeAt(0);
32420
33307
 
32421
33308
  // ../../packages/persistence/src/finding-key.ts
32422
33309
  import { createHash as createHash4 } from "crypto";
@@ -32427,18 +33314,109 @@ import { existsSync as existsSync3, readFileSync as readFileSync6 } from "fs";
32427
33314
  import { join as join8 } from "path";
32428
33315
  import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
32429
33316
 
33317
+ // ../../packages/persistence/src/forward-health.ts
33318
+ import { readFileSync as readFileSync7 } from "fs";
33319
+ import { join as join9 } from "path";
33320
+ var BREAKER_COOLDOWN_MS = 3e4;
33321
+ function parseForwardHealth(raw, nowMs) {
33322
+ try {
33323
+ const parsed2 = JSON.parse(raw);
33324
+ if (typeof parsed2 !== "object" || parsed2 === null) return null;
33325
+ const record2 = parsed2;
33326
+ const failures = typeof record2.consecutiveFailures === "number" && record2.consecutiveFailures >= 0 ? record2.consecutiveFailures : 0;
33327
+ const openedAtMs = typeof record2.openedAtMs === "number" && Number.isFinite(record2.openedAtMs) && record2.openedAtMs <= nowMs ? record2.openedAtMs : null;
33328
+ const parsedFailure = ControlPlaneFailure.safeParse(record2.lastFailure);
33329
+ const lastFailure = parsedFailure.success ? parsedFailure.data : null;
33330
+ return { consecutiveFailures: failures, openedAtMs, lastFailure };
33331
+ } catch {
33332
+ return null;
33333
+ }
33334
+ }
33335
+ function readForwardHealth(dir, nowMs = Date.now()) {
33336
+ try {
33337
+ return parseForwardHealth(
33338
+ readFileSync7(join9(dir, ATTACHED_FORWARD_STATE_FILENAME), "utf8"),
33339
+ nowMs
33340
+ );
33341
+ } catch {
33342
+ return null;
33343
+ }
33344
+ }
33345
+ function isForwardPaused(health, nowMs) {
33346
+ const openedAtMs = health?.openedAtMs ?? null;
33347
+ if (openedAtMs === null) return false;
33348
+ return nowMs - openedAtMs < BREAKER_COOLDOWN_MS;
33349
+ }
33350
+
32430
33351
  // ../../packages/persistence/src/history-backfill.ts
32431
33352
  import { existsSync as existsSync4 } from "fs";
32432
- import { join as join9 } from "path";
33353
+ import { join as join10 } from "path";
32433
33354
 
32434
33355
  // ../../packages/persistence/src/history-preview.ts
32435
33356
  import { existsSync as existsSync5 } from "fs";
32436
- import { join as join10 } from "path";
33357
+ import { join as join11 } from "path";
32437
33358
  import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
32438
33359
 
33360
+ // ../../packages/persistence/src/history-sync-state.ts
33361
+ import { readFileSync as readFileSync8 } from "fs";
33362
+ import { join as join12 } from "path";
33363
+ var HISTORY_SYNC_STATE_FILENAME = ATTACHED_HISTORY_SYNC_STATE_FILENAME;
33364
+ var PHASES = /* @__PURE__ */ new Set(["filling", "complete"]);
33365
+ var OUTCOMES = /* @__PURE__ */ new Set([
33366
+ "ok",
33367
+ "unreachable",
33368
+ "refused",
33369
+ "interrupted"
33370
+ ]);
33371
+ var SPEC_VERSION = 1;
33372
+ function historySyncStatePath(dataDir2) {
33373
+ return join12(dataDir2, HISTORY_SYNC_STATE_FILENAME);
33374
+ }
33375
+ function writeHistorySyncState(dataDir2, state) {
33376
+ try {
33377
+ ensureDataDirSync(dataDir2);
33378
+ const persisted = { specVersion: SPEC_VERSION, ...state };
33379
+ writeOwnerOnlyFileSync(historySyncStatePath(dataDir2), `${JSON.stringify(persisted)}
33380
+ `);
33381
+ } catch {
33382
+ }
33383
+ }
33384
+ function readHistorySyncState(dataDir2) {
33385
+ try {
33386
+ const parsed2 = JSON.parse(readFileSync8(historySyncStatePath(dataDir2), "utf8"));
33387
+ if (typeof parsed2 !== "object" || parsed2 === null) return null;
33388
+ const r = parsed2;
33389
+ if (r.specVersion !== SPEC_VERSION) return null;
33390
+ if (typeof r.phase !== "string" || !PHASES.has(r.phase)) return null;
33391
+ if (typeof r.lastOutcome !== "string" || !OUTCOMES.has(r.lastOutcome)) return null;
33392
+ if (!isCount(r.lastPassAtMs)) return null;
33393
+ if (!isCount(r.sentTotal) || !isCount(r.pendingTotal) || !isCount(r.skippedTotal)) return null;
33394
+ if (!isNullableCount(r.startedAtMs) || !isNullableCount(r.completedAtMs)) return null;
33395
+ return {
33396
+ specVersion: SPEC_VERSION,
33397
+ phase: r.phase,
33398
+ lastOutcome: r.lastOutcome,
33399
+ lastPassAtMs: r.lastPassAtMs,
33400
+ sentTotal: r.sentTotal,
33401
+ pendingTotal: r.pendingTotal,
33402
+ skippedTotal: r.skippedTotal,
33403
+ startedAtMs: r.startedAtMs,
33404
+ completedAtMs: r.completedAtMs
33405
+ };
33406
+ } catch {
33407
+ return null;
33408
+ }
33409
+ }
33410
+ function isCount(v) {
33411
+ return typeof v === "number" && Number.isFinite(v) && v >= 0;
33412
+ }
33413
+ function isNullableCount(v) {
33414
+ return v === null || isCount(v);
33415
+ }
33416
+
32439
33417
  // ../../packages/persistence/src/store-symlinks.ts
32440
33418
  import { existsSync as existsSync6, lstatSync as lstatSync3, readlinkSync, realpathSync, statSync as statSync4 } from "fs";
32441
- import { dirname as dirname3, join as join11, resolve } from "path";
33419
+ import { dirname as dirname3, join as join13, resolve } from "path";
32442
33420
 
32443
33421
  // ../../packages/persistence/src/vault/crypto.ts
32444
33422
  import {
@@ -32452,15 +33430,15 @@ import {
32452
33430
  // ../../packages/persistence/src/vault/key-provider.ts
32453
33431
  import { execFileSync } from "child_process";
32454
33432
  import { randomBytes as randomBytes2 } from "crypto";
32455
- import { chmodSync as chmodSync3, readFileSync as readFileSync7, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
32456
- import { join as join12 } from "path";
33433
+ import { chmodSync as chmodSync3, readFileSync as readFileSync9, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
33434
+ import { join as join14 } from "path";
32457
33435
 
32458
33436
  // ../../packages/persistence/src/vault/vault.ts
32459
33437
  import { randomBytes as randomBytes3, randomUUID as randomUUID12 } from "crypto";
32460
33438
 
32461
33439
  // ../../packages/persistence/src/warn-era-cap.ts
32462
33440
  import { existsSync as existsSync7, writeFileSync as writeFileSync4 } from "fs";
32463
- import { join as join13 } from "path";
33441
+ import { join as join15 } from "path";
32464
33442
 
32465
33443
  // ../../packages/remote/src/http.ts
32466
33444
  import { request as httpRequest } from "http";
@@ -32491,6 +33469,12 @@ var RemoteRequestInvalid = class extends Error {
32491
33469
  }
32492
33470
  cause;
32493
33471
  };
33472
+ var RemoteEndpointRefused = class extends Error {
33473
+ constructor(endpoint) {
33474
+ super(`refusing to talk to an unsafe control-plane endpoint: ${originOnly(endpoint)}`);
33475
+ this.name = "RemoteEndpointRefused";
33476
+ }
33477
+ };
32494
33478
  var RemoteResponseInvalid = class extends Error {
32495
33479
  constructor(route, detail) {
32496
33480
  super(`control plane answered ${route} with ${detail}`);
@@ -32643,14 +33627,15 @@ function parsed(schema, body, route) {
32643
33627
  }
32644
33628
  return result.data;
32645
33629
  }
32646
- function withoutTrailingSlashes(endpoint) {
33630
+ function resolveBaseUrl(endpoint) {
33631
+ if (!isSafeEndpoint(endpoint)) throw new RemoteEndpointRefused(endpoint);
32647
33632
  let end = endpoint.length;
32648
- while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH) end -= 1;
33633
+ while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH2) end -= 1;
32649
33634
  return endpoint.slice(0, end);
32650
33635
  }
32651
- var SLASH = "/".charCodeAt(0);
33636
+ var SLASH2 = "/".charCodeAt(0);
32652
33637
  function createRemoteClient(options) {
32653
- const base = withoutTrailingSlashes(options.endpoint);
33638
+ const base = resolveBaseUrl(options.endpoint);
32654
33639
  const url2 = (route) => `${base}${route}`;
32655
33640
  const common = { apiKey: options.apiKey, timeoutMs: options.timeoutMs };
32656
33641
  const sendOne = async (event) => {
@@ -32765,18 +33750,17 @@ function createRemoteClient(options) {
32765
33750
  }
32766
33751
 
32767
33752
  // ../../packages/plugin-runtime/src/attached/forward-drops.ts
32768
- import { readFileSync as readFileSync8 } from "fs";
32769
- import { join as join14 } from "path";
33753
+ import { readFileSync as readFileSync10 } from "fs";
33754
+ import { join as join16 } from "path";
32770
33755
 
32771
33756
  // ../../packages/plugin-runtime/src/attached/forward-policy.ts
32772
33757
  import { randomUUID as randomUUID15 } from "crypto";
32773
- import { readFileSync as readFileSync15 } from "fs";
32774
33758
  import { readFile, rename, writeFile } from "fs/promises";
32775
- import { join as join24 } from "path";
33759
+ import { join as join26 } from "path";
32776
33760
 
32777
33761
  // ../../packages/plugin-sdk/src/config.ts
32778
33762
  import { existsSync as existsSync8 } from "fs";
32779
- import { join as join15 } from "path";
33763
+ import { join as join17 } from "path";
32780
33764
 
32781
33765
  // ../../packages/plugin-sdk/src/provider-env.ts
32782
33766
  var booleanish = external_exports.string().optional().transform((v) => {
@@ -32797,9 +33781,9 @@ var providerEnvShape = {
32797
33781
  var ProviderEnvSchema = external_exports.object(providerEnvShape);
32798
33782
 
32799
33783
  // ../../packages/plugin-sdk/src/config-inventory.ts
32800
- import { readdirSync as readdirSync2, readFileSync as readFileSync10, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
33784
+ import { readdirSync as readdirSync2, readFileSync as readFileSync12, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
32801
33785
  import { homedir as homedir2 } from "os";
32802
- import { basename as basename3, join as join17 } from "path";
33786
+ import { basename as basename3, join as join19 } from "path";
32803
33787
 
32804
33788
  // ../../packages/detections/src/egress/registry.ts
32805
33789
  var EXTRACTOR_VERSION = "1";
@@ -33528,6 +34512,56 @@ var CONFIG_POSTURE_RULES = [
33528
34512
  }
33529
34513
  ];
33530
34514
 
34515
+ // ../../packages/detections/src/posture/web-capture-posture.ts
34516
+ var RULE_VERSION2 = "1";
34517
+ var DRIFT_MIN_PARSE_FAILURES = 2;
34518
+ var WEB_CAPTURE_DRIFT_STATES = /* @__PURE__ */ new Set([
34519
+ "blind",
34520
+ "degraded"
34521
+ ]);
34522
+ var WEB_CAPTURE_DRIFT_RULE = {
34523
+ ruleId: "web-capture-drift",
34524
+ version: RULE_VERSION2,
34525
+ name: "Web chat capture is not reading the site",
34526
+ category: "config",
34527
+ severity: "medium",
34528
+ definition: JSON.stringify({
34529
+ kind: "web-capture-drift",
34530
+ states: [...WEB_CAPTURE_DRIFT_STATES],
34531
+ minParseFailures: DRIFT_MIN_PARSE_FAILURES
34532
+ })
34533
+ };
34534
+ var STATIC_COPY = {
34535
+ active: { headline: "turns are being observed on this site" },
34536
+ unreported: {
34537
+ // Says "recently" rather than "yet": the store read is bounded to
34538
+ // CAPTURE_STATUS_RECENCY_MS, so this state covers a site nothing has ever
34539
+ // reported for AND one whose last report has aged out. The two are the
34540
+ // same fact to a reader — nobody has confirmed anything lately — and the
34541
+ // copy may not claim the stronger of them.
34542
+ headline: `no report in the last ${String(CAPTURE_STATUS_RECENCY_DAYS)} days \u2014 open the site in Chrome with the extension loaded`
34543
+ },
34544
+ standby: {
34545
+ headline: "this build declares no endpoints for the site, so nothing is observed yet"
34546
+ },
34547
+ unpatched: {
34548
+ // Says what the flags say and no more. `patched` is false both for a tap
34549
+ // that installed and hooked neither transport and for one that never ran
34550
+ // at all — a page reports the same status either way, so the copy may not
34551
+ // assert one of them.
34552
+ headline: "the page tap captured neither fetch nor XHR \u2014 it may not have installed; reload the extension at chrome://extensions"
34553
+ },
34554
+ idle: { headline: "watching; no turn has been observed yet" },
34555
+ blind: {
34556
+ headline: "messages were sent in the page that the network capture never saw",
34557
+ 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."
34558
+ },
34559
+ degraded: {
34560
+ headline: "the site's payloads no longer carry the fields the extension reads",
34561
+ 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."
34562
+ }
34563
+ };
34564
+
33531
34565
  // ../../packages/detections/src/security/redos-probe.ts
33532
34566
  var BUDGET_MS = 100;
33533
34567
  var EXPONENTIAL_UNITS = [
@@ -33557,8 +34591,8 @@ var CPU_CORROBORATION_SHARE = 0.2;
33557
34591
  var CORROBORATION_FLOOR_MS = BUDGET_MS * CPU_CORROBORATION_SHARE;
33558
34592
 
33559
34593
  // ../../packages/plugin-sdk/src/repo.ts
33560
- import { existsSync as existsSync9, readFileSync as readFileSync9, statSync as statSync6 } from "fs";
33561
- import { basename as basename2, dirname as dirname4, isAbsolute, join as join16, sep as sep2 } from "path";
34594
+ import { existsSync as existsSync9, readFileSync as readFileSync11, statSync as statSync6 } from "fs";
34595
+ import { basename as basename2, dirname as dirname4, isAbsolute, join as join18, sep as sep2 } from "path";
33562
34596
 
33563
34597
  // ../../packages/plugin-sdk/src/events.ts
33564
34598
  import { createHash as createHash5, randomUUID as randomUUID13 } from "crypto";
@@ -33569,8 +34603,8 @@ import { fileURLToPath } from "url";
33569
34603
  import { Worker } from "worker_threads";
33570
34604
 
33571
34605
  // ../../packages/plugin-sdk/src/host-floor.ts
33572
- import { readFileSync as readFileSync12 } from "fs";
33573
- import { join as join19 } from "path";
34606
+ import { readFileSync as readFileSync14 } from "fs";
34607
+ import { join as join21 } from "path";
33574
34608
 
33575
34609
  // ../../packages/plugin-sdk/src/model-governance.ts
33576
34610
  import {
@@ -33578,11 +34612,11 @@ import {
33578
34612
  fstatSync,
33579
34613
  mkdirSync as mkdirSync2,
33580
34614
  openSync as openSync2,
33581
- readFileSync as readFileSync11,
34615
+ readFileSync as readFileSync13,
33582
34616
  readSync,
33583
34617
  writeFileSync as writeFileSync5
33584
34618
  } from "fs";
33585
- import { join as join18 } from "path";
34619
+ import { join as join20 } from "path";
33586
34620
  var TAIL_BYTES = 256 * 1024;
33587
34621
 
33588
34622
  // ../../packages/plugin-sdk/src/host-floor.ts
@@ -33605,15 +34639,15 @@ var HOST_FLOORS = {
33605
34639
 
33606
34640
  // ../../packages/plugin-sdk/src/ignore-layers.ts
33607
34641
  var import_ignore = __toESM(require_ignore(), 1);
33608
- import { readFileSync as readFileSync13 } from "fs";
33609
- import { join as join20 } from "path";
34642
+ import { readFileSync as readFileSync15 } from "fs";
34643
+ import { join as join22 } from "path";
33610
34644
 
33611
34645
  // ../../packages/plugin-sdk/src/inventory-resolver.ts
33612
34646
  import { arch, hostname as hostname4, platform, release } from "os";
33613
34647
 
33614
34648
  // ../../packages/plugin-sdk/src/nudge.ts
33615
- import { mkdirSync as mkdirSync3, readFileSync as readFileSync14, writeFileSync as writeFileSync6 } from "fs";
33616
- import { join as join21 } from "path";
34649
+ import { mkdirSync as mkdirSync3, readFileSync as readFileSync16, writeFileSync as writeFileSync6 } from "fs";
34650
+ import { join as join23 } from "path";
33617
34651
 
33618
34652
  // ../../packages/plugin-sdk/src/paths.ts
33619
34653
  import { readdirSync as readdirSync3, realpathSync as realpathSync3 } from "fs";
@@ -33621,7 +34655,7 @@ import { basename as basename4, dirname as dirname5, sep as sep3 } from "path";
33621
34655
 
33622
34656
  // ../../packages/plugin-sdk/src/project-files.ts
33623
34657
  import { existsSync as existsSync11, readdirSync as readdirSync4 } from "fs";
33624
- import { basename as basename5, join as join22 } from "path";
34658
+ import { basename as basename5, join as join24 } from "path";
33625
34659
 
33626
34660
  // ../../packages/plugin-sdk/src/provider-env-antigravity.ts
33627
34661
  var optionalBaseUrl2 = external_exports.preprocess((v) => {
@@ -33657,94 +34691,7 @@ var THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1e3;
33657
34691
 
33658
34692
  // ../../packages/plugin-sdk/src/throttle.ts
33659
34693
  import { mkdirSync as mkdirSync4, statSync as statSync8, writeFileSync as writeFileSync7 } from "fs";
33660
- import { join as join23 } from "path";
33661
-
33662
- // ../../packages/plugin-runtime/src/attached/forward-policy.ts
33663
- var BREAKER_COOLDOWN_MS = 3e4;
33664
- var FAILURES = /* @__PURE__ */ new Set([
33665
- "unauthorized",
33666
- "forbidden",
33667
- "unreachable"
33668
- ]);
33669
- var FORWARD_STATE_FILENAME = ATTACHED_FORWARD_STATE_FILENAME;
33670
- var STATE_FILENAME = FORWARD_STATE_FILENAME;
33671
- function parseBreakerState(raw, nowMs) {
33672
- try {
33673
- const parsed2 = JSON.parse(raw);
33674
- if (typeof parsed2 !== "object" || parsed2 === null) return null;
33675
- const record2 = parsed2;
33676
- const failures = typeof record2.consecutiveFailures === "number" && record2.consecutiveFailures >= 0 ? record2.consecutiveFailures : 0;
33677
- const openedAtMs = typeof record2.openedAtMs === "number" && Number.isFinite(record2.openedAtMs) && record2.openedAtMs <= nowMs ? record2.openedAtMs : null;
33678
- const lastFailure = typeof record2.lastFailure === "string" && FAILURES.has(record2.lastFailure) ? record2.lastFailure : null;
33679
- return { consecutiveFailures: failures, openedAtMs, lastFailure };
33680
- } catch {
33681
- return null;
33682
- }
33683
- }
33684
- function readForwardHealth(dir, nowMs = Date.now()) {
33685
- try {
33686
- return parseBreakerState(readFileSync15(join24(dir, STATE_FILENAME), "utf8"), nowMs);
33687
- } catch {
33688
- return null;
33689
- }
33690
- }
33691
-
33692
- // ../../packages/plugin-runtime/src/attached/history-state.ts
33693
- import { readFileSync as readFileSync16 } from "fs";
33694
34694
  import { join as join25 } from "path";
33695
- var HISTORY_SYNC_STATE_FILENAME = ATTACHED_HISTORY_SYNC_STATE_FILENAME;
33696
- var PHASES = /* @__PURE__ */ new Set(["filling", "complete"]);
33697
- var OUTCOMES = /* @__PURE__ */ new Set([
33698
- "ok",
33699
- "unreachable",
33700
- "refused",
33701
- "interrupted"
33702
- ]);
33703
- var SPEC_VERSION = 1;
33704
- function historySyncStatePath(dataDir2) {
33705
- return join25(dataDir2, HISTORY_SYNC_STATE_FILENAME);
33706
- }
33707
- function writeHistorySyncState(dataDir2, state) {
33708
- try {
33709
- ensureDataDirSync(dataDir2);
33710
- const persisted = { specVersion: SPEC_VERSION, ...state };
33711
- writeOwnerOnlyFileSync(historySyncStatePath(dataDir2), `${JSON.stringify(persisted)}
33712
- `);
33713
- } catch {
33714
- }
33715
- }
33716
- function readHistorySyncState(dataDir2) {
33717
- try {
33718
- const parsed2 = JSON.parse(readFileSync16(historySyncStatePath(dataDir2), "utf8"));
33719
- if (typeof parsed2 !== "object" || parsed2 === null) return null;
33720
- const r = parsed2;
33721
- if (r.specVersion !== SPEC_VERSION) return null;
33722
- if (typeof r.phase !== "string" || !PHASES.has(r.phase)) return null;
33723
- if (typeof r.lastOutcome !== "string" || !OUTCOMES.has(r.lastOutcome)) return null;
33724
- if (!isCount(r.lastPassAtMs)) return null;
33725
- if (!isCount(r.sentTotal) || !isCount(r.pendingTotal) || !isCount(r.skippedTotal)) return null;
33726
- if (!isNullableCount(r.startedAtMs) || !isNullableCount(r.completedAtMs)) return null;
33727
- return {
33728
- specVersion: SPEC_VERSION,
33729
- phase: r.phase,
33730
- lastOutcome: r.lastOutcome,
33731
- lastPassAtMs: r.lastPassAtMs,
33732
- sentTotal: r.sentTotal,
33733
- pendingTotal: r.pendingTotal,
33734
- skippedTotal: r.skippedTotal,
33735
- startedAtMs: r.startedAtMs,
33736
- completedAtMs: r.completedAtMs
33737
- };
33738
- } catch {
33739
- return null;
33740
- }
33741
- }
33742
- function isCount(v) {
33743
- return typeof v === "number" && Number.isFinite(v) && v >= 0;
33744
- }
33745
- function isNullableCount(v) {
33746
- return v === null || isCount(v);
33747
- }
33748
34695
 
33749
34696
  // ../../packages/plugin-runtime/src/attached/history-sync.ts
33750
34697
  import { createHash as createHash6 } from "crypto";
@@ -33770,7 +34717,16 @@ function rebuildCapture(row) {
33770
34717
  const metadata = {
33771
34718
  ...rootSessionId === null ? {} : { sessionId: rootSessionId },
33772
34719
  ...filePath === void 0 ? {} : { filePath },
33773
- ...pick2(attributes, { repo: "repo", toolName: "tool_name", model: "model" }),
34720
+ ...pick2(attributes, {
34721
+ repo: "repo",
34722
+ toolName: "tool_name",
34723
+ model: "model",
34724
+ // The join back to the llm_call leaf for the same web-chat turn.
34725
+ // Stripping these would forward a response capture the deployment can
34726
+ // never correlate to the llm_call leaf describing the same turn.
34727
+ messageId: "message_id",
34728
+ conversationId: "conversation_id"
34729
+ }),
33774
34730
  // The two constrained strings, kept only if they satisfy the wire.
33775
34731
  ...withField("traceId", keep(stringOrUndefined(attributes.trace_id), TRACE_ID)),
33776
34732
  ...withField(
@@ -33791,7 +34747,20 @@ function rebuildCapture(row) {
33791
34747
  // it, IngestEvent.safeParse then refuses the assembled event, and the whole
33792
34748
  // capture becomes a permanent skip. That is the per-row door the rest of this
33793
34749
  // function exists to avoid, and this field was the last one still using it.
33794
- ...withList("exceptionIds", keepAll(attributes.exception_ids, EXCEPTION_ID))
34750
+ ...withList("exceptionIds", keepAll(attributes.exception_ids, EXCEPTION_ID)),
34751
+ // Carried, for the same reason exceptionIds is: it says WHY an enforced
34752
+ // detection let a value through, and a capture that means one thing live
34753
+ // and another when drained is worse than one that carries neither.
34754
+ //
34755
+ // Parsed rather than type-checked. The bag is free-form JSON, so a hand
34756
+ // edit or an older build can leave any string here; an unparseable one is
34757
+ // dropped rather than assembled into an event the deployment would refuse
34758
+ // with a 400 — which, on a drain that reads the head of the unstamped set
34759
+ // with no cursor, is the per-row door that retires the whole lane.
34760
+ ...withField(
34761
+ "redactDegradedTo",
34762
+ keep(stringOrUndefined(attributes.redact_degraded_to), REDACT_DEGRADED_TO)
34763
+ )
33795
34764
  // inspectionMs is DELIBERATELY not carried. It measures latency a live host
33796
34765
  // session actually waited on, and a row being drained hours later is not
33797
34766
  // that; the field's own contract says a replay leaves it absent rather than
@@ -33820,6 +34789,7 @@ function keepAll(value, schema) {
33820
34789
  var CORRELATION_ID = EventMetadata.shape.correlationId;
33821
34790
  var TRACE_ID = EventMetadata.shape.traceId;
33822
34791
  var EXCEPTION_ID = EventMetadata.shape.exceptionIds.unwrap().element;
34792
+ var REDACT_DEGRADED_TO = EventMetadata.shape.redactDegradedTo.unwrap();
33823
34793
  function isoOrUndefined(epochMs) {
33824
34794
  if (!Number.isFinite(epochMs)) return void 0;
33825
34795
  const iso = new Date(epochMs);
@@ -33899,7 +34869,6 @@ function attributesOf(raw) {
33899
34869
  // ../../packages/plugin-runtime/src/attached/history-sync.ts
33900
34870
  var HISTORY_REQUEST_TIMEOUT_MS = 15e3;
33901
34871
  var HISTORY_PASS_BUDGET_MS = 12e4;
33902
- var HISTORY_LEASE_STALE_MS = 6e4;
33903
34872
  var HEARTBEAT_EVERY_MS = 1e4;
33904
34873
  var PACE_INTERVAL_MS = 200;
33905
34874
  var MAX_ATTEMPTS = 4;
@@ -33908,6 +34877,23 @@ var SESSION_PAGE = 25;
33908
34877
  var ROW_PAGE = 200;
33909
34878
  var CAPTURE_GRACE_MS = 3e4;
33910
34879
  var CAPTURE_BATCH_SIZE = INGEST_BATCH_MAX;
34880
+ var CAPTURE_BATCH_BYTES = 1024 * 1024;
34881
+ function underByteCeiling(ready) {
34882
+ const fitting = [];
34883
+ const oversized = [];
34884
+ let bytes = 0;
34885
+ for (const item of ready) {
34886
+ const size = Buffer.byteLength(item.event.content, "utf8");
34887
+ if (size > CAPTURE_BATCH_BYTES) {
34888
+ oversized.push(item.id);
34889
+ continue;
34890
+ }
34891
+ if (bytes + size > CAPTURE_BATCH_BYTES) break;
34892
+ bytes += size;
34893
+ fitting.push(item);
34894
+ }
34895
+ return { fitting, oversized };
34896
+ }
33911
34897
  var STRUCTURAL_BUDGET_SHARE = 0.7;
33912
34898
  var BATCH_SIZE = AUDIT_EVENT_BATCH_MAX;
33913
34899
  function endpointFingerprint(endpoint) {
@@ -33937,8 +34923,7 @@ async function runHistorySync(deps) {
33937
34923
  const state = readControlPlaneCredentialFile(deps.settingsDir, connection);
33938
34924
  if (!state.usable) return didNotRun("credential-unusable");
33939
34925
  const nowMs = now();
33940
- const openedAtMs = readForwardHealth(deps.dataDir, nowMs)?.openedAtMs ?? null;
33941
- if (openedAtMs !== null && nowMs - openedAtMs < BREAKER_COOLDOWN_MS) {
34926
+ if (isForwardPaused(readForwardHealth(deps.dataDir, nowMs), nowMs)) {
33942
34927
  return didNotRun("breaker-open");
33943
34928
  }
33944
34929
  db = (deps.openStore ?? openLocalDatabase)(deps.dataDir);
@@ -33958,7 +34943,7 @@ async function runHistorySync(deps) {
33958
34943
  backlogBefore = recorded.backlogBefore;
33959
34944
  }
33960
34945
  const pid = process.pid;
33961
- if (!ledger.claim(pid, hostname5(), now(), HISTORY_LEASE_STALE_MS)) {
34946
+ if (!ledger.claim(pid, hostname5(), now(), HISTORY_SYNC_LEASE_STALE_MS)) {
33962
34947
  return didNotRun("already-running");
33963
34948
  }
33964
34949
  const client = deps.sendBatch !== void 0 && deps.sendCaptures !== void 0 && deps.sendOne !== void 0 ? void 0 : createRemoteClient({
@@ -34008,6 +34993,7 @@ async function runHistorySync(deps) {
34008
34993
  async function drain(d) {
34009
34994
  const startedAt = d.now();
34010
34995
  const deadline = startedAt + d.budgetMs;
34996
+ d.ledger.releaseStaleClaims(startedAt - HISTORY_SYNC_LEASE_STALE_MS);
34011
34997
  const structuralDeadline = Math.min(deadline, startedAt + d.budgetMs * STRUCTURAL_BUDGET_SHARE);
34012
34998
  let sent = 0;
34013
34999
  let skipped = 0;
@@ -34030,7 +35016,7 @@ async function drain(d) {
34030
35016
  for (const row of rows) {
34031
35017
  const event = rebuildAuditEvent(row, d.ledger.inspectionsFor(row.id));
34032
35018
  if (event === void 0) {
34033
- d.ledger.markSkipped([row.id]);
35019
+ d.ledger.markSkipped([row.id], d.now());
34034
35020
  skipped += 1;
34035
35021
  continue;
34036
35022
  }
@@ -34042,7 +35028,14 @@ async function drain(d) {
34042
35028
  break outer;
34043
35029
  }
34044
35030
  const chunk = ready.slice(i, i + BATCH_SIZE);
34045
- const result = await sendChunk(d, chunk, beat);
35031
+ const chunkIds = chunk.map((c) => c.id);
35032
+ d.ledger.claimRows(chunkIds, d.now());
35033
+ let result;
35034
+ try {
35035
+ result = await sendChunk(d, chunk, beat);
35036
+ } finally {
35037
+ releaseClaim(d, chunkIds);
35038
+ }
34046
35039
  sent += result.sent;
34047
35040
  skipped += result.skipped;
34048
35041
  if (result.stopped !== void 0) {
@@ -34100,7 +35093,7 @@ async function drainCaptures(d, deadline, beat) {
34100
35093
  ready.push({ id: row.id, event });
34101
35094
  }
34102
35095
  if (unbuildable.length > 0) {
34103
- d.ledger.markSkipped(unbuildable);
35096
+ d.ledger.markSkipped(unbuildable, d.now());
34104
35097
  skipped += unbuildable.length;
34105
35098
  }
34106
35099
  if (ready.length === 0) {
@@ -34108,7 +35101,24 @@ async function drainCaptures(d, deadline, beat) {
34108
35101
  await d.sleep(PACE_INTERVAL_MS);
34109
35102
  continue;
34110
35103
  }
34111
- const result = await sendCaptureChunk(d, ready, beat);
35104
+ const { fitting, oversized } = underByteCeiling(ready);
35105
+ if (oversized.length > 0) {
35106
+ d.ledger.markSkipped(oversized, d.now());
35107
+ skipped += oversized.length;
35108
+ }
35109
+ if (fitting.length === 0) {
35110
+ beat();
35111
+ await d.sleep(PACE_INTERVAL_MS);
35112
+ continue;
35113
+ }
35114
+ const readyIds = fitting.map((r) => r.id);
35115
+ d.ledger.claimRows(readyIds, d.now());
35116
+ let result;
35117
+ try {
35118
+ result = await sendCaptureChunk(d, fitting, beat);
35119
+ } finally {
35120
+ releaseClaim(d, readyIds);
35121
+ }
34112
35122
  sent += result.sent;
34113
35123
  skipped += result.skipped;
34114
35124
  if (result.stopped !== void 0) return { sent, skipped, stopped: result.stopped };
@@ -34136,7 +35146,7 @@ async function sendCaptureChunk(d, chunk, beat) {
34136
35146
  {
34137
35147
  const only = chunk.length === 1 ? chunk[0] : void 0;
34138
35148
  if (only !== void 0) {
34139
- d.ledger.markSkipped([only.id]);
35149
+ recordGaveUp(d, [only.id], outcome.verdict);
34140
35150
  return { sent: 0, skipped: 1 };
34141
35151
  }
34142
35152
  return await isolate(d, chunk, beat);
@@ -34163,7 +35173,8 @@ async function sendCapturesWithRetries(d, chunk, beat) {
34163
35173
  } catch (err) {
34164
35174
  const kind = classify(err);
34165
35175
  if (kind === "refused") return { verdict: "refused" };
34166
- if (kind === "skip") return { verdict: "skip" };
35176
+ if (kind === "payload-invalid") return { verdict: "payload-invalid" };
35177
+ if (kind === "deployment-refused") return { verdict: "deployment-refused" };
34167
35178
  if (attempt === MAX_ATTEMPTS - 1) return { verdict: "unreachable" };
34168
35179
  const ceiling = Math.min(MAX_BACKOFF_MS, 1e3 * 2 ** attempt);
34169
35180
  beat();
@@ -34205,7 +35216,7 @@ async function sendSingleRow(d, one, beat) {
34205
35216
  if (outcome.verdict === "refused" || outcome.verdict === "unreachable") {
34206
35217
  return { sent: 0, skipped: 0, stopped: outcome.verdict };
34207
35218
  }
34208
- d.ledger.markSkipped([one.id]);
35219
+ recordGaveUp(d, [one.id], outcome.verdict);
34209
35220
  return { sent: 0, skipped: 1 };
34210
35221
  }
34211
35222
  async function isolateStructural(d, chunk, beat) {
@@ -34229,7 +35240,8 @@ async function sendWithRetries(d, attempt, beat) {
34229
35240
  } catch (err) {
34230
35241
  const kind = classify(err);
34231
35242
  if (kind === "refused") return { verdict: "refused" };
34232
- if (kind === "skip") return { verdict: "skip" };
35243
+ if (kind === "payload-invalid") return { verdict: "payload-invalid" };
35244
+ if (kind === "deployment-refused") return { verdict: "deployment-refused" };
34233
35245
  if (i === MAX_ATTEMPTS - 1) return { verdict: "unreachable" };
34234
35246
  const ceiling = Math.min(MAX_BACKOFF_MS, 1e3 * 2 ** i);
34235
35247
  beat();
@@ -34238,6 +35250,22 @@ async function sendWithRetries(d, attempt, beat) {
34238
35250
  }
34239
35251
  return { verdict: "unreachable" };
34240
35252
  }
35253
+ function releaseClaim(d, ids) {
35254
+ try {
35255
+ d.ledger.releaseRows(ids);
35256
+ } catch {
35257
+ }
35258
+ }
35259
+ function recordGaveUp(d, ids, verdict) {
35260
+ switch (verdict) {
35261
+ case "deployment-refused":
35262
+ d.ledger.markRefused(ids, d.now());
35263
+ return;
35264
+ case "payload-invalid":
35265
+ d.ledger.markSkipped(ids, d.now());
35266
+ return;
35267
+ }
35268
+ }
34241
35269
  function statusOf2(err) {
34242
35270
  if (typeof err !== "object" || err === null || !("status" in err)) return null;
34243
35271
  const { status } = err;
@@ -34245,7 +35273,7 @@ function statusOf2(err) {
34245
35273
  return status >= 100 && status <= 599 ? status : null;
34246
35274
  }
34247
35275
  function classify(err) {
34248
- if (err.name === "RemoteRequestInvalid") return "skip";
35276
+ if (err.name === "RemoteRequestInvalid") return "payload-invalid";
34249
35277
  switch (statusOf2(err)) {
34250
35278
  // Terminal in a way a timeout is not: the credential may have died with an
34251
35279
  // offboarded member, and every later row would fail the same way.
@@ -34253,11 +35281,11 @@ function classify(err) {
34253
35281
  case 403:
34254
35282
  return "refused";
34255
35283
  // The deployment understood the request and rejected it. Re-sending an
34256
- // identical body cannot change that.
35284
+ // identical body TO THIS DEPLOYMENT cannot change that.
34257
35285
  case 400:
34258
35286
  case 413:
34259
35287
  case 422:
34260
- return "skip";
35288
+ return "deployment-refused";
34261
35289
  default:
34262
35290
  return "retry";
34263
35291
  }
@@ -34293,7 +35321,18 @@ async function runHistorySyncPass(base = defaultDataDir(), seams = {}) {
34293
35321
  // field whose capture half is one pass wide, so the surface beside
34294
35322
  // `sentTotal` and `pendingTotal` would announce a permanent loss once and
34295
35323
  // drop it on the next pass, while the rows stayed gone.
34296
- skippedTotal: result.counts.skipped + result.counts.capturesSkipped,
35324
+ //
35325
+ // EVERY reason the store can name, not just the original one. Splitting
35326
+ // `skipped` into its reasons gave the store a truer answer and silently
35327
+ // shrank this number twice over: a structural row a deployment rejected,
35328
+ // and a window a detach closed over undelivered, both used to land in
35329
+ // `skipped` and reach a surface, and after the splits each reached
35330
+ // nothing. A bucket this sum does not name is a row that disappears from
35331
+ // the only total anyone sees.
35332
+ //
35333
+ // The capture term needs no counterpart: that lane keeps both of its
35334
+ // reasons in one total, because neither is ever freed there.
35335
+ skippedTotal: result.counts.skipped + result.counts.refused + result.counts.detached + result.counts.capturesSkipped,
34297
35336
  // The first pass that ran is when this machine started sending, and it
34298
35337
  // keeps that answer across every later pass.
34299
35338
  startedAtMs: previous?.startedAtMs ?? result.atMs,
@@ -34330,10 +35369,13 @@ import { readFileSync as readFileSync17 } from "fs";
34330
35369
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
34331
35370
  import { randomUUID as randomUUID16 } from "crypto";
34332
35371
  import { readFile as readFile2, rm, writeFile as writeFile2 } from "fs/promises";
34333
- import { join as join26 } from "path";
35372
+ import { join as join27 } from "path";
34334
35373
 
34335
35374
  // ../../packages/plugin-runtime/src/attached/atomic-publish.ts
34336
35375
  import { rename as rename2 } from "fs/promises";
35376
+ var IMMEDIATE_RETRIES = 8;
35377
+ var TIMED_RETRIES = 4;
35378
+ var ATTEMPTS = 1 + IMMEDIATE_RETRIES + TIMED_RETRIES;
34337
35379
 
34338
35380
  // ../../packages/plugin-runtime/src/attached/posture-reporter.ts
34339
35381
  var POSTURE_REPORT_INTERVAL_MS = 60 * 60 * 1e3;
@@ -34345,11 +35387,11 @@ import { DatabaseSync as DatabaseSync4 } from "node:sqlite";
34345
35387
  // ../../packages/plugin-runtime/src/attached/posture-store.ts
34346
35388
  import { randomUUID as randomUUID17 } from "crypto";
34347
35389
  import { readFile as readFile3, rm as rm2, writeFile as writeFile3 } from "fs/promises";
34348
- import { join as join27 } from "path";
35390
+ import { join as join28 } from "path";
34349
35391
 
34350
35392
  // ../../packages/plugin-runtime/src/attached/sync-state.ts
34351
35393
  import { readFileSync as readFileSync18 } from "fs";
34352
- import { join as join28 } from "path";
35394
+ import { join as join29 } from "path";
34353
35395
 
34354
35396
  // ../../packages/plugin-runtime/src/attached/status.ts
34355
35397
  var REFUSAL_LINES = {
@@ -34370,6 +35412,14 @@ import { spawn as spawn2 } from "child_process";
34370
35412
  import { fileURLToPath as fileURLToPath3 } from "url";
34371
35413
  var SYNC_THROTTLE_MS = 15 * 60 * 1e3;
34372
35414
 
35415
+ // ../../packages/plugin-runtime/src/content-retention-pass.ts
35416
+ var MAX_ROWS_PER_SWEEP = 50 * 1e3;
35417
+
35418
+ // ../../packages/plugin-runtime/src/content-retention-trigger.ts
35419
+ import { spawn as spawn3 } from "child_process";
35420
+ import { fileURLToPath as fileURLToPath4 } from "url";
35421
+ var CONTENT_RETENTION_THROTTLE_MS = 60 * 60 * 1e3;
35422
+
34373
35423
  // ../../packages/plugin-runtime/src/attached/factory.ts
34374
35424
  import { hostname as hostname6 } from "os";
34375
35425