@lensmcp/protocol-types 1.26.1 → 1.26.2

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.
@@ -1 +1 @@
1
- "use strict";var m=Object.defineProperty;var r=(t,e)=>m(t,"name",{value:e,configurable:!0});var f=Object.defineProperty,o=r((t,e)=>f(t,"name",{value:e,configurable:!0}),"r"),x=Object.defineProperty,s=o((t,e)=>x(t,"name",{value:e,configurable:!0}),"c");import{renameSync as v,statSync as M,unlinkSync as E}from"node:fs";export function eventMaxBytes(t=process.env){const e=Number(t.LENSMCP_EVENT_MAX_BYTES);return Number.isFinite(e)&&e>0?e:50*1024*1024}r(eventMaxBytes,"eventMaxBytes"),o(eventMaxBytes,"eventMaxBytes"),s(eventMaxBytes,"eventMaxBytes");export function eventMaxFiles(t=process.env){const e=Number(t.LENSMCP_EVENT_MAX_FILES);return Number.isFinite(e)&&e>=1&&e<=20?Math.floor(e):5}r(eventMaxFiles,"eventMaxFiles"),o(eventMaxFiles,"eventMaxFiles"),s(eventMaxFiles,"eventMaxFiles");const b=1024*1024,a=new Map;export function maybeRotateEventFile(t,e,c){const i=(a.get(t)??0)+e,l=c?.maxBytes??eventMaxBytes(),u=c?.maxFiles??eventMaxFiles(),y=Math.min(b,l);if(i<y){a.set(t,i);return}try{const n=M(t).size;if(a.set(t,0),n<=l)return}catch{a.set(t,i);return}try{E(`${t}.${u}`)}catch{}for(let n=u-1;n>=1;n--)try{v(`${t}.${n}`,`${t}.${n+1}`)}catch{}try{v(t,`${t}.1`)}catch{}}r(maybeRotateEventFile,"maybeRotateEventFile"),o(maybeRotateEventFile,"maybeRotateEventFile"),s(maybeRotateEventFile,"maybeRotateEventFile");export function resetRotationThrottle(t){t===void 0?a.clear():a.delete(t)}r(resetRotationThrottle,"resetRotationThrottle"),o(resetRotationThrottle,"resetRotationThrottle"),s(resetRotationThrottle,"resetRotationThrottle");
1
+ "use strict";var y=Object.defineProperty;var r=(e,t)=>y(e,"name",{value:t,configurable:!0});var v=Object.defineProperty,o=r((e,t)=>v(e,"name",{value:t,configurable:!0}),"c");import{renameSync as l,statSync as f,unlinkSync as x}from"node:fs";export function eventMaxBytes(e=process.env){const t=Number(e.LENSMCP_EVENT_MAX_BYTES);return Number.isFinite(t)&&t>0?t:50*1024*1024}r(eventMaxBytes,"eventMaxBytes"),o(eventMaxBytes,"eventMaxBytes");export function eventMaxFiles(e=process.env){const t=Number(e.LENSMCP_EVENT_MAX_FILES);return Number.isFinite(t)&&t>=1&&t<=20?Math.floor(t):5}r(eventMaxFiles,"eventMaxFiles"),o(eventMaxFiles,"eventMaxFiles");const E=1024*1024,a=new Map;export function maybeRotateEventFile(e,t,i){const s=(a.get(e)??0)+t,c=i?.maxBytes??eventMaxBytes(),u=i?.maxFiles??eventMaxFiles(),m=Math.min(E,c);if(s<m){a.set(e,s);return}try{const n=f(e).size;if(a.set(e,0),n<=c)return}catch{a.set(e,s);return}try{x(`${e}.${u}`)}catch{}for(let n=u-1;n>=1;n--)try{l(`${e}.${n}`,`${e}.${n+1}`)}catch{}try{l(e,`${e}.1`)}catch{}}r(maybeRotateEventFile,"maybeRotateEventFile"),o(maybeRotateEventFile,"maybeRotateEventFile");export function resetRotationThrottle(e){e===void 0?a.clear():a.delete(e)}r(resetRotationThrottle,"resetRotationThrottle"),o(resetRotationThrottle,"resetRotationThrottle");
@@ -1 +1 @@
1
- "use strict";var s=Object.defineProperty;var a=(r,e)=>s(r,"name",{value:e,configurable:!0});var p=Object.defineProperty,c=a((r,e)=>p(r,"name",{value:e,configurable:!0}),"o"),u=Object.defineProperty,E=c((r,e)=>u(r,"name",{value:e,configurable:!0}),"s");export const CAPTURE_REQUEST_FILENAME="capture-request.json",CAPTURE_PRESENCE_FILENAME="capture-runner.json";export function appMatchesPage(r,e){const t=r.trim().toLowerCase();if(!t)return!1;if(e.project&&e.project.toLowerCase()===t)return!0;const o=e.url.toLowerCase();if(o===t||o.replace(/\/+$/,"")===t.replace(/\/+$/,""))return!0;try{const n=new URL(e.url);return/^\d+$/.test(t)?n.port===t:n.origin.toLowerCase()===t.replace(/\/+$/,"")}catch{return!1}}a(appMatchesPage,"appMatchesPage"),c(appMatchesPage,"appMatchesPage"),E(appMatchesPage,"appMatchesPage");export const CAPTURE_RULES_FILENAME="capture-rules.json";
1
+ "use strict";var c=Object.defineProperty;var o=(t,e)=>c(t,"name",{value:e,configurable:!0});var s=Object.defineProperty,u=o((t,e)=>s(t,"name",{value:e,configurable:!0}),"s");export const CAPTURE_REQUEST_FILENAME="capture-request.json",CAPTURE_PRESENCE_FILENAME="capture-runner.json";export function appMatchesPage(t,e){const r=t.trim().toLowerCase();if(!r)return!1;if(e.project&&e.project.toLowerCase()===r)return!0;const n=e.url.toLowerCase();if(n===r||n.replace(/\/+$/,"")===r.replace(/\/+$/,""))return!0;try{const a=new URL(e.url);return/^\d+$/.test(r)?a.port===r:a.origin.toLowerCase()===r.replace(/\/+$/,"")}catch{return!1}}o(appMatchesPage,"appMatchesPage"),u(appMatchesPage,"appMatchesPage");export const CAPTURE_RULES_FILENAME="capture-rules.json";
@@ -1 +1 @@
1
- "use strict";var d=Object.defineProperty;var t=(e,n)=>d(e,"name",{value:n,configurable:!0});var a=Object.defineProperty,c=t((e,n)=>a(e,"name",{value:n,configurable:!0}),"c"),g=Object.defineProperty,o=c((e,n)=>g(e,"name",{value:n,configurable:!0}),"t");const p={"~":"~~","/":"~s","\\":"~b","\0":"~0"},l={"~":"~",s:"/",b:"\\",0:"\0",d:"."},m=/%2f|%5c|%2e|%00/i;export function encodeSegment(e){return e==="."||e===".."?e.replace(/\./g,"~d"):encodeURIComponent(e.replace(/[~/\\\0]/g,n=>p[n])).replace(/%3A/g,":").replace(/%40/g,"@")}t(encodeSegment,"encodeSegment"),c(encodeSegment,"encodeSegment"),o(encodeSegment,"encodeSegment");export function decodeSegment(e){let n;try{n=decodeURIComponent(e)}catch{n=e}return m.test(e)?n:n.replace(/~([~sb0d])/g,(u,r)=>l[r])}t(decodeSegment,"decodeSegment"),c(decodeSegment,"decodeSegment"),o(decodeSegment,"decodeSegment");
1
+ "use strict";var o=Object.defineProperty;var c=(e,t)=>o(e,"name",{value:t,configurable:!0});var d=Object.defineProperty,n=c((e,t)=>d(e,"name",{value:t,configurable:!0}),"t");const a={"~":"~~","/":"~s","\\":"~b","\0":"~0"},p={"~":"~",s:"/",b:"\\",0:"\0",d:"."},g=/%2f|%5c|%2e|%00/i;export function encodeSegment(e){return e==="."||e===".."?e.replace(/\./g,"~d"):encodeURIComponent(e.replace(/[~/\\\0]/g,t=>a[t])).replace(/%3A/g,":").replace(/%40/g,"@")}c(encodeSegment,"encodeSegment"),n(encodeSegment,"encodeSegment");export function decodeSegment(e){let t;try{t=decodeURIComponent(e)}catch{t=e}return g.test(e)?t:t.replace(/~([~sb0d])/g,(l,r)=>p[r])}c(decodeSegment,"decodeSegment"),n(decodeSegment,"decodeSegment");
@@ -16,6 +16,7 @@ import type { PageVisitNavType, PageVisitRaw, PageVisitReadyBy, PageVisitRequest
16
16
  import type { WorktreeRunOutcome } from './workspace-actions.js';
17
17
  import type { DesignStage } from './goal-design.js';
18
18
  import type { DashExternalBefore, DashSqlBefore } from './metrics-reset.js';
19
+ import type { ExpectedFailureMatch } from './expected-failure.js';
19
20
  /** Bumped only on a breaking change to the stream framing itself. */
20
21
  export declare const DASHBOARD_PROTOCOL = 1;
21
22
  /** The swimlane a flow event belongs to (mirrors `FlowArea` in `@lensmcp/core`'s flow-shape). */
@@ -905,6 +906,49 @@ export interface DashErrorGroup {
905
906
  /** Who dismissed it — a person here, a person at the CLI, or an agent — and the reason they gave. */
906
907
  dismissedBy?: 'dashboard' | 'cli' | 'agent';
907
908
  dismissedReason?: string;
909
+ /** Occurrences of it a standing rule held back (overseer-86): not in `count`. On a group in `DashErrors.expected.groups`, all of them. */
910
+ expectedCount?: number;
911
+ /** The rule that holds it back — on a group in `DashErrors.expected.groups`. */
912
+ expectedBy?: string;
913
+ expectedReason?: string;
914
+ }
915
+ /** A standing rule as Errors lists it (overseer-86, expected-failure.ts `ExpectedRuleView`). */
916
+ export interface DashExpectedRule {
917
+ id: string;
918
+ match: ExpectedFailureMatch;
919
+ /** The match in a line: `auth · GET /session/token · 401`. */
920
+ label: string;
921
+ reason: string;
922
+ by: 'dashboard' | 'cli' | 'agent' | 'repository';
923
+ createdAt: number;
924
+ expiresAt?: number;
925
+ title?: string;
926
+ hits: number;
927
+ lastHitAt?: number;
928
+ lastHour: number;
929
+ /** It matches far more than its usual rate: said once, as «this expected failure is now happening much more often». */
930
+ surge?: {
931
+ since: number;
932
+ lastHour: number;
933
+ usualPerHour: number;
934
+ line: string;
935
+ };
936
+ }
937
+ /** What the standing rules held back from this list — never silent. */
938
+ export interface DashExpected {
939
+ /** «2 rules held back 61 occurrences in the last hour». */
940
+ line: string;
941
+ /** Rules that held something back in the last hour, and those occurrences. */
942
+ rulesHolding: number;
943
+ lastHour: number;
944
+ /** Occurrences held back across the groups the error log keeps (whole groups and parts of shown ones). */
945
+ held: number;
946
+ /** Every rule in effect. */
947
+ rules: DashExpectedRule[];
948
+ /** Groups every occurrence of which is held back — listed on request, marked «expected». */
949
+ groups: DashErrorGroup[];
950
+ /** Problems reading `lensmcp.json` → `config.expectedFailures`, if any. */
951
+ problems?: string[];
908
952
  }
909
953
  export interface DashErrors {
910
954
  at: number;
@@ -933,6 +977,8 @@ export interface DashErrors {
933
977
  * plus any the error log itself let go of. Per-cause drops are on each cause (`DashErrorCause.dropped`).
934
978
  */
935
979
  dropped?: number;
980
+ /** What standing rules held back, and the rules (overseer-86). Absent when no rule is in effect, and from an older server. */
981
+ expected?: DashExpected;
936
982
  }
937
983
  /** Where a cause surfaced: one of its groups, as a row of the cause («GET /documents → 500 ×30»). */
938
984
  export interface DashErrorSurface {
@@ -1,5 +1,5 @@
1
- "use strict";var p=Object.defineProperty;var n=(e,t)=>p(e,"name",{value:t,configurable:!0});var f=Object.defineProperty,s=n((e,t)=>f(e,"name",{value:t,configurable:!0}),"n"),g=Object.defineProperty,a=s((e,t)=>g(e,"name",{value:t,configurable:!0}),"n");export function joinId(e,t){const o=a(i=>i.replace(/%/g,"%25").replace(/:/g,"%3A"),"esc");return[e,...t.map(i=>o(i===void 0?"":String(i)))].join(":")}n(joinId,"joinId"),s(joinId,"joinId"),a(joinId,"joinId");export function foldMessage(e){return e?e.split(`
2
- `)[0].replace(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi,"<id>").replace(/\b[0-9A-HJKMNP-TV-Z]{26}\b/g,"<id>").replace(/0x[0-9a-f]+/gi,"<hex>").replace(/\b[0-9a-f]{12,}\b/gi,"<id>").replace(/\d+/g,"#").trim().slice(0,140):""}n(foldMessage,"foldMessage"),s(foldMessage,"foldMessage"),a(foldMessage,"foldMessage");const E=/^(?:Uncaught\s+(?:\(in promise\)\s+)?)?((?:[A-Za-z_$][\w$]*)?(?:Error|Exception|Failure|Fault|Rejection))(?:\s*\[[^\]]*\])?:\s*(.+)$/;function d(e){const t=E.exec((e??"").split(`
3
- `)[0].trim());return t?{name:t[1],message:t[2].trim()}:void 0}n(d,"c"),s(d,"r"),a(d,"named");export function appFrameOf(e){for(const t of(e??"").split(`
4
- `)){const o=/^\s*at\s+(.+)$/.exec(t);if(!o||/node_modules|node:internal|node:async_hooks|\(native\)|<anonymous>|\(internal\//.test(o[1]))continue;const i=/\(?([^()\s]+?):(\d+)(?::\d+)?\)?$/.exec(o[1].trim());return i?`${i[1].replace(/^.*?\/(?=(?:src|apps|libs)\/)/,"")}:${i[2]}`:o[1].trim()}}n(appFrameOf,"appFrameOf"),s(appFrameOf,"appFrameOf"),a(appFrameOf,"appFrameOf");export function errorCause(e){const t=d(e.stack),o=d(e.message),i=d(e.title),c=e.name?.trim()||t?.name||o?.name||i?.name;if(!c)return;let r=(t&&t.name===c?t.message:void 0)??e.message??i?.message??e.title??"";const h=d(r);h&&h.name===c&&(r=h.message),r=r.split(`
5
- `)[0].trim();const u=appFrameOf(e.stack),l=y.has(errorHeadline({name:c,message:r})?.id??"");return{id:joinId("cause",[c,foldMessage(r),l?void 0:u]),errorName:c,message:r,...u?{frame:u}:{}}}n(errorCause,"errorCause"),s(errorCause,"errorCause"),a(errorCause,"errorCause");const y=new Set(["missing-column","missing-table","connection-refused","out-of-memory"]);export function causeIdWithoutFrame(e){return joinId("cause",[e.errorName,foldMessage(e.message),void 0])}n(causeIdWithoutFrame,"causeIdWithoutFrame"),s(causeIdWithoutFrame,"causeIdWithoutFrame"),a(causeIdWithoutFrame,"causeIdWithoutFrame");const m=a(e=>e?` (\xAB${e}\xBB)`:"","q");export const ERROR_HEADLINES=[{id:"missing-column",match:a(e=>/column "?([\w.]+)"?(?: of relation "?[\w.]+"?)? does not exist|Unknown column '([^']+)'|ER_BAD_FIELD_ERROR/i.exec(e),"match"),say:a(e=>({headline:`The code expects a database column${m(e===!0?void 0:e[1]??e[2])} the database doesn't have`,hint:"Run the migrations, or add the migration the entity change needs."}),"say")},{id:"missing-table",match:a(e=>/relation "?([\w.]+)"? does not exist|Table '([^']+)' doesn't exist|ER_NO_SUCH_TABLE/i.exec(e),"match"),say:a(e=>({headline:`The code expects a database table${m(e===!0?void 0:e[1]??e[2])} the database doesn't have`,hint:"Run the migrations against this database."}),"say")},{id:"unique-violation",match:a((e,t)=>/duplicate key value violates unique constraint "?([\w.]+)"?|Duplicate entry '[^']*' for key '([^']+)'|ER_DUP_ENTRY/i.exec(e)||t.code==="23505","match"),say:a(e=>({headline:`A row with the same unique value already exists${m(e===!0?void 0:e[1]??e[2])}`,hint:"The code inserts a duplicate: look up the existing row first, or upsert."}),"say")},{id:"foreign-key-violation",match:a((e,t)=>/violates foreign key constraint "?([\w.]+)"?|a foreign key constraint fails|ER_NO_REFERENCED_ROW|ER_ROW_IS_REFERENCED/i.exec(e)||t.code==="23503","match"),say:a(e=>({headline:`A row points at a row that doesn't exist, or a row still in use was deleted${m(e===!0?void 0:e[1])}`,hint:"Create the referenced row first, or delete the rows that point at it."}),"say")},{id:"connection-refused",match:a((e,t)=>/ECONNREFUSED|connection refused|connect ECONNREFUSED/i.exec(e)||t.code==="ECONNREFUSED","match"),say:a(()=>({headline:"A service the code connects to is not running, or not listening where the code looks",hint:"Start it (database, cache, broker or API), or fix its host and port."}),"say")},{id:"out-of-memory",match:a((e,t)=>/heap out of memory|JavaScript heap|out of memory|ENOMEM|Allocation failed/i.exec(e)||t.code==="ENOMEM","match"),say:a(()=>({headline:"The process ran out of memory",hint:"Something holds or loads too much at once \u2014 look for an unbounded list, cache or query."}),"say")},{id:"jwt-expired",match:a((e,t)=>/jwt expired|token expired/i.exec(e)||t.name==="TokenExpiredError","match"),say:a(()=>({headline:"A sign-in token expired",hint:"Sign in again; if it keeps happening, the client is not refreshing its token."}),"say")},{id:"jwt-invalid",match:a((e,t)=>/jwt malformed|invalid signature|invalid token|jwt must be provided|jwt audience invalid|jwt issuer invalid/i.exec(e)||t.name==="JsonWebTokenError","match"),say:a(()=>({headline:"A sign-in token is not valid here",hint:"Its signature, audience or issuer does not match what this service expects."}),"say")},{id:"timeout",match:a((e,t)=>/ETIMEDOUT|ESOCKETTIMEDOUT|timed? ?out|timeout exceeded|statement timeout|canceling statement due to|Query read timeout/i.exec(e)||t.name==="TimeoutError"||t.code==="ETIMEDOUT","match"),say:a(()=>({headline:"Something took too long and was cut off",hint:"A slow query, a busy dependency or a lock \u2014 open the failing step to see which."}),"say")},{id:"unauthorized",match:a((e,t)=>t.status===401||t.name==="UnauthorizedException"||/^Unauthorized$/i.test(e.trim()),"match"),say:a(()=>({headline:"The request was not signed in (401)",hint:"It came without a valid session or token."}),"say")},{id:"forbidden",match:a((e,t)=>t.status===403||t.name==="ForbiddenException"||/^Forbidden(?: resource)?$/i.test(e.trim()),"match"),say:a(()=>({headline:"The signed-in user is not allowed to do this (403)",hint:"A role or permission check refused it."}),"say")}];export function errorHeadline(e){const t=[e.code,e.message].filter(Boolean).join(" ");for(const o of ERROR_HEADLINES){const i=o.match(t,e);if(i)return{id:o.id,...o.say(i)}}}n(errorHeadline,"errorHeadline"),s(errorHeadline,"errorHeadline"),a(errorHeadline,"errorHeadline");
1
+ "use strict";var l=Object.defineProperty;var n=(e,t)=>l(e,"name",{value:t,configurable:!0});var p=Object.defineProperty,i=n((e,t)=>p(e,"name",{value:t,configurable:!0}),"n");export function joinId(e,t){const o=i(a=>a.replace(/%/g,"%25").replace(/:/g,"%3A"),"esc");return[e,...t.map(a=>o(a===void 0?"":String(a)))].join(":")}n(joinId,"joinId"),i(joinId,"joinId");export function foldMessage(e){return e?e.split(`
2
+ `)[0].replace(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi,"<id>").replace(/\b[0-9A-HJKMNP-TV-Z]{26}\b/g,"<id>").replace(/0x[0-9a-f]+/gi,"<hex>").replace(/\b[0-9a-f]{12,}\b/gi,"<id>").replace(/\d+/g,"#").trim().slice(0,140):""}n(foldMessage,"foldMessage"),i(foldMessage,"foldMessage");const f=/^(?:Uncaught\s+(?:\(in promise\)\s+)?)?((?:[A-Za-z_$][\w$]*)?(?:Error|Exception|Failure|Fault|Rejection))(?:\s*\[[^\]]*\])?:\s*(.+)$/;function c(e){const t=f.exec((e??"").split(`
3
+ `)[0].trim());return t?{name:t[1],message:t[2].trim()}:void 0}n(c,"r"),i(c,"named");export function appFrameOf(e){for(const t of(e??"").split(`
4
+ `)){const o=/^\s*at\s+(.+)$/.exec(t);if(!o||/node_modules|node:internal|node:async_hooks|\(native\)|<anonymous>|\(internal\//.test(o[1]))continue;const a=/\(?([^()\s]+?):(\d+)(?::\d+)?\)?$/.exec(o[1].trim());return a?`${a[1].replace(/^.*?\/(?=(?:src|apps|libs)\/)/,"")}:${a[2]}`:o[1].trim()}}n(appFrameOf,"appFrameOf"),i(appFrameOf,"appFrameOf");export function errorCause(e){const t=c(e.stack),o=c(e.message),a=c(e.title),r=e.name?.trim()||t?.name||o?.name||a?.name;if(!r)return;let s=(t&&t.name===r?t.message:void 0)??e.message??a?.message??e.title??"";const m=c(s);m&&m.name===r&&(s=m.message),s=s.split(`
5
+ `)[0].trim();const h=appFrameOf(e.stack),u=g.has(errorHeadline({name:r,message:s})?.id??"");return{id:joinId("cause",[r,foldMessage(s),u?void 0:h]),errorName:r,message:s,...h?{frame:h}:{}}}n(errorCause,"errorCause"),i(errorCause,"errorCause");const g=new Set(["missing-column","missing-table","connection-refused","out-of-memory"]);export function causeIdWithoutFrame(e){return joinId("cause",[e.errorName,foldMessage(e.message),void 0])}n(causeIdWithoutFrame,"causeIdWithoutFrame"),i(causeIdWithoutFrame,"causeIdWithoutFrame");const d=i(e=>e?` (\xAB${e}\xBB)`:"","q");export const ERROR_HEADLINES=[{id:"missing-column",match:i(e=>/column "?([\w.]+)"?(?: of relation "?[\w.]+"?)? does not exist|Unknown column '([^']+)'|ER_BAD_FIELD_ERROR/i.exec(e),"match"),say:i(e=>({headline:`The code expects a database column${d(e===!0?void 0:e[1]??e[2])} the database doesn't have`,hint:"Run the migrations, or add the migration the entity change needs."}),"say")},{id:"missing-table",match:i(e=>/relation "?([\w.]+)"? does not exist|Table '([^']+)' doesn't exist|ER_NO_SUCH_TABLE/i.exec(e),"match"),say:i(e=>({headline:`The code expects a database table${d(e===!0?void 0:e[1]??e[2])} the database doesn't have`,hint:"Run the migrations against this database."}),"say")},{id:"unique-violation",match:i((e,t)=>/duplicate key value violates unique constraint "?([\w.]+)"?|Duplicate entry '[^']*' for key '([^']+)'|ER_DUP_ENTRY/i.exec(e)||t.code==="23505","match"),say:i(e=>({headline:`A row with the same unique value already exists${d(e===!0?void 0:e[1]??e[2])}`,hint:"The code inserts a duplicate: look up the existing row first, or upsert."}),"say")},{id:"foreign-key-violation",match:i((e,t)=>/violates foreign key constraint "?([\w.]+)"?|a foreign key constraint fails|ER_NO_REFERENCED_ROW|ER_ROW_IS_REFERENCED/i.exec(e)||t.code==="23503","match"),say:i(e=>({headline:`A row points at a row that doesn't exist, or a row still in use was deleted${d(e===!0?void 0:e[1])}`,hint:"Create the referenced row first, or delete the rows that point at it."}),"say")},{id:"connection-refused",match:i((e,t)=>/ECONNREFUSED|connection refused|connect ECONNREFUSED/i.exec(e)||t.code==="ECONNREFUSED","match"),say:i(()=>({headline:"A service the code connects to is not running, or not listening where the code looks",hint:"Start it (database, cache, broker or API), or fix its host and port."}),"say")},{id:"out-of-memory",match:i((e,t)=>/heap out of memory|JavaScript heap|out of memory|ENOMEM|Allocation failed/i.exec(e)||t.code==="ENOMEM","match"),say:i(()=>({headline:"The process ran out of memory",hint:"Something holds or loads too much at once \u2014 look for an unbounded list, cache or query."}),"say")},{id:"jwt-expired",match:i((e,t)=>/jwt expired|token expired/i.exec(e)||t.name==="TokenExpiredError","match"),say:i(()=>({headline:"A sign-in token expired",hint:"Sign in again; if it keeps happening, the client is not refreshing its token."}),"say")},{id:"jwt-invalid",match:i((e,t)=>/jwt malformed|invalid signature|invalid token|jwt must be provided|jwt audience invalid|jwt issuer invalid/i.exec(e)||t.name==="JsonWebTokenError","match"),say:i(()=>({headline:"A sign-in token is not valid here",hint:"Its signature, audience or issuer does not match what this service expects."}),"say")},{id:"timeout",match:i((e,t)=>/ETIMEDOUT|ESOCKETTIMEDOUT|timed? ?out|timeout exceeded|statement timeout|canceling statement due to|Query read timeout/i.exec(e)||t.name==="TimeoutError"||t.code==="ETIMEDOUT","match"),say:i(()=>({headline:"Something took too long and was cut off",hint:"A slow query, a busy dependency or a lock \u2014 open the failing step to see which."}),"say")},{id:"unauthorized",match:i((e,t)=>t.status===401||t.name==="UnauthorizedException"||/^Unauthorized$/i.test(e.trim()),"match"),say:i(()=>({headline:"The request was not signed in (401)",hint:"It came without a valid session or token."}),"say")},{id:"forbidden",match:i((e,t)=>t.status===403||t.name==="ForbiddenException"||/^Forbidden(?: resource)?$/i.test(e.trim()),"match"),say:i(()=>({headline:"The signed-in user is not allowed to do this (403)",hint:"A role or permission check refused it."}),"say")}];export function errorHeadline(e){const t=[e.code,e.message].filter(Boolean).join(" ");for(const o of ERROR_HEADLINES){const a=o.match(t,e);if(a)return{id:o.id,...o.say(a)}}}n(errorHeadline,"errorHeadline"),i(errorHeadline,"errorHeadline");
@@ -1 +1 @@
1
- "use strict";var E=Object.defineProperty;var s=(e,r)=>E(e,"name",{value:r,configurable:!0});var m=Object.defineProperty,c=s((e,r)=>m(e,"name",{value:r,configurable:!0}),"s"),p=Object.defineProperty,l=c((e,r)=>p(e,"name",{value:r,configurable:!0}),"s");export const ERROR_DISMISSED="error-dismissed",ERROR_RESTORED="error-restored",LENS_EVENT_SOURCE="lens",MAX_DISMISSAL_EVENT_IDS=200;const y=2048;export const MAX_DISMISSAL_REASON_CHARS=500;const b=300,I=new Set(["dashboard","cli","agent"]);export function readErrorDismissal(e){if(e.source!==LENS_EVENT_SOURCE||!e.raw||typeof e.raw!="object")return;const r=e.raw,i=r.groupId;if(typeof i!="string"||i.length===0||i.length>2048)return;if(r.kind===ERROR_RESTORED)return{kind:ERROR_RESTORED,groupId:i};if(r.kind!==ERROR_DISMISSED)return;const n=r.until;if(typeof n!="number"||!Number.isFinite(n))return;const f=Array.isArray(r.eventIds)?r.eventIds.filter(t=>typeof t=="string"&&t.length>0).slice(0,200):[],o=I.has(r.by)?r.by:void 0,a=l((t,S)=>typeof t=="string"&&t.trim()?t.trim().slice(0,S):void 0,"text"),d=a(r.reason,500),u=a(r.title,300);return{kind:ERROR_DISMISSED,groupId:i,until:Math.min(n,e.timestamp),eventIds:f,...o?{by:o}:{},...d?{reason:d}:{},...u?{title:u}:{}}}s(readErrorDismissal,"readErrorDismissal"),c(readErrorDismissal,"readErrorDismissal"),l(readErrorDismissal,"readErrorDismissal");
1
+ "use strict";var f=Object.defineProperty;var s=(t,r)=>f(t,"name",{value:r,configurable:!0});var E=Object.defineProperty,S=s((t,r)=>E(t,"name",{value:r,configurable:!0}),"s");export const ERROR_DISMISSED="error-dismissed",ERROR_RESTORED="error-restored",LENS_EVENT_SOURCE="lens",MAX_DISMISSAL_EVENT_IDS=200;const g=2048;export const MAX_DISMISSAL_REASON_CHARS=500;const m=300,I=new Set(["dashboard","cli","agent"]);export function readErrorDismissal(t){if(t.source!==LENS_EVENT_SOURCE||!t.raw||typeof t.raw!="object")return;const r=t.raw,i=r.groupId;if(typeof i!="string"||i.length===0||i.length>2048)return;if(r.kind===ERROR_RESTORED)return{kind:ERROR_RESTORED,groupId:i};if(r.kind!==ERROR_DISMISSED)return;const n=r.until;if(typeof n!="number"||!Number.isFinite(n))return;const c=Array.isArray(r.eventIds)?r.eventIds.filter(e=>typeof e=="string"&&e.length>0).slice(0,200):[],o=I.has(r.by)?r.by:void 0,a=S((e,l)=>typeof e=="string"&&e.trim()?e.trim().slice(0,l):void 0,"text"),d=a(r.reason,500),u=a(r.title,300);return{kind:ERROR_DISMISSED,groupId:i,until:Math.min(n,t.timestamp),eventIds:c,...o?{by:o}:{},...d?{reason:d}:{},...u?{title:u}:{}}}s(readErrorDismissal,"readErrorDismissal"),S(readErrorDismissal,"readErrorDismissal");
package/lib/event-loop.js CHANGED
@@ -1 +1 @@
1
- "use strict";var f=Object.defineProperty;var s=(e,t)=>f(e,"name",{value:t,configurable:!0});var w=Object.defineProperty,a=s((e,t)=>w(e,"name",{value:t,configurable:!0}),"r"),h=Object.defineProperty,l=a((e,t)=>h(e,"name",{value:t,configurable:!0}),"r");export const LENS_CAUSES={"lensmcp-gc":"forced GC","lensmcp-cleanup":"cleanup","lensmcp-write":"writing events","lensmcp-capture":"capturing values"};export function lensOwnWork(e){const t=typeof e.cause=="string"&&e.cause.startsWith("lensmcp-");if(!t&&!(typeof e.lensMs=="number"&&e.durationMs>0&&e.lensMs>=e.durationMs/2))return;const o=t?LENS_CAUSES[e.cause]:void 0;return o?`LensMCP's own work \u2014 ${o}`:"LensMCP's own work"}s(lensOwnWork,"lensOwnWork"),a(lensOwnWork,"lensOwnWork"),l(lensOwnWork,"lensOwnWork");export function waitedBehind(e){const t=new Set,o=new Set;for(const n of e.evidence)n.relation==="executing"||(n.requestId?n.requestId===e.requestId:!n.flowId||n.flowId===e.flowId)||(t.add(n.requestId??n.flowId),n.flowId&&n.flowId!==e.flowId&&o.add(n.flowId));return{requests:t.size,flows:o.size,atLeast:e.evidenceTruncated}}s(waitedBehind,"waitedBehind"),a(waitedBehind,"waitedBehind"),l(waitedBehind,"waitedBehind");export function waitedLine(e){const t=waitedBehind(e);return t.requests?`${t.atLeast?"at least ":""}${t.requests} request${t.requests===1?"":"s"} waited behind it`:void 0}s(waitedLine,"waitedLine"),a(waitedLine,"waitedLine"),l(waitedLine,"waitedLine");export function flowStalls(e,t){const o={ran:[],overlapped:[]};for(const n of e){if(lensOwnWork(n))continue;if(n.flowId===t){o.ran.push(n);continue}const u=n.endAt??n.observedAt,d=n.evidence.filter(r=>r.flowId===t).map(r=>[Math.max(r.startAt,n.startAt),Math.min(r.endAt,u)]).filter(([r,i])=>i>=r).sort((r,i)=>r[0]-i[0]);if(!d.length)continue;let p=0,c=-1/0;for(const[r,i]of d)i>c&&(p+=i-Math.max(r,c)),c=Math.max(c,i);o.overlapped.push({incident:n,overlapMs:Math.round(p*100)/100})}return o}s(flowStalls,"flowStalls"),a(flowStalls,"flowStalls"),l(flowStalls,"flowStalls");export function overlapLine(e){if(!e.length)return;const t=[...new Set(e.map(u=>u.incident.loop.project))],o=t.length<=2?t.join(" and "):`${t.length} services`,n=e.length;return{count:n,services:t,longestMs:Math.max(...e.map(u=>u.overlapMs)),text:`${n} pause${n===1?"":"s"} in ${o} while this flow was open \u2014 not this flow\u2019s code`}}s(overlapLine,"overlapLine"),a(overlapLine,"overlapLine"),l(overlapLine,"overlapLine");export const LOOP_STARTUP_MS=6e4;export function loopStartedAt(e){if(!e.startsWith("node:"))return;const t=Number(e.slice(e.lastIndexOf(":")+1));return Number.isFinite(t)&&t>0?t:void 0}s(loopStartedAt,"loopStartedAt"),a(loopStartedAt,"loopStartedAt"),l(loopStartedAt,"loopStartedAt");export function loopPhaseAt(e,t){const o=loopStartedAt(e);if(o===void 0)return;const n=Math.max(0,Math.round(t-o));return{phase:n<LOOP_STARTUP_MS?"startup":"running",sinceStartMs:n}}s(loopPhaseAt,"loopPhaseAt"),a(loopPhaseAt,"loopPhaseAt"),l(loopPhaseAt,"loopPhaseAt");
1
+ "use strict";var f=Object.defineProperty;var r=(t,e)=>f(t,"name",{value:e,configurable:!0});var p=Object.defineProperty,a=r((t,e)=>p(t,"name",{value:e,configurable:!0}),"r");export const LENS_CAUSES={"lensmcp-gc":"forced GC","lensmcp-cleanup":"cleanup","lensmcp-write":"writing events","lensmcp-capture":"capturing values"};export function lensOwnWork(t){const e=typeof t.cause=="string"&&t.cause.startsWith("lensmcp-");if(!e&&!(typeof t.lensMs=="number"&&t.durationMs>0&&t.lensMs>=t.durationMs/2))return;const o=e?LENS_CAUSES[t.cause]:void 0;return o?`LensMCP's own work \u2014 ${o}`:"LensMCP's own work"}r(lensOwnWork,"lensOwnWork"),a(lensOwnWork,"lensOwnWork");export function waitedBehind(t){const e=new Set,o=new Set;for(const n of t.evidence)n.relation==="executing"||(n.requestId?n.requestId===t.requestId:!n.flowId||n.flowId===t.flowId)||(e.add(n.requestId??n.flowId),n.flowId&&n.flowId!==t.flowId&&o.add(n.flowId));return{requests:e.size,flows:o.size,atLeast:t.evidenceTruncated}}r(waitedBehind,"waitedBehind"),a(waitedBehind,"waitedBehind");export function waitedLine(t){const e=waitedBehind(t);return e.requests?`${e.atLeast?"at least ":""}${e.requests} request${e.requests===1?"":"s"} waited behind it`:void 0}r(waitedLine,"waitedLine"),a(waitedLine,"waitedLine");export function flowStalls(t,e){const o={ran:[],overlapped:[]};for(const n of t){if(lensOwnWork(n))continue;if(n.flowId===e){o.ran.push(n);continue}const u=n.endAt??n.observedAt,c=n.evidence.filter(s=>s.flowId===e).map(s=>[Math.max(s.startAt,n.startAt),Math.min(s.endAt,u)]).filter(([s,i])=>i>=s).sort((s,i)=>s[0]-i[0]);if(!c.length)continue;let d=0,l=-1/0;for(const[s,i]of c)i>l&&(d+=i-Math.max(s,l)),l=Math.max(l,i);o.overlapped.push({incident:n,overlapMs:Math.round(d*100)/100})}return o}r(flowStalls,"flowStalls"),a(flowStalls,"flowStalls");export function overlapLine(t){if(!t.length)return;const e=[...new Set(t.map(u=>u.incident.loop.project))],o=e.length<=2?e.join(" and "):`${e.length} services`,n=t.length;return{count:n,services:e,longestMs:Math.max(...t.map(u=>u.overlapMs)),text:`${n} pause${n===1?"":"s"} in ${o} while this flow was open \u2014 not this flow\u2019s code`}}r(overlapLine,"overlapLine"),a(overlapLine,"overlapLine");export const LOOP_STARTUP_MS=6e4;export function loopStartedAt(t){if(!t.startsWith("node:"))return;const e=Number(t.slice(t.lastIndexOf(":")+1));return Number.isFinite(e)&&e>0?e:void 0}r(loopStartedAt,"loopStartedAt"),a(loopStartedAt,"loopStartedAt");export function loopPhaseAt(t,e){const o=loopStartedAt(t);if(o===void 0)return;const n=Math.max(0,Math.round(e-o));return{phase:n<LOOP_STARTUP_MS?"startup":"running",sinceStartMs:n}}r(loopPhaseAt,"loopPhaseAt"),a(loopPhaseAt,"loopPhaseAt");
@@ -0,0 +1,251 @@
1
+ import type { BaseEvent } from './event.js';
2
+ /**
3
+ * A standing rule that says «in these flows, this failure is expected» (issues/open/overseer-86).
4
+ *
5
+ * A dismissal (error-dismissal.ts) covers the past: «I have seen this one». Some failures are expected every time —
6
+ * a signed-out browser asking for a session token, a budget gate refusing a model call, one stranded test business
7
+ * retrying until its deadline — and a person or an agent had to recognise each occurrence again. A rule holds the
8
+ * occurrences it matches back from the error lists and from «is anything broken», and counts them.
9
+ *
10
+ * Where a rule comes from:
11
+ * - RUN TIME — a person in the dashboard, a person at the CLI, an agent through `observe_expect_errors`. An EVENT ON THE
12
+ * BUS, for the reason a dismissal is one: every lens process folds the same file in the same order, and a restart
13
+ * replays it. Undone the same way (`expected-rule-removed`). It needs a reason, and it ends: 7 days unless said,
14
+ * never more than 30.
15
+ * - THE REPOSITORY — `lensmcp.json` → `config.expectedFailures`, committed: the failures expected in this product for
16
+ * good. Every checkout and every agent starts with them; undone by editing the file.
17
+ *
18
+ * What keeps it from becoming a way to stop seeing failures:
19
+ * - **Never broad.** A rule needs a flow scope (`route`, `span` or `flow`) AND an outcome (`status`, `error` or
20
+ * `message`). «Everything in engine» is refused (`checkExpectedMatch`).
21
+ * - **Never silent.** Whatever list held something back says how many occurrences and how many rules
22
+ * (`heldBackLine`); the rules are listed with reason, author, last hit and hit count; held occurrences stay readable.
23
+ * - **It ends.** A run-time rule past its expiry holds nothing back.
24
+ * - **A change in rate is said.** A rule that suddenly matches far more than it usually does is reported
25
+ * (`ExpectedRuleBook.surging`).
26
+ */
27
+ export declare const EXPECTED_RULE_SET = "expected-rule-set";
28
+ export declare const EXPECTED_RULE_REMOVED = "expected-rule-removed";
29
+ /** Who wrote a rule: a person in the dashboard, a person at the CLI, an agent, or the repository's `lensmcp.json`. */
30
+ export type ExpectedRuleAuthor = 'dashboard' | 'cli' | 'agent' | 'repository';
31
+ /** A run-time rule's life when its writer names none. */
32
+ export declare const EXPECTED_RULE_DEFAULT_TTL_MS: number;
33
+ /** The longest a run-time rule may live: past it, a rule belongs in the repository. */
34
+ export declare const EXPECTED_RULE_MAX_TTL_MS: number;
35
+ export declare const EXPECTED_RULE_MIN_REASON_CHARS = 8;
36
+ export declare const MAX_EXPECTED_REASON_CHARS = 500;
37
+ /**
38
+ * What a rule matches on. Patterns are case-insensitive globs (`*` any run, `?` one character), whole-text except
39
+ * `message`, which may occur anywhere in the message. A `flow` ending in `:` is a kind (`api:`, `job:`).
40
+ */
41
+ export interface ExpectedFailureMatch {
42
+ /** The service (Nx project) — narrows; not a scope by itself. */
43
+ service?: string;
44
+ /** `GET /session/token`, or a path alone (`/session/token`). */
45
+ route?: string;
46
+ /** A traced call's name: `SessionTokenService.tokenForSession`. */
47
+ span?: string;
48
+ /** The flow's id or kind: `job:product-analysis-*`, `api:`. A job also answers to `job:<queue>` and `job:<job id>`. */
49
+ flow?: string;
50
+ /** The HTTP status the request answered. */
51
+ status?: number;
52
+ /** An error key or class: `supervisor.preparationBudgetUnavailable`, `DelayedError`. */
53
+ error?: string;
54
+ /** A pattern the message contains. */
55
+ message?: string;
56
+ /** One attribute of the flow — a tenant id. Looked up on the failure and on the other events of its flow. */
57
+ attribute?: {
58
+ name: string;
59
+ value: string;
60
+ };
61
+ }
62
+ export interface ExpectedFailureRule {
63
+ id: string;
64
+ match: ExpectedFailureMatch;
65
+ /** Why it is expected here, in the writer's words. */
66
+ reason: string;
67
+ by: ExpectedRuleAuthor;
68
+ createdAt: number;
69
+ /** Absent only on a repository rule, which lasts while the file says it. */
70
+ expiresAt?: number;
71
+ /** What it was made from, for a list that no longer holds the failure. */
72
+ title?: string;
73
+ }
74
+ export interface ExpectedRuleRemoval {
75
+ kind: typeof EXPECTED_RULE_REMOVED;
76
+ id: string;
77
+ by?: Exclude<ExpectedRuleAuthor, 'repository'>;
78
+ }
79
+ export type ExpectedRuleChange = ({
80
+ kind: typeof EXPECTED_RULE_SET;
81
+ } & ExpectedFailureRule) | ExpectedRuleRemoval;
82
+ /** The fields that make a flow scope, and those that make an outcome. */
83
+ export declare const EXPECTED_SCOPE_FIELDS: readonly ["route", "span", "flow"];
84
+ export declare const EXPECTED_OUTCOME_FIELDS: readonly ["status", "error", "message"];
85
+ /**
86
+ * A match as written by anyone — a tool's input, a bus event, a line of `lensmcp.json` — checked and normalised, or why
87
+ * it is refused. Refused when it is not narrow: no flow scope, or no outcome.
88
+ */
89
+ export declare function checkExpectedMatch(input: unknown): {
90
+ match: ExpectedFailureMatch;
91
+ } | {
92
+ error: string;
93
+ };
94
+ /** A rule's match in a line: `auth · GET /session/token · 401`. */
95
+ export declare function describeExpectedMatch(m: ExpectedFailureMatch): string;
96
+ /**
97
+ * Read a rule or its removal out of a bus event, or nothing. Total: the bus is a file any local process appends to.
98
+ * Its `createdAt` is the event's timestamp at the latest, and its life at most `EXPECTED_RULE_MAX_TTL_MS` from then: no
99
+ * event can make a rule ahead, or one that never ends. A rule that is not narrow is not one.
100
+ */
101
+ export declare function readExpectedRule(event: Pick<BaseEvent, 'source' | 'timestamp' | 'raw'>): ExpectedRuleChange | undefined;
102
+ /** A rule's life in ms from the hours a writer asked for: the default when none, never past the maximum. */
103
+ export declare function expectedRuleTtlMs(hours: number | undefined): number;
104
+ /**
105
+ * `lensmcp.json` → `config.expectedFailures`: each entry the match's fields (or a `match` object), a `reason`, and an
106
+ * optional `id`. A wrong entry is dropped by itself and named; the rest still count.
107
+ */
108
+ export declare function readRepositoryExpectedRules(raw: unknown, createdAt: number): {
109
+ rules: ExpectedFailureRule[];
110
+ problems: string[];
111
+ };
112
+ /** What a rule can be matched against, read off a failure and what the lens knows of its request and its flow. */
113
+ export interface FailureFacts {
114
+ service?: string;
115
+ method?: string;
116
+ /** The route pattern and the path it was called on, as far as known. */
117
+ routes?: string[];
118
+ span?: string;
119
+ flowId?: string;
120
+ /** Other names its flow answers to: a job's `job:<queue>`, `job:<job id>`. */
121
+ flowNames?: string[];
122
+ status?: number;
123
+ errorName?: string;
124
+ /** An error's own key fields (`errorKey`, `reason`), when it carries them. */
125
+ errorKeys?: string[];
126
+ message?: string;
127
+ attributes?: Record<string, string>;
128
+ requestId?: string;
129
+ }
130
+ /** The attributes an event states: string context fields, and `attributes` / a span's `attributes` and captured arguments / a job's `data`, one level deep. */
131
+ export declare function eventAttributes(e: Pick<BaseEvent, 'context' | 'raw'>): Record<string, string> | undefined;
132
+ /** What a failure event says of itself. `enrich` adds its request's and its flow's. */
133
+ export declare function failureFacts(e: Pick<BaseEvent, 'context' | 'raw' | 'message' | 'title'>): FailureFacts;
134
+ /** What the lens learned of one request from its own reports: the service's answer, the gateway's hop. */
135
+ export interface RequestFacts {
136
+ service?: string;
137
+ method?: string;
138
+ route?: string;
139
+ path?: string;
140
+ status?: number;
141
+ }
142
+ /**
143
+ * What a failure's request and flow said elsewhere, kept so a rule can be matched against them: a span that threw does
144
+ * not say the route or the status its request answered (the request's own report does, a moment later), and a tenant
145
+ * id is stated on one event of a flow, not every one. Bounded; cheap per event.
146
+ */
147
+ export declare class FailureContextIndex {
148
+ private readonly maxRequests;
149
+ private readonly maxFlows;
150
+ private readonly requests;
151
+ private readonly flows;
152
+ constructor(maxRequests?: number, maxFlows?: number);
153
+ /** Learn from one bus event. Returns the request id whose answer it reported, if it did. */
154
+ observe(e: Pick<BaseEvent, 'source' | 'context' | 'raw'>): string | undefined;
155
+ request(requestId: string | undefined): RequestFacts | undefined;
156
+ /** The facts with what the request and the flow said added where the failure itself was silent. */
157
+ enrich(f: FailureFacts): FailureFacts;
158
+ }
159
+ /** Does this failure match the rule's every field? */
160
+ export declare function expectedMatches(m: ExpectedFailureMatch, f: FailureFacts): boolean;
161
+ /**
162
+ * Does the rule's verdict on an occurrence depend on more than what every occurrence of one error group shares? A flow,
163
+ * an attribute — and a message pattern with a number in it, since a group's messages differ in their numbers.
164
+ */
165
+ export declare function expectedMatchIsPerOccurrence(m: ExpectedFailureMatch): boolean;
166
+ /**
167
+ * A narrow match for «always expect this here», from one occurrence's facts: its service, its route (else its span,
168
+ * else its flow's kind) and its status (else its error's class, else its message with the numbers left open).
169
+ */
170
+ export declare function suggestExpectedMatch(f: FailureFacts): ExpectedFailureMatch | undefined;
171
+ /** A rule that ended: removed by someone, or past its date. */
172
+ export interface EndedExpectedRule extends ExpectedFailureRule {
173
+ endedAt: number;
174
+ why: 'removed' | 'expired' | 'dropped from lensmcp.json';
175
+ removedBy?: ExpectedRuleRemoval['by'];
176
+ }
177
+ /** A rule as a list shows it: what it is, and what it has done. */
178
+ export interface ExpectedRuleView extends ExpectedFailureRule {
179
+ /** Occurrences it held back since this process started. */
180
+ hits: number;
181
+ lastHitAt?: number;
182
+ /** Of them, in the hour before the reading. */
183
+ lastHour: number;
184
+ /** Set while it matches far more than its usual rate — said once, as a warning. */
185
+ surge?: ExpectedSurge;
186
+ }
187
+ export interface ExpectedSurge {
188
+ since: number;
189
+ lastHour: number;
190
+ /** Its usual hourly rate over the day before the last hour. */
191
+ usualPerHour: number;
192
+ }
193
+ /** How much more than usual is a surge, from how many an hour, after how much history. */
194
+ export declare const EXPECTED_SURGE_FACTOR = 10;
195
+ export declare const EXPECTED_SURGE_MIN_PER_HOUR = 20;
196
+ /**
197
+ * The rules one process holds — the repository's and the bus's — and what each has held back. Pure; the clock is
198
+ * passed in. A reader (the runtime reducer, the dashboard's error log) asks it which rule holds a failure, tells it
199
+ * what was held, and lists it.
200
+ */
201
+ export declare class ExpectedRuleBook {
202
+ private readonly startedAt;
203
+ private readonly runtime;
204
+ private repository;
205
+ private repositoryKey;
206
+ private readonly stats;
207
+ private readonly ended;
208
+ /** Bumped whenever the rules in effect change — what a holder re-reads its held occurrences on. */
209
+ version: number;
210
+ constructor(startedAt?: number);
211
+ /** Fold a bus event. True when it was a rule or a removal. */
212
+ apply(e: Pick<BaseEvent, 'source' | 'timestamp' | 'raw'>, now: number): boolean;
213
+ /** Replace the repository's rules. True when they changed. */
214
+ setRepository(rules: readonly ExpectedFailureRule[], now: number): boolean;
215
+ /** End the run-time rules past their date. True when one ended. */
216
+ expire(now: number): boolean;
217
+ private end;
218
+ /** The rules in effect at `now`: the repository's first, then the run-time ones oldest first. */
219
+ active(now: number): ExpectedFailureRule[];
220
+ get(id: string): ExpectedFailureRule | undefined;
221
+ isActive(id: string, now: number): boolean;
222
+ get size(): number;
223
+ /** The first rule in effect that holds this failure. */
224
+ holderOf(f: FailureFacts, now: number): ExpectedFailureRule | undefined;
225
+ /** Count `n` occurrences held by a rule, at `at` (undefined: their times are not known, the total only). */
226
+ count(id: string, at: number | undefined, n?: number): void;
227
+ /** Occurrences in the minutes that start in [from, to). */
228
+ private windowCount;
229
+ /** Re-judge a rule's rate: a surge starts at 10× its usual hourly rate (and 20 at least), ends below a third of that. */
230
+ private judge;
231
+ /** The rules in effect, each with what it has held — newest first, the repository's last. */
232
+ list(now: number): ExpectedRuleView[];
233
+ /** The rules that ended lately, newest first. */
234
+ endedRules(): EndedExpectedRule[];
235
+ }
236
+ /** «2 rules held back 61 occurrences in the last hour» — what every list and status that held something back says. */
237
+ export declare function heldBackLine(rules: number, occurrences: number, window?: string): string;
238
+ /** «this expected failure is now happening much more often» — said once per surge. */
239
+ export declare function surgeLine(r: Pick<ExpectedRuleView, 'match' | 'reason' | 'surge'>): string;
240
+ /** `POST /api/errors/expect` — a rule from a row («always expect this here»), or a match written out. */
241
+ export interface DashExpectBody {
242
+ groupId?: string;
243
+ causeId?: string;
244
+ match?: ExpectedFailureMatch;
245
+ reason: string;
246
+ hours?: number;
247
+ }
248
+ /** `POST /api/errors/unexpect` — the run-time rules to remove, by id. */
249
+ export interface DashUnexpectBody {
250
+ ids: string[];
251
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";var z=Object.defineProperty;var h=(t,e)=>z(t,"name",{value:e,configurable:!0});var K=Object.defineProperty,c=h((t,e)=>K(t,"name",{value:e,configurable:!0}),"d");import{LENS_EVENT_SOURCE as W}from"./error-dismissal.js";export const EXPECTED_RULE_SET="expected-rule-set",EXPECTED_RULE_REMOVED="expected-rule-removed";const k=new Set(["dashboard","cli","agent"]),m=60*6e4;export const EXPECTED_RULE_DEFAULT_TTL_MS=168*m,EXPECTED_RULE_MAX_TTL_MS=720*m,EXPECTED_RULE_MIN_REASON_CHARS=8,MAX_EXPECTED_REASON_CHARS=500;const A=300,G=300,P=120,J=200,H=20,l=c(t=>!!t&&typeof t=="object"&&!Array.isArray(t),"isObj"),g=c((t,e)=>typeof t=="string"&&t.trim()?t.trim().slice(0,e):void 0,"text"),R=c(t=>!!t&&t.replace(/[*?\s/:.#_-]/g,"").length>=2,"meaningful");export const EXPECTED_SCOPE_FIELDS=["route","span","flow"],EXPECTED_OUTCOME_FIELDS=["status","error","message"];export function checkExpectedMatch(t){if(!l(t))return{error:"a rule needs a match: a flow scope (route, span or flow) and an outcome (status, error or message)"};const e={};for(const r of["service","route","span","flow","error","message"]){const o=t[r];if(o==null||o==="")continue;if(typeof o!="string")return{error:`\`${r}\` must be text`};const i=o.trim();if(i.length>A)return{error:`\`${r}\` is longer than ${A} characters`};i&&(e[r]=i)}if(t.status!==void 0&&t.status!==null&&t.status!==""){const r=typeof t.status=="string"?Number(t.status):t.status;if(typeof r!="number"||!Number.isInteger(r)||r<100||r>599)return{error:"`status` must be an HTTP status (100\u2013599)"};e.status=r}const s=t.attribute;if(s!=null){const r=l(s)?g(s.name,100):void 0,o=l(s)?typeof s.value=="number"?String(s.value):g(s.value,A):void 0;if(!r||!o)return{error:"`attribute` needs a `name` and a `value` (one attribute of the flow, such as a tenant id)"};e.attribute={name:r,value:o}}return EXPECTED_SCOPE_FIELDS.some(r=>R(e[r]))?e.status===void 0&&!R(e.error)&&!R(e.message)?{error:"a rule needs an outcome \u2014 a `status`, an `error` key or a `message` pattern \u2014 saying WHICH failure is expected in that flow"}:{match:e}:{error:`a rule needs a flow scope \u2014 a \`route\`, a \`span\` or a \`flow\` \u2014 not only ${e.service?`the service \xAB${e.service}\xBB`:"an outcome"}: \xABeverything in a service\xBB is not expected, it is unwatched`}}h(checkExpectedMatch,"checkExpectedMatch"),c(checkExpectedMatch,"checkExpectedMatch");export function describeExpectedMatch(t){return[t.service,t.route,t.span,t.flow?`flow ${t.flow}`:void 0,t.status!==void 0?String(t.status):void 0,t.error,t.message?`\xAB${t.message}\xBB`:void 0,t.attribute?`${t.attribute.name}=${t.attribute.value}`:void 0].filter(Boolean).join(" \xB7 ")}h(describeExpectedMatch,"describeExpectedMatch"),c(describeExpectedMatch,"describeExpectedMatch");export function readExpectedRule(t){if(t.source!==W||!l(t.raw))return;const e=t.raw,s=g(e.id,P);if(!s)return;if(e.kind===EXPECTED_RULE_REMOVED)return{kind:EXPECTED_RULE_REMOVED,id:s,...k.has(e.by)?{by:e.by}:{}};if(e.kind!==EXPECTED_RULE_SET||!k.has(e.by))return;const r=g(e.reason,MAX_EXPECTED_REASON_CHARS);if(!r)return;const o=checkExpectedMatch(e.match);if("error"in o)return;const i=Math.min(typeof e.createdAt=="number"&&Number.isFinite(e.createdAt)?e.createdAt:t.timestamp,t.timestamp),u=typeof e.expiresAt=="number"&&Number.isFinite(e.expiresAt)?e.expiresAt:i+EXPECTED_RULE_DEFAULT_TTL_MS,a=g(e.title,G);return{kind:EXPECTED_RULE_SET,id:s,match:o.match,reason:r,by:e.by,createdAt:i,expiresAt:Math.min(u,i+EXPECTED_RULE_MAX_TTL_MS),...a?{title:a}:{}}}h(readExpectedRule,"readExpectedRule"),c(readExpectedRule,"readExpectedRule");export function expectedRuleTtlMs(t){return t===void 0||!Number.isFinite(t)||t<=0?EXPECTED_RULE_DEFAULT_TTL_MS:Math.min(Math.round(t*m),EXPECTED_RULE_MAX_TTL_MS)}h(expectedRuleTtlMs,"expectedRuleTtlMs"),c(expectedRuleTtlMs,"expectedRuleTtlMs");function F(t){let e=2166136261;for(let s=0;s<t.length;s++)e=Math.imul(e^t.charCodeAt(s),16777619);return(e>>>0).toString(36)}h(F,"z"),c(F,"hashOf");export function readRepositoryExpectedRules(t,e){const s=[],r=[];return t==null?{rules:s,problems:r}:Array.isArray(t)?(t.forEach((o,i)=>{if(!l(o))return void r.push(`expectedFailures[${i}] is not an object`);const u=checkExpectedMatch(l(o.match)?o.match:o);if("error"in u)return void r.push(`expectedFailures[${i}]: ${u.error}`);const a=g(o.reason,MAX_EXPECTED_REASON_CHARS);if(!a)return void r.push(`expectedFailures[${i}] has no reason \u2014 say why it is expected`);const d=`repository:${g(o.id,P)??F(JSON.stringify(u.match))}`;if(s.some(p=>p.id===d))return void r.push(`expectedFailures[${i}] repeats the id ${d}`);s.push({id:d,match:u.match,reason:a,by:"repository",createdAt:e})}),{rules:s,problems:r}):{rules:s,problems:["expectedFailures is not a list \u2014 no repository rule is read"]}}h(readRepositoryExpectedRules,"readRepositoryExpectedRules"),c(readRepositoryExpectedRules,"readRepositoryExpectedRules");const n=c(t=>typeof t=="string"&&t?t:void 0,"str"),$=c(t=>typeof t=="number"&&Number.isFinite(t)?t:void 0,"num"),B=c(t=>{const e=t.split(/[?#]/)[0]??t,s=/^[a-z][a-z0-9+.-]*:\/\/[^/]+(\/.*)?$/i.exec(e);return s?s[1]??"/":e},"pathOf"),V=new Set(["sessionId","flowId","requestId","parentRequestId","runId","traceparent","originNodeId","causedByNodeId","userActionId","browserContextId","frameId","tabId","url","route","projectName"]),_=24;export function eventAttributes(t){let e;const s=c((a,d)=>{if(e&&Object.keys(e).length>=_)return;const p=typeof d=="string"?d:typeof d=="number"||typeof d=="boolean"?String(d):void 0;p===void 0||p.length>A||((e??={})[a]=p)},"put"),r=t.context??{};for(const a of Object.keys(r))V.has(a)||s(a,r[a]);const o=l(t.raw)?t.raw:void 0;if(!o)return e;const i=l(o.span)?o.span:void 0,u=l(o.request)?o.request:void 0;for(const a of[o.attributes,i?.attributes,u?.attributes,o.data,Array.isArray(i?.args)?i?.args[0]:i?.args])if(l(a))for(const d of Object.keys(a))s(d,a[d]);return e}h(eventAttributes,"eventAttributes"),c(eventAttributes,"eventAttributes");export function failureFacts(t){const e=l(t.raw)?t.raw:{},s=t.context??{},r=l(e.request)?e.request:{},o=l(e.span)?e.span:{},i=l(r.error)?r.error:{},u=l(o.error)?o.error:{},a=l(e.error)?e.error:{},d=n(e.kind),p=[],b=n(r.route)??(d==="egress"?n(e.path):void 0);b&&p.push(b);const y=n(e.url)??n(r.url);y&&p.push(B(y)),d!=="server-request"&&n(s.route)&&p.push(n(s.route));const f=[];if(d==="queue-failed"||d==="queue-enqueued"){const w=n(e.queue),E=e.jobId===void 0||e.jobId===null?void 0:String(e.jobId);w&&f.push(`job:${w}`),E&&f.push(`job:${E}`),w&&E&&f.push(`job:${w}#${E}`),n(e.name)&&f.push(`job:${n(e.name)}`)}const x=[i.errorKey,u.errorKey,a.errorKey,e.errorKey,i.reason,u.reason].map(n).filter(w=>!!w),S=n(i.message)??n(t.message)??n(u.message)??n(a.message)??n(e.failedReason)??n(e.error)??n(e.message)??n(t.title),C=$(r.status)??$(e.status),T=n(s.flowId)??n(o.flowId)??n(r.flowId),N=n(s.requestId)??n(r.requestId)??n(o.requestId),O=eventAttributes(t);return{...n(e.project)??n(s.projectName)?{service:n(e.project)??n(s.projectName)}:{},...n(r.method)??n(e.method)?{method:n(r.method)??n(e.method)}:{},...p.length?{routes:p}:{},...n(o.name)?{span:n(o.name)}:{},...T?{flowId:T}:{},...f.length?{flowNames:f}:{},...C!==void 0?{status:C}:{},...n(i.name)??n(u.name)??n(a.name)?{errorName:n(i.name)??n(u.name)??n(a.name)}:{},...x.length?{errorKeys:x}:{},...S?{message:S}:{},...O?{attributes:O}:{},...N?{requestId:N}:{}}}h(failureFacts,"failureFacts"),c(failureFacts,"failureFacts");export class FailureContextIndex{static{h(this,"FailureContextIndex")}static{c(this,"FailureContextIndex")}constructor(e=5e3,s=2e3){this.maxRequests=e,this.maxFlows=s,this.requests=new Map,this.flows=new Map}observe(e){const s=l(e.raw)?e.raw:void 0,r=e.context??{},o=n(r.flowId);if(o&&(s?.attributes!==void 0||l(s?.span)||r.tenantIdHash!==void 0||r.userIdHash!==void 0||s?.data!==void 0)){const y=eventAttributes(e);if(y){const f=this.flows.get(o);this.flows.delete(o);const x={...f??{},...y};this.flows.set(o,Object.keys(x).length>_?Object.fromEntries(Object.entries(x).slice(-_)):x),this.flows.size>this.maxFlows&&this.flows.delete(this.flows.keys().next().value)}}const i=n(s?.kind);if(!s||i!=="server-request"&&i!=="gateway-request")return;const u=l(s.request)?s.request:s,a=n(r.requestId)??n(u.requestId);if(!a)return;const d=this.requests.get(a)??{},p=n(u.url),b={...d,...n(s.project)&&(i==="server-request"||!d.service)?{service:n(s.project)}:{},...n(u.method)?{method:n(u.method)}:{},...i==="server-request"&&n(u.route)?{route:n(u.route)}:{},...p?{path:B(p)}:{},...$(u.status)!==void 0&&(i==="server-request"||d.status===void 0)?{status:$(u.status)}:{}};return this.requests.delete(a),this.requests.set(a,b),this.requests.size>this.maxRequests&&this.requests.delete(this.requests.keys().next().value),i==="server-request"?a:void 0}request(e){return e?this.requests.get(e):void 0}enrich(e){const s=this.request(e.requestId),r=e.flowId?this.flows.get(e.flowId):void 0;if(!s&&!r)return e;const o=[...e.routes??[],...s?.route?[s.route]:[],...s?.path?[s.path]:[]];return{...e,...e.service??s?.service?{service:e.service??s?.service}:{},...e.method??s?.method?{method:e.method??s?.method}:{},...o.length?{routes:[...new Set(o)]}:{},...e.status??s?.status!==void 0?{status:e.status??s?.status}:{},...r||e.attributes?{attributes:{...r??{},...e.attributes??{}}}:{}}}}const I=new Map,j=c((t,e)=>t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,e).replace(/\?/g,"."),"globBody");function M(t,e="whole"){const s=`${e}\0${t}`;let r=I.get(s);return r||(r=e==="whole"?new RegExp(`^${j(t,"[\\s\\S]*")}$`,"i"):e==="anywhere"?new RegExp(j(t,"[\\s\\S]*"),"i"):new RegExp(`(?:^|[^\\w.])${j(t,"[\\w.]*")}(?:$|[^\\w.])`,"i"),I.size>1e3&&I.clear(),I.set(s,r)),r}h(M,"S"),c(M,"globRe");const v=c((t,e)=>e!==void 0&&M(t).test(e),"glob");function D(t,e){const s=e.routes??[],r=/^([A-Za-z]+)\s+(\S.*)$/.exec(t);return r&&/^(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS|\*)$/i.test(r[1])?r[1]!=="*"&&(e.method??"").toUpperCase()!==r[1].toUpperCase()?!1:s.some(o=>v(r[2],o)):s.some(o=>v(t,o))}h(D,"B"),c(D,"routeMatches");function L(t,e){const s=[e.flowId,...e.flowNames??[]].filter(o=>!!o),r=t.endsWith(":")?`${t}*`:t;return s.some(o=>v(r,o))}h(L,"G"),c(L,"flowMatches");function U(t,e){return v(t,e.errorName)||(e.errorKeys??[]).some(s=>v(t,s))?!0:e.message!==void 0&&M(t,"word").test(e.message)}h(U,"W"),c(U,"errorMatches");export function expectedMatches(t,e){return!(t.service!==void 0&&!v(t.service,e.service)||t.route!==void 0&&!D(t.route,e)||t.span!==void 0&&!v(t.span,e.span)||t.flow!==void 0&&!L(t.flow,e)||t.status!==void 0&&e.status!==t.status||t.error!==void 0&&!U(t.error,e)||t.message!==void 0&&!(e.message!==void 0&&M(t.message,"anywhere").test(e.message))||t.attribute!==void 0&&!v(t.attribute.value,e.attributes?.[t.attribute.name]))}h(expectedMatches,"expectedMatches"),c(expectedMatches,"expectedMatches");export function expectedMatchIsPerOccurrence(t){return t.flow!==void 0||t.attribute!==void 0||t.message!==void 0&&/\d/.test(t.message)}h(expectedMatchIsPerOccurrence,"expectedMatchIsPerOccurrence"),c(expectedMatchIsPerOccurrence,"expectedMatchIsPerOccurrence");export function suggestExpectedMatch(t){const e=t.routes?.find(a=>a.startsWith("/")),s=t.flowNames?.find(a=>a.startsWith("job:")&&!a.includes("#"))??(t.flowId?`${t.flowId.split(":")[0]}:`:void 0),r=e?{route:t.method?`${t.method.toUpperCase()} ${e}`:e}:t.span?{span:t.span}:s?{flow:s}:{},o=t.message?.split(`
2
+ `)[0]?.replace(/\d+/g,"*").replace(/\*+/g,"*").slice(0,120).trim(),i=t.status!==void 0?{status:t.status}:t.errorName&&t.errorName!=="Error"?{error:t.errorName}:o?{message:o}:{},u=checkExpectedMatch({...t.service?{service:t.service}:{},...r,...i});return"match"in u?u.match:void 0}h(suggestExpectedMatch,"suggestExpectedMatch"),c(suggestExpectedMatch,"suggestExpectedMatch");export const EXPECTED_SURGE_FACTOR=10,EXPECTED_SURGE_MIN_PER_HOUR=20;const Z=2*m,X=24*m,q=6e4;export class ExpectedRuleBook{static{h(this,"ExpectedRuleBook")}static{c(this,"ExpectedRuleBook")}constructor(e=Date.now()){this.startedAt=e,this.runtime=new Map,this.repository=[],this.repositoryKey="",this.stats=new Map,this.ended=[],this.version=0}apply(e,s){const r=readExpectedRule(e);if(!r)return!1;const o=this.runtime.get(r.id);if(this.runtime.delete(r.id),r.kind===EXPECTED_RULE_REMOVED)o&&this.end(o,s,"removed",r.by);else{const{kind:i,...u}=r;if(this.runtime.set(u.id,u),this.stats.has(u.id)||this.stats.set(u.id,{hits:0,minutes:new Map,since:Math.max(u.createdAt,this.startedAt)}),this.runtime.size>J){const a=this.runtime.keys().next().value,d=this.runtime.get(a);this.runtime.delete(a),this.end(d,s,"expired")}}return this.version++,!0}setRepository(e,s){const r=JSON.stringify(e.map(i=>[i.id,i.match,i.reason]));if(r===this.repositoryKey)return!1;const o=new Set(e.map(i=>i.id));for(const i of this.repository)o.has(i.id)||this.end(i,s,"dropped from lensmcp.json");this.repository=e.slice(),this.repositoryKey=r;for(const i of e)this.stats.has(i.id)||this.stats.set(i.id,{hits:0,minutes:new Map,since:Math.max(this.startedAt,Math.min(i.createdAt,s))});return this.version++,!0}expire(e){let s=!1;for(const[r,o]of this.runtime)o.expiresAt===void 0||o.expiresAt>e||(this.runtime.delete(r),this.end(o,o.expiresAt,"expired"),s=!0);return s&&this.version++,s}end(e,s,r,o){this.ended.unshift({...e,endedAt:s,why:r,...o?{removedBy:o}:{}}),this.ended.length>H&&(this.ended.length=H)}active(e){return[...this.repository,...[...this.runtime.values()].filter(s=>s.expiresAt===void 0||s.expiresAt>e)]}get(e){return this.runtime.get(e)??this.repository.find(s=>s.id===e)}isActive(e,s){const r=this.get(e);return!!r&&(r.expiresAt===void 0||r.expiresAt>s)}get size(){return this.runtime.size+this.repository.length}holderOf(e,s){if(this.size!==0)return this.active(s).find(r=>expectedMatches(r.match,e))}count(e,s,r=1){const o=this.stats.get(e);if(!o||r<=0||(o.hits+=r,s===void 0))return;o.lastHitAt=Math.max(o.lastHitAt??0,s);const i=Math.floor(s/q);if(o.minutes.set(i,(o.minutes.get(i)??0)+r),o.minutes.size>1600){const u=i-(X+m)/q;for(const a of o.minutes.keys())a<u&&o.minutes.delete(a)}}windowCount(e,s,r){let o=0;for(const[i,u]of e.minutes)i*q>=s&&i*q<r&&(o+=u);return o}judge(e,s){const r=this.windowCount(e,s-m,s+1),o=Math.max(e.since,s-m-X),i=s-m-o;if(i<Z)return e.surge=void 0;const u=this.windowCount(e,o,s-m)/(i/m),a=Math.max(EXPECTED_SURGE_MIN_PER_HOUR,EXPECTED_SURGE_FACTOR*u);return e.surge?r<a/3?e.surge=void 0:e.surge={...e.surge,lastHour:r}:r>=a&&(e.surge={since:s,lastHour:r,usualPerHour:Math.round(u*10)/10}),e.surge}list(e){return this.active(e).map(s=>{const r=this.stats.get(s.id),o=r?this.judge(r,e):void 0;return{...s,hits:r?.hits??0,...r?.lastHitAt!==void 0?{lastHitAt:r.lastHitAt}:{},lastHour:r?this.windowCount(r,e-m,e+1):0,...o?{surge:o}:{}}}).sort((s,r)=>+(s.by==="repository")-+(r.by==="repository")||r.createdAt-s.createdAt)}endedRules(){return this.ended.slice()}}export function heldBackLine(t,e,s=""){return`${t} rule${t===1?"":"s"} held back ${e} occurrence${e===1?"":"s"}${s?` ${s}`:""}`}h(heldBackLine,"heldBackLine"),c(heldBackLine,"heldBackLine");export function surgeLine(t){const e=t.surge;return`this expected failure is now happening much more often: ${describeExpectedMatch(t.match)} \u2014 ${e?`${e.lastHour} in the last hour, usually ${e.usualPerHour} an hour`:"its rate jumped"} (expected because: ${t.reason})`}h(surgeLine,"surgeLine"),c(surgeLine,"surgeLine");
@@ -1 +1 @@
1
- "use strict";var S=Object.defineProperty;var i=(t,s)=>S(t,"name",{value:s,configurable:!0});var A=Object.defineProperty,f=i((t,s)=>A(t,"name",{value:s,configurable:!0}),"i"),k=Object.defineProperty,u=f((t,s)=>k(t,"name",{value:s,configurable:!0}),"o");function l(){const t=typeof process<"u"?process.env?.LENSMCP_EVENT_MAX_EPS:void 0;if(t===void 0||t==="")return;if(t==="off")return"off";const s=Number(t);if(Number.isFinite(s))return s<=0?"off":s}i(l,"d"),f(l,"S"),u(l,"envPerSec");export function createEventFloodGuard(t){const s=t?.envOverride===!1?void 0:l();if(s==="off")return{admit:u(()=>({ok:!0,suppressed:0}),"admit")};const c=s??t?.perSec??5,d=Math.max(1,t?.burst??Math.max(30,c*4)),p=t?.maxKeys??2048,n=new Map,v=u(o=>{for(const[r,e]of n)o-e.lastSeenAt>6e4&&n.delete(r);if(n.size>p){const r=[...n.entries()].sort((e,a)=>e[1].lastSeenAt-a[1].lastSeenAt);for(let e=0;e<r.length>>1;e++)n.delete(r[e][0])}},"evictStale");return{admit(o){const r=Date.now();let e=n.get(o);e||(n.size>=p&&v(r),e={tokens:d,lastRefillAt:r,suppressed:0,lastSeenAt:r},n.set(o,e)),e.lastSeenAt=r;const a=r-e.lastRefillAt;if(a>0&&(e.tokens=Math.min(d,e.tokens+a/1e3*c),e.lastRefillAt=r),e.tokens>=1){e.tokens-=1;const m=e.suppressed;return e.suppressed=0,{ok:!0,suppressed:m}}return e.suppressed+=1,{ok:!1,suppressed:0}}}}i(createEventFloodGuard,"createEventFloodGuard"),f(createEventFloodGuard,"createEventFloodGuard"),u(createEventFloodGuard,"createEventFloodGuard");
1
+ "use strict";var S=Object.defineProperty;var i=(t,n)=>S(t,"name",{value:n,configurable:!0});var m=Object.defineProperty,u=i((t,n)=>m(t,"name",{value:n,configurable:!0}),"o");function d(){const t=typeof process<"u"?process.env?.LENSMCP_EVENT_MAX_EPS:void 0;if(t===void 0||t==="")return;if(t==="off")return"off";const n=Number(t);if(Number.isFinite(n))return n<=0?"off":n}i(d,"S"),u(d,"envPerSec");export function createEventFloodGuard(t){const n=t?.envOverride===!1?void 0:d();if(n==="off")return{admit:u(()=>({ok:!0,suppressed:0}),"admit")};const l=n??t?.perSec??5,f=Math.max(1,t?.burst??Math.max(30,l*4)),c=t?.maxKeys??2048,r=new Map,p=u(o=>{for(const[s,e]of r)o-e.lastSeenAt>6e4&&r.delete(s);if(r.size>c){const s=[...r.entries()].sort((e,a)=>e[1].lastSeenAt-a[1].lastSeenAt);for(let e=0;e<s.length>>1;e++)r.delete(s[e][0])}},"evictStale");return{admit(o){const s=Date.now();let e=r.get(o);e||(r.size>=c&&p(s),e={tokens:f,lastRefillAt:s,suppressed:0,lastSeenAt:s},r.set(o,e)),e.lastSeenAt=s;const a=s-e.lastRefillAt;if(a>0&&(e.tokens=Math.min(f,e.tokens+a/1e3*l),e.lastRefillAt=s),e.tokens>=1){e.tokens-=1;const v=e.suppressed;return e.suppressed=0,{ok:!0,suppressed:v}}return e.suppressed+=1,{ok:!1,suppressed:0}}}}i(createEventFloodGuard,"createEventFloodGuard"),u(createEventFloodGuard,"createEventFloodGuard");
@@ -1 +1 @@
1
- "use strict";var o=Object.defineProperty;var t=(n,e)=>o(n,"name",{value:e,configurable:!0});var s=Object.defineProperty,a=t((n,e)=>s(n,"name",{value:e,configurable:!0}),"a"),l=Object.defineProperty,i=a((n,e)=>l(n,"name",{value:e,configurable:!0}),"a");export const DESIGN_TYPES=["bug","investigation","performance","reliability","feature","architecture","maintenance"],DESIGN_CONCERNS=["security","data","api","ui","integration","operations"],DESIGN_TYPE_INFO={bug:{label:"Bug",when:"Something works wrong, and the cause is known or can be found by reading the code."},investigation:{label:"Investigation",when:"Symptoms without a known cause: research first, and the goal ends in a decision or a fix."},performance:{label:"Performance",when:"Something is measurably slow, heavy or costly: a baseline the lens measured and a target."},reliability:{label:"Reliability",when:"Crashes, stalls, flaky tests, lost work, CI or the machine: how it fails and how often."},feature:{label:"Feature",when:"Someone can do something they cannot do now."},architecture:{label:"Architecture",when:"Boundaries, contracts or structure change, in steps that each ship."},maintenance:{label:"Maintenance",when:"Upgrades, moves, tooling and cleanup: no new behaviour, and nothing breaks."}},DESIGN_CONCERN_INFO={security:{label:"Security",when:"Auth, permissions, secrets, input from outside, or anything an attacker would read."},data:{label:"Data",when:"Schema, migrations, backfills, or data already stored."},api:{label:"API",when:"A request or response other code or other people depend on."},ui:{label:"UI",when:"Screens, flows or what a person sees."},integration:{label:"Integration",when:"A service outside the repository: its API, keys, limits and failures."},operations:{label:"Operations",when:"How it deploys, runs, is watched and is rolled back."}},DESIGN_STAGES=["proposed","requested","drafting","waiting","changes","approved","declined"];export function designWriter(n){if(n.writer)return n.writer;if(n.by==="user")return{kind:"person"};if(n.by==="lensmcp")return{kind:"lensmcp",...n.byName?{name:n.byName}:{}}}t(designWriter,"designWriter"),a(designWriter,"designWriter"),i(designWriter,"designWriter");const c={claude:"Claude Code",codex:"Codex"};export function designWriterText(n){const e=designWriter(n);if(!e)return"who handed it in was not recorded";const r=e.client?c[e.client]:void 0;switch(e.kind){case"person":return"written by the person";case"lensmcp":return"written by LensMCP's own run";case"terminal":return"handed in from a terminal, as the overseer";case"session":return`handed in by ${r?`a ${r}`:"an agent's"} session${e.role?`, the team's ${e.role}`:" with no role on this team"}`;case"launch":return e.purpose==="design"?`written by a design launch${r?` on ${r}`:""}`:`handed in by the overseer's ${e.purpose==="inbox"?"inbox launch":e.purpose==="round"?"round":"launch"}${r?` on ${r}`:""}`}}t(designWriterText,"designWriterText"),a(designWriterText,"designWriterText"),i(designWriterText,"designWriterText");
1
+ "use strict";var i=Object.defineProperty;var a=(n,e)=>i(n,"name",{value:e,configurable:!0});var o=Object.defineProperty,r=a((n,e)=>o(n,"name",{value:e,configurable:!0}),"a");export const DESIGN_TYPES=["bug","investigation","performance","reliability","feature","architecture","maintenance"],DESIGN_CONCERNS=["security","data","api","ui","integration","operations"],DESIGN_TYPE_INFO={bug:{label:"Bug",when:"Something works wrong, and the cause is known or can be found by reading the code."},investigation:{label:"Investigation",when:"Symptoms without a known cause: research first, and the goal ends in a decision or a fix."},performance:{label:"Performance",when:"Something is measurably slow, heavy or costly: a baseline the lens measured and a target."},reliability:{label:"Reliability",when:"Crashes, stalls, flaky tests, lost work, CI or the machine: how it fails and how often."},feature:{label:"Feature",when:"Someone can do something they cannot do now."},architecture:{label:"Architecture",when:"Boundaries, contracts or structure change, in steps that each ship."},maintenance:{label:"Maintenance",when:"Upgrades, moves, tooling and cleanup: no new behaviour, and nothing breaks."}},DESIGN_CONCERN_INFO={security:{label:"Security",when:"Auth, permissions, secrets, input from outside, or anything an attacker would read."},data:{label:"Data",when:"Schema, migrations, backfills, or data already stored."},api:{label:"API",when:"A request or response other code or other people depend on."},ui:{label:"UI",when:"Screens, flows or what a person sees."},integration:{label:"Integration",when:"A service outside the repository: its API, keys, limits and failures."},operations:{label:"Operations",when:"How it deploys, runs, is watched and is rolled back."}},DESIGN_STAGES=["proposed","requested","drafting","waiting","changes","approved","declined"];export function designWriter(n){if(n.writer)return n.writer;if(n.by==="user")return{kind:"person"};if(n.by==="lensmcp")return{kind:"lensmcp",...n.byName?{name:n.byName}:{}}}a(designWriter,"designWriter"),r(designWriter,"designWriter");const s={claude:"Claude Code",codex:"Codex"};export function designWriterText(n){const e=designWriter(n);if(!e)return"who handed it in was not recorded";const t=e.client?s[e.client]:void 0;switch(e.kind){case"person":return"written by the person";case"lensmcp":return"written by LensMCP's own run";case"terminal":return"handed in from a terminal, as the overseer";case"session":return`handed in by ${t?`a ${t}`:"an agent's"} session${e.role?`, the team's ${e.role}`:" with no role on this team"}`;case"launch":return e.purpose==="design"?`written by a design launch${t?` on ${t}`:""}`:`handed in by the overseer's ${e.purpose==="inbox"?"inbox launch":e.purpose==="round"?"round":"launch"}${t?` on ${t}`:""}`}}a(designWriterText,"designWriterText"),r(designWriterText,"designWriterText");
@@ -1 +1 @@
1
- "use strict";var C=Object.defineProperty;var p=(e,r)=>C(e,"name",{value:r,configurable:!0});var k=Object.defineProperty,h=p((e,r)=>k(e,"name",{value:r,configurable:!0}),"g"),A=Object.defineProperty,d=h((e,r)=>A(e,"name",{value:r,configurable:!0}),"i");import{TRUNCATION_MARKER_KEY as j}from"./bounded-clone.js";export const LINT_COVER_KIND="lint-cover",MAX_LINT_UNCOMMITTED=500;const L=["tree","paths","changed","incremental"],m=d(e=>Array.isArray(e)?e.filter(r=>typeof r=="string"&&r.length>0):[],"strings"),i=d(e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):void 0,"count"),l=d(e=>typeof e=="string"&&e?e:void 0,"text");export function readLintCoverage(e){if(!e||typeof e!="object"||e[j])return;const r=e.coverage;if(!r||typeof r!="object")return;const t=r,n=t.kind,a=t.root;if(!L.includes(n)||typeof a!="string"||!a)return;const u=m(t.dirs),o=m(t.files),g=m(t.gone),$=i(t.notLinted),y=i(t.untracked),s=t.base&&typeof t.base=="object"?t.base:void 0,v=s&&l(s.sha)&&l(s.run)?{from:s.from==="main"?"main":"own",sha:s.sha,run:s.run}:void 0,b=Array.isArray(t.inputs)?t.inputs.flatMap(f=>Array.isArray(f)&&typeof f[0]=="string"&&typeof f[1]=="string"?[[f[0],f[1]]]:[]):void 0;return{kind:n,root:a,dirs:u,files:o,gone:g,fileCount:i(t.fileCount)??o.length,goneCount:i(t.goneCount)??g.length,linted:i(t.linted)??0,...i(t.dirCount)!==void 0?{dirCount:i(t.dirCount)}:{},...$?{notLinted:$}:{},...y?{untracked:y}:{},...l(t.since)?{since:t.since}:{},...l(t.head)?{head:t.head}:{},...typeof t.dirty=="boolean"?{dirty:t.dirty}:{},...Array.isArray(t.uncommitted)?{uncommitted:m(t.uncommitted)}:{},...t.uncommittedMore===!0?{uncommittedMore:!0}:{},...b?{inputs:b}:{},...l(t.folder)?{folder:t.folder}:{},...t.projects===!0?{projects:!0}:{},...v?{base:v}:{},...t.fromZero===!0?{fromZero:!0}:{},...t.narrowed===!0?{narrowed:!0}:{}}}p(readLintCoverage,"readLintCoverage"),h(readLintCoverage,"readLintCoverage"),d(readLintCoverage,"readLintCoverage");const c=d((e,r)=>`${e} ${r}${e===1?"":"s"}`,"some");export function lintCoverageLabel(e,r={}){const t=e.files??0,n=e.gone??0;if(e.kind==="changed"){const o=`since ${e.since??"HEAD"}`;if(!t)return`${c(n,"deleted file")} ${o}`;const g=r.untracked&&e.untracked?` (${e.untracked} untracked)`:"";return`${c(t,"changed file")} ${o}${g}${n?`, ${n} deleted`:""}`}if(e.kind==="incremental"){const o=e.since?` since ${e.since.slice(0,7)}`:"";return!t&&!n?`nothing changed${o}`:t?`${c(t,"file")} changed${o}${n?`, ${n} deleted`:""}`:`${c(n,"file")} deleted${o}`}if(e.kind==="tree"&&e.projects)return`the workspace\u2019s ${c(e.projects,"project")}`;if(e.kind==="tree"&&e.paths[0]===".")return"whole checkout";if(e.narrowed)return`${c(t,"file")} ESLint linted with the caller\u2019s arguments`;const a=e.paths.slice(0,3).join(", "),u=(e.more??0)+Math.max(0,e.paths.length-3);return u?`${a} +${u} more`:a}p(lintCoverageLabel,"lintCoverageLabel"),h(lintCoverageLabel,"lintCoverageLabel"),d(lintCoverageLabel,"lintCoverageLabel");
1
+ "use strict";var k=Object.defineProperty;var g=(e,n)=>k(e,"name",{value:n,configurable:!0});var v=Object.defineProperty,d=g((e,n)=>v(e,"name",{value:n,configurable:!0}),"i");import{TRUNCATION_MARKER_KEY as C}from"./bounded-clone.js";export const LINT_COVER_KIND="lint-cover",MAX_LINT_UNCOMMITTED=500;const A=["tree","paths","changed","incremental"],h=d(e=>Array.isArray(e)?e.filter(n=>typeof n=="string"&&n.length>0):[],"strings"),i=d(e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):void 0,"count"),l=d(e=>typeof e=="string"&&e?e:void 0,"text");export function readLintCoverage(e){if(!e||typeof e!="object"||e[C])return;const n=e.coverage;if(!n||typeof n!="object")return;const t=n,r=t.kind,s=t.root;if(!A.includes(r)||typeof s!="string"||!s)return;const f=h(t.dirs),o=h(t.files),p=h(t.gone),m=i(t.notLinted),$=i(t.untracked),a=t.base&&typeof t.base=="object"?t.base:void 0,y=a&&l(a.sha)&&l(a.run)?{from:a.from==="main"?"main":"own",sha:a.sha,run:a.run}:void 0,b=Array.isArray(t.inputs)?t.inputs.flatMap(u=>Array.isArray(u)&&typeof u[0]=="string"&&typeof u[1]=="string"?[[u[0],u[1]]]:[]):void 0;return{kind:r,root:s,dirs:f,files:o,gone:p,fileCount:i(t.fileCount)??o.length,goneCount:i(t.goneCount)??p.length,linted:i(t.linted)??0,...i(t.dirCount)!==void 0?{dirCount:i(t.dirCount)}:{},...m?{notLinted:m}:{},...$?{untracked:$}:{},...l(t.since)?{since:t.since}:{},...l(t.head)?{head:t.head}:{},...typeof t.dirty=="boolean"?{dirty:t.dirty}:{},...Array.isArray(t.uncommitted)?{uncommitted:h(t.uncommitted)}:{},...t.uncommittedMore===!0?{uncommittedMore:!0}:{},...b?{inputs:b}:{},...l(t.folder)?{folder:t.folder}:{},...t.projects===!0?{projects:!0}:{},...y?{base:y}:{},...t.fromZero===!0?{fromZero:!0}:{},...t.narrowed===!0?{narrowed:!0}:{}}}g(readLintCoverage,"readLintCoverage"),d(readLintCoverage,"readLintCoverage");const c=d((e,n)=>`${e} ${n}${e===1?"":"s"}`,"some");export function lintCoverageLabel(e,n={}){const t=e.files??0,r=e.gone??0;if(e.kind==="changed"){const o=`since ${e.since??"HEAD"}`;if(!t)return`${c(r,"deleted file")} ${o}`;const p=n.untracked&&e.untracked?` (${e.untracked} untracked)`:"";return`${c(t,"changed file")} ${o}${p}${r?`, ${r} deleted`:""}`}if(e.kind==="incremental"){const o=e.since?` since ${e.since.slice(0,7)}`:"";return!t&&!r?`nothing changed${o}`:t?`${c(t,"file")} changed${o}${r?`, ${r} deleted`:""}`:`${c(r,"file")} deleted${o}`}if(e.kind==="tree"&&e.projects)return`the workspace\u2019s ${c(e.projects,"project")}`;if(e.kind==="tree"&&e.paths[0]===".")return"whole checkout";if(e.narrowed)return`${c(t,"file")} ESLint linted with the caller\u2019s arguments`;const s=e.paths.slice(0,3).join(", "),f=(e.more??0)+Math.max(0,e.paths.length-3);return f?`${s} +${f} more`:s}g(lintCoverageLabel,"lintCoverageLabel"),d(lintCoverageLabel,"lintCoverageLabel");
package/lib/log-query.js CHANGED
@@ -1 +1 @@
1
- "use strict";var L=Object.defineProperty;var a=(e,t)=>L(e,"name",{value:t,configurable:!0});var d=Object.defineProperty,c=a((e,t)=>d(e,"name",{value:t,configurable:!0}),"a"),h=Object.defineProperty,u=c((e,t)=>h(e,"name",{value:t,configurable:!0}),"c");const p={level:"level",severity:"level",service:"service",svc:"service",src:"service",source:"service",flow:"flow",trace:"trace",request:"trace",category:"category",cat:"category",ms:"ms"},C={warn:"warning",err:"error"},k=/(-?)(?:([A-Za-z]+):)?(?:"([^"]*)"|(\S+))/g;export function parseLogQuery(e){const t=[],r=[];for(const s of e.matchAll(k)){const[o,n,g,y,w]=s,i=(y??w??"").trim(),l=g?p[g.toLowerCase()]:void 0;if(l&&i){const m=l==="level"?C[i.toLowerCase()]??i.toLowerCase():i;t.push({key:l,value:m,negate:n==="-"})}else o.trim()&&r.push(o.trim())}return{tokens:t,text:r.join(" ")}}a(parseLogQuery,"parseLogQuery"),c(parseLogQuery,"parseLogQuery"),u(parseLogQuery,"parseLogQuery");export function formatLogQuery(e){const t=u(r=>/\s/.test(r)?`"${r}"`:r,"quote");return[...e.tokens.map(r=>`${r.negate?"-":""}${r.key}:${t(r.value)}`),e.text].filter(Boolean).join(" ")}a(formatLogQuery,"formatLogQuery"),c(formatLogQuery,"formatLogQuery"),u(formatLogQuery,"formatLogQuery");function v(e,t){if(e===void 0)return!1;const r=/^(>=|<=|>|<|=)?\s*(\d+(?:\.\d+)?)$/.exec(t);if(!r)return!1;const s=Number(r[2]);switch(r[1]){case">":return e>s;case"<":return e<s;case"<=":return e<=s;case"=":return e===s;default:return e>=s}}a(v,"v"),c(v,"h"),u(v,"msMatches");function f(e,t){const r=t.value.toLowerCase();switch(t.key){case"level":return e.severity.toLowerCase()===r;case"service":return e.source.toLowerCase()===r;case"flow":return!!e.flowId&&e.flowId.toLowerCase().startsWith(r);case"trace":return!!e.requestId&&e.requestId.toLowerCase().startsWith(r);case"category":return e.category.toLowerCase()===r;case"ms":return v(e.durationMs,t.value)}}a(f,"l"),c(f,"i"),u(f,"tokenMatches");export function matchesLogQuery(e,t,r){const s=new Map;for(const o of t.tokens){if(o.negate){if(f(e,o))return!1;continue}const n=s.get(o.key);n?n.push(o):s.set(o.key,[o])}for(const o of s.values())if(!o.some(n=>f(e,n)))return!1;if(t.text){const o=`${e.title} ${e.message??""} ${e.source} ${e.flowId??""}`;return r?r(o):o.toLowerCase().includes(t.text.toLowerCase())}return!0}a(matchesLogQuery,"matchesLogQuery"),c(matchesLogQuery,"matchesLogQuery"),u(matchesLogQuery,"matchesLogQuery");
1
+ "use strict";var m=Object.defineProperty;var a=(e,r)=>m(e,"name",{value:r,configurable:!0});var L=Object.defineProperty,c=a((e,r)=>L(e,"name",{value:r,configurable:!0}),"c");const d={level:"level",severity:"level",service:"service",svc:"service",src:"service",source:"service",flow:"flow",trace:"trace",request:"trace",category:"category",cat:"category",ms:"ms"},h={warn:"warning",err:"error"},p=/(-?)(?:([A-Za-z]+):)?(?:"([^"]*)"|(\S+))/g;export function parseLogQuery(e){const r=[],t=[];for(const s of e.matchAll(p)){const[o,n,f,w,g]=s,u=(w??g??"").trim(),i=f?d[f.toLowerCase()]:void 0;if(i&&u){const y=i==="level"?h[u.toLowerCase()]??u.toLowerCase():u;r.push({key:i,value:y,negate:n==="-"})}else o.trim()&&t.push(o.trim())}return{tokens:r,text:t.join(" ")}}a(parseLogQuery,"parseLogQuery"),c(parseLogQuery,"parseLogQuery");export function formatLogQuery(e){const r=c(t=>/\s/.test(t)?`"${t}"`:t,"quote");return[...e.tokens.map(t=>`${t.negate?"-":""}${t.key}:${r(t.value)}`),e.text].filter(Boolean).join(" ")}a(formatLogQuery,"formatLogQuery"),c(formatLogQuery,"formatLogQuery");function v(e,r){if(e===void 0)return!1;const t=/^(>=|<=|>|<|=)?\s*(\d+(?:\.\d+)?)$/.exec(r);if(!t)return!1;const s=Number(t[2]);switch(t[1]){case">":return e>s;case"<":return e<s;case"<=":return e<=s;case"=":return e===s;default:return e>=s}}a(v,"h"),c(v,"msMatches");function l(e,r){const t=r.value.toLowerCase();switch(r.key){case"level":return e.severity.toLowerCase()===t;case"service":return e.source.toLowerCase()===t;case"flow":return!!e.flowId&&e.flowId.toLowerCase().startsWith(t);case"trace":return!!e.requestId&&e.requestId.toLowerCase().startsWith(t);case"category":return e.category.toLowerCase()===t;case"ms":return v(e.durationMs,r.value)}}a(l,"i"),c(l,"tokenMatches");export function matchesLogQuery(e,r,t){const s=new Map;for(const o of r.tokens){if(o.negate){if(l(e,o))return!1;continue}const n=s.get(o.key);n?n.push(o):s.set(o.key,[o])}for(const o of s.values())if(!o.some(n=>l(e,n)))return!1;if(r.text){const o=`${e.title} ${e.message??""} ${e.source} ${e.flowId??""}`;return t?t(o):o.toLowerCase().includes(r.text.toLowerCase())}return!0}a(matchesLogQuery,"matchesLogQuery"),c(matchesLogQuery,"matchesLogQuery");
@@ -1 +1 @@
1
- "use strict";var l=Object.defineProperty;var i=(e,t)=>l(e,"name",{value:t,configurable:!0});var f=Object.defineProperty,a=i((e,t)=>f(e,"name",{value:t,configurable:!0}),"i"),u=Object.defineProperty,c=a((e,t)=>u(e,"name",{value:t,configurable:!0}),"s");import{LENS_EVENT_SOURCE as S}from"./error-dismissal.js";export const METRICS_RESET="metrics-reset",METRICS_RESTORED="metrics-restored",METRICS_SCOPES=["sql","external"],MAX_METRICS_RESET_IDS=500,MAX_METRICS_RESET_ID_LENGTH=512,METRICS_RESET_IDS_PER_EVENT=64;const d=16*1024,p=c(e=>e==="sql"||e==="external","isScope"),E=c(e=>typeof e=="string"&&e.length>0&&e.length<=MAX_METRICS_RESET_ID_LENGTH,"isId");export function readMetricsReset(e){if(e.source!==S||!e.raw||typeof e.raw!="object")return;const t=e.raw,r=t.kind;if(r!==METRICS_RESET&&r!==METRICS_RESTORED)return;const n=t.scope;if(!p(n))return;let s;if(t.ids!==void 0&&(!Array.isArray(t.ids)||(s=[...new Set(t.ids.filter(E))].slice(0,METRICS_RESET_IDS_PER_EVENT),!s.length)))return;if(r===METRICS_RESTORED)return{kind:r,scope:n,...s?{ids:s}:{}};const o=t.at;if(!(typeof o!="number"||!Number.isFinite(o)))return{kind:r,scope:n,at:Math.min(o,e.timestamp),...s?{ids:s}:{}}}i(readMetricsReset,"readMetricsReset"),a(readMetricsReset,"readMetricsReset"),c(readMetricsReset,"readMetricsReset");export function metricsIdBatches(e){const t=[];let r=[],n=0;for(const s of new Set(e.filter(E)))r.length&&(r.length>=METRICS_RESET_IDS_PER_EVENT||n+s.length+3>d)&&(t.push(r),r=[],n=0),r.push(s),n+=s.length+3;return r.length&&t.push(r),t}i(metricsIdBatches,"metricsIdBatches"),a(metricsIdBatches,"metricsIdBatches"),c(metricsIdBatches,"metricsIdBatches");
1
+ "use strict";var a=Object.defineProperty;var i=(t,e)=>a(t,"name",{value:e,configurable:!0});var S=Object.defineProperty,o=i((t,e)=>S(t,"name",{value:e,configurable:!0}),"s");import{LENS_EVENT_SOURCE as f}from"./error-dismissal.js";export const METRICS_RESET="metrics-reset",METRICS_RESTORED="metrics-restored",METRICS_SCOPES=["sql","external"],MAX_METRICS_RESET_IDS=500,MAX_METRICS_RESET_ID_LENGTH=512,METRICS_RESET_IDS_PER_EVENT=64;const l=16*1024,u=o(t=>t==="sql"||t==="external","isScope"),E=o(t=>typeof t=="string"&&t.length>0&&t.length<=MAX_METRICS_RESET_ID_LENGTH,"isId");export function readMetricsReset(t){if(t.source!==f||!t.raw||typeof t.raw!="object")return;const e=t.raw,r=e.kind;if(r!==METRICS_RESET&&r!==METRICS_RESTORED)return;const n=e.scope;if(!u(n))return;let s;if(e.ids!==void 0&&(!Array.isArray(e.ids)||(s=[...new Set(e.ids.filter(E))].slice(0,METRICS_RESET_IDS_PER_EVENT),!s.length)))return;if(r===METRICS_RESTORED)return{kind:r,scope:n,...s?{ids:s}:{}};const c=e.at;if(!(typeof c!="number"||!Number.isFinite(c)))return{kind:r,scope:n,at:Math.min(c,t.timestamp),...s?{ids:s}:{}}}i(readMetricsReset,"readMetricsReset"),o(readMetricsReset,"readMetricsReset");export function metricsIdBatches(t){const e=[];let r=[],n=0;for(const s of new Set(t.filter(E)))r.length&&(r.length>=METRICS_RESET_IDS_PER_EVENT||n+s.length+3>l)&&(e.push(r),r=[],n=0),r.push(s),n+=s.length+3;return r.length&&e.push(r),e}i(metricsIdBatches,"metricsIdBatches"),o(metricsIdBatches,"metricsIdBatches");
@@ -1 +1 @@
1
- "use strict";var u=Object.defineProperty;var i=(e,n)=>u(e,"name",{value:n,configurable:!0});var f=Object.defineProperty,s=i((e,n)=>f(e,"name",{value:n,configurable:!0}),"i"),d=Object.defineProperty,r=s((e,n)=>d(e,"name",{value:n,configurable:!0}),"s");export const FINDING_RUN_KINDS=["operate","stop-launch","close-session","role","role-off","check","rule","flow","lesson"];export function findingLive(e){return e.state==="open"||e.state==="proposed"||e.state==="applied"}i(findingLive,"findingLive"),s(findingLive,"findingLive"),r(findingLive,"findingLive");export function findingRunsActions(e,n={}){return e.actions.some(o=>FINDING_RUN_KINDS.includes(o.kind)||o.kind==="issue"&&n.issuesFolder===!0)}i(findingRunsActions,"findingRunsActions"),s(findingRunsActions,"findingRunsActions"),r(findingRunsActions,"findingRunsActions");export function findingsForCheck(e,n,o){const c=`repo:${n}/team.${o}`;return e.filter(t=>findingLive(t)&&t.checks.includes(c))}i(findingsForCheck,"findingsForCheck"),s(findingsForCheck,"findingsForCheck"),r(findingsForCheck,"findingsForCheck");
1
+ "use strict";var c=Object.defineProperty;var i=(e,n)=>c(e,"name",{value:n,configurable:!0});var u=Object.defineProperty,o=i((e,n)=>u(e,"name",{value:n,configurable:!0}),"s");export const FINDING_RUN_KINDS=["operate","stop-launch","close-session","role","role-off","check","rule","flow","lesson"];export function findingLive(e){return e.state==="open"||e.state==="proposed"||e.state==="applied"}i(findingLive,"findingLive"),o(findingLive,"findingLive");export function findingRunsActions(e,n={}){return e.actions.some(s=>FINDING_RUN_KINDS.includes(s.kind)||s.kind==="issue"&&n.issuesFolder===!0)}i(findingRunsActions,"findingRunsActions"),o(findingRunsActions,"findingRunsActions");export function findingsForCheck(e,n,s){const r=`repo:${n}/team.${s}`;return e.filter(t=>findingLive(t)&&t.checks.includes(r))}i(findingsForCheck,"findingsForCheck"),o(findingsForCheck,"findingsForCheck");
package/lib/perf-rules.js CHANGED
@@ -1 +1 @@
1
- "use strict";var c=Object.defineProperty;var a=(r,e)=>c(r,"name",{value:e,configurable:!0});var l=Object.defineProperty,o=a((r,e)=>l(r,"name",{value:e,configurable:!0}),"o"),f=Object.defineProperty,p=o((r,e)=>f(r,"name",{value:e,configurable:!0}),"o");export const PERF_RULE_IDS=["bundle/heavy-barrel-import","pod/heap-budget","pod/retained-generation"],PERF_RULE_EVENT_KINDS=["perf-rule-finding","perf-rule-retracted","perf-rule-scan"],PERF_RULES_DOC="https://github.com/kiwiapps-ltd/lensmcp/blob/main/docs/lensmcp/concepts/memory-and-build-cost.mdx",PERF_RULE_DOCS={"bundle/heavy-barrel-import":`${PERF_RULES_DOC}#bundleheavy-barrel-import`,"pod/heap-budget":`${PERF_RULES_DOC}#podheap-budget`,"pod/retained-generation":`${PERF_RULES_DOC}#podretained-generation`};export function perfRuleFingerprint(r,e,n){return`perf-rule:${r}:${e}:${n}`}a(perfRuleFingerprint,"perfRuleFingerprint"),o(perfRuleFingerprint,"perfRuleFingerprint"),p(perfRuleFingerprint,"perfRuleFingerprint");export function perfRuleScanFingerprint(r,e){return`perf-rule-scan:${r}:${e}`}a(perfRuleScanFingerprint,"perfRuleScanFingerprint"),o(perfRuleScanFingerprint,"perfRuleScanFingerprint"),p(perfRuleScanFingerprint,"perfRuleScanFingerprint");const s=/^[a-z][a-z0-9-]*\/[a-z0-9][a-z0-9-]*$/,d=12,y=4e3,t=p((r,e=y)=>typeof r=="string"&&r.length>0&&r.length<=e,"isText");export function asPerfRuleRaw(r){if(!r||typeof r!="object")return;const e=r;if(!PERF_RULE_EVENT_KINDS.includes(e.kind)||typeof e.rule!="string"||!s.test(e.rule)||!t(e.project,512))return;if(e.kind==="perf-rule-scan"){const i=e.open;return!Array.isArray(i)||i.length>256||!i.every(u=>t(u,512))?void 0:r}if(!t(e.subject,512))return;if(e.kind==="perf-rule-retracted")return r;if(e.severity!=="warning"&&e.severity!=="error"||!t(e.title)||!t(e.summary)||!t(e.verify)||!t(e.docs,1024))return;const n=e.fix;if(!(!Array.isArray(n)||n.length===0||n.length>d||!n.every(i=>t(i)))&&!(!e.evidence||typeof e.evidence!="object"||Array.isArray(e.evidence))&&!(!e.cost||typeof e.cost!="object"||Array.isArray(e.cost)))return r}a(asPerfRuleRaw,"asPerfRuleRaw"),o(asPerfRuleRaw,"asPerfRuleRaw"),p(asPerfRuleRaw,"asPerfRuleRaw");
1
+ "use strict";var u=Object.defineProperty;var o=(r,e)=>u(r,"name",{value:e,configurable:!0});var c=Object.defineProperty,a=o((r,e)=>c(r,"name",{value:e,configurable:!0}),"o");export const PERF_RULE_IDS=["bundle/heavy-barrel-import","pod/heap-budget","pod/retained-generation"],PERF_RULE_EVENT_KINDS=["perf-rule-finding","perf-rule-retracted","perf-rule-scan"],PERF_RULES_DOC="https://github.com/kiwiapps-ltd/lensmcp/blob/main/docs/lensmcp/concepts/memory-and-build-cost.mdx",PERF_RULE_DOCS={"bundle/heavy-barrel-import":`${PERF_RULES_DOC}#bundleheavy-barrel-import`,"pod/heap-budget":`${PERF_RULES_DOC}#podheap-budget`,"pod/retained-generation":`${PERF_RULES_DOC}#podretained-generation`};export function perfRuleFingerprint(r,e,n){return`perf-rule:${r}:${e}:${n}`}o(perfRuleFingerprint,"perfRuleFingerprint"),a(perfRuleFingerprint,"perfRuleFingerprint");export function perfRuleScanFingerprint(r,e){return`perf-rule-scan:${r}:${e}`}o(perfRuleScanFingerprint,"perfRuleScanFingerprint"),a(perfRuleScanFingerprint,"perfRuleScanFingerprint");const s=/^[a-z][a-z0-9-]*\/[a-z0-9][a-z0-9-]*$/,l=12,f=4e3,t=a((r,e=f)=>typeof r=="string"&&r.length>0&&r.length<=e,"isText");export function asPerfRuleRaw(r){if(!r||typeof r!="object")return;const e=r;if(!PERF_RULE_EVENT_KINDS.includes(e.kind)||typeof e.rule!="string"||!s.test(e.rule)||!t(e.project,512))return;if(e.kind==="perf-rule-scan"){const i=e.open;return!Array.isArray(i)||i.length>256||!i.every(p=>t(p,512))?void 0:r}if(!t(e.subject,512))return;if(e.kind==="perf-rule-retracted")return r;if(e.severity!=="warning"&&e.severity!=="error"||!t(e.title)||!t(e.summary)||!t(e.verify)||!t(e.docs,1024))return;const n=e.fix;if(!(!Array.isArray(n)||n.length===0||n.length>l||!n.every(i=>t(i)))&&!(!e.evidence||typeof e.evidence!="object"||Array.isArray(e.evidence))&&!(!e.cost||typeof e.cost!="object"||Array.isArray(e.cost)))return r}o(asPerfRuleRaw,"asPerfRuleRaw"),a(asPerfRuleRaw,"asPerfRuleRaw");
package/lib/pod-memory.js CHANGED
@@ -1 +1 @@
1
- "use strict";var n=Object.defineProperty;var o=(r,e)=>n(r,"name",{value:e,configurable:!0});var d=Object.defineProperty,t=o((r,e)=>d(r,"name",{value:e,configurable:!0}),"r"),m=Object.defineProperty,i=t((r,e)=>m(r,"name",{value:e,configurable:!0}),"r");export const POD_MEMORY_KINDS=["pod-memory","pod-memory-retained","pod-memory-released","pod-memory-exited"];export function asPodMemoryRaw(r){if(!r||typeof r!="object")return;const e=r;if(POD_MEMORY_KINDS.includes(e.kind)&&!(typeof e.project!="string"||!e.project)&&!(typeof e.pod!="number"||typeof e.pid!="number")&&!(e.kind==="pod-memory"&&(typeof e.live!="number"||!Number.isFinite(e.live)))&&!((e.kind==="pod-memory-retained"||e.kind==="pod-memory-released")&&typeof e.gen!="number"))return r}o(asPodMemoryRaw,"asPodMemoryRaw"),t(asPodMemoryRaw,"asPodMemoryRaw"),i(asPodMemoryRaw,"asPodMemoryRaw");
1
+ "use strict";var t=Object.defineProperty;var r=(o,e)=>t(o,"name",{value:e,configurable:!0});var d=Object.defineProperty,m=r((o,e)=>d(o,"name",{value:e,configurable:!0}),"r");export const POD_MEMORY_KINDS=["pod-memory","pod-memory-retained","pod-memory-released","pod-memory-exited"];export function asPodMemoryRaw(o){if(!o||typeof o!="object")return;const e=o;if(POD_MEMORY_KINDS.includes(e.kind)&&!(typeof e.project!="string"||!e.project)&&!(typeof e.pod!="number"||typeof e.pid!="number")&&!(e.kind==="pod-memory"&&(typeof e.live!="number"||!Number.isFinite(e.live)))&&!((e.kind==="pod-memory-retained"||e.kind==="pod-memory-released")&&typeof e.gen!="number"))return o}r(asPodMemoryRaw,"asPodMemoryRaw"),m(asPodMemoryRaw,"asPodMemoryRaw");