@lensmcp/protocol-types 1.26.7 → 1.26.9
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.
- package/index.d.ts +3 -0
- package/index.js +1 -1
- package/lib/ai-call-groups.js +2 -2
- package/lib/ai-call-row.js +3 -3
- package/lib/ai-call.js +9 -9
- package/lib/ai-context.js +6 -6
- package/lib/ai-origins.js +6 -6
- package/lib/backlog.d.ts +83 -0
- package/lib/backlog.js +1 -0
- package/lib/bounded-clone.js +1 -1
- package/lib/bounded-map.js +1 -1
- package/lib/bounded-writer.js +1 -1
- package/lib/capture-demand.js +1 -1
- package/lib/dashboard-path.js +1 -1
- package/lib/dashboard.d.ts +15 -0
- package/lib/docker-errors.js +1 -1
- package/lib/docker-jobs.d.ts +22 -0
- package/lib/docker-jobs.js +1 -1
- package/lib/docker-report.js +2 -2
- package/lib/docker-runs.js +3 -3
- package/lib/error-cause.js +6 -6
- package/lib/error-dismissal.js +1 -1
- package/lib/error-verdict.d.ts +161 -0
- package/lib/error-verdict.js +3 -0
- package/lib/event-loop.js +1 -1
- package/lib/expected-failure.js +2 -2
- package/lib/flood-guard.js +1 -1
- package/lib/follow-ups.d.ts +4 -0
- package/lib/goal-design.js +1 -1
- package/lib/host-agents.js +1 -1
- package/lib/hosts.d.ts +2 -0
- package/lib/lint-coverage.js +1 -1
- package/lib/log-query.js +1 -1
- package/lib/metrics-reset.js +1 -1
- package/lib/overseer-findings.js +1 -1
- package/lib/peers.d.ts +14 -1
- package/lib/peers.js +1 -1
- package/lib/perf-rules.js +1 -1
- package/lib/pod-memory.js +1 -1
- package/lib/producer-health.js +1 -1
- package/lib/remote-instances.d.ts +6 -0
- package/lib/remote-instances.js +1 -1
- package/lib/sessions.d.ts +233 -0
- package/lib/sessions.js +1 -0
- package/lib/sources.js +1 -1
- package/lib/static-checks.js +1 -1
- package/lib/system-report.js +1 -1
- package/lib/team.js +1 -1
- package/lib/workspace-actions.d.ts +10 -0
- package/package.json +1 -1
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
import type { BaseEvent } from './event.js';
|
|
2
|
+
import { type DismissedBy } from './error-dismissal.js';
|
|
3
|
+
import type { FailureFacts } from './expected-failure.js';
|
|
4
|
+
/**
|
|
5
|
+
* Whether an error is a bug, as the lens can show it from what it recorded (issues/overseer-105).
|
|
6
|
+
*
|
|
7
|
+
* A dismissal and a standing rule are a person's word. This is the lens's: three narrow checks, each over evidence the
|
|
8
|
+
* bus already carries, each naming the event it rests on.
|
|
9
|
+
*
|
|
10
|
+
* - `restart` — every occurrence fell inside a stop/restart window of the service that raised it (the gateway's own
|
|
11
|
+
* lifecycle events). A window opens AT the stop: what a process printed before it died is no part of it.
|
|
12
|
+
* - `test-expected` — the failing request came from a test run the lens can name (a `test-run` event, by its flow
|
|
13
|
+
* scope), and that run passed.
|
|
14
|
+
* - `auth-expired` — a 401/403 whose request the app said carried an expired token or session, and the client
|
|
15
|
+
* recovered: a refresh then the same request answered, or the page went to sign-in.
|
|
16
|
+
*
|
|
17
|
+
* What keeps it from becoming a way to stop seeing failures:
|
|
18
|
+
* - **No guess.** `bug` is the default. A check whose trigger matched but whose evidence the lens cannot read says
|
|
19
|
+
* `unsure`, never `not-a-bug`.
|
|
20
|
+
* - **Every occurrence.** A group is `not-a-bug` only when every occurrence it counted is: a new one outside the
|
|
21
|
+
* evidence turns it back to `bug`, and one it can no longer check makes it `unsure`.
|
|
22
|
+
* - **Never hidden.** A not-a-bug error stays listed and counted; a person's «this is a bug» (`error-verdict-set`, a
|
|
23
|
+
* bus event undone by `error-verdict-cleared`) wins over the lens.
|
|
24
|
+
*/
|
|
25
|
+
export type NotABugKind = 'restart' | 'test-expected' | 'auth-expired';
|
|
26
|
+
export declare const NOT_A_BUG_KINDS: readonly NotABugKind[];
|
|
27
|
+
/** One thing the lens recorded that a verdict rests on — and what to open to see it. */
|
|
28
|
+
export interface VerdictEvidence {
|
|
29
|
+
kind: NotABugKind;
|
|
30
|
+
/** What it was, in a line: `engine — handed over to a new pod (build)`. */
|
|
31
|
+
line: string;
|
|
32
|
+
/** When: the restart's start, the run's end, the recovery. */
|
|
33
|
+
at: number;
|
|
34
|
+
service?: string;
|
|
35
|
+
runId?: string;
|
|
36
|
+
flowId?: string;
|
|
37
|
+
}
|
|
38
|
+
export type ErrorVerdict = {
|
|
39
|
+
verdict: 'bug';
|
|
40
|
+
note?: string;
|
|
41
|
+
overridden?: {
|
|
42
|
+
by?: DismissedBy;
|
|
43
|
+
at: number;
|
|
44
|
+
};
|
|
45
|
+
} | {
|
|
46
|
+
verdict: 'not-a-bug';
|
|
47
|
+
kind: NotABugKind;
|
|
48
|
+
line: string;
|
|
49
|
+
evidence: VerdictEvidence[];
|
|
50
|
+
} | {
|
|
51
|
+
verdict: 'unsure';
|
|
52
|
+
kind: NotABugKind;
|
|
53
|
+
missing: string;
|
|
54
|
+
};
|
|
55
|
+
/** One occurrence as the checks read it: when, and what it, its request and its flow said. */
|
|
56
|
+
export type VerdictOccurrence = {
|
|
57
|
+
at: number;
|
|
58
|
+
} & Pick<FailureFacts, 'service' | 'flowId' | 'requestId' | 'status' | 'method' | 'routes' | 'errorName' | 'message'>;
|
|
59
|
+
/** An occurrence's facts (`failureFacts`, enriched with its request's) as the checks read them. */
|
|
60
|
+
export declare function verdictOccurrence(at: number, f: FailureFacts): VerdictOccurrence;
|
|
61
|
+
/** A test or e2e run's state, as the action runner tells the bus: when it starts and when it ends. */
|
|
62
|
+
export declare const TEST_RUN = "test-run";
|
|
63
|
+
/** What a test process is given to stamp its requests' flows with: a flow id that starts with it is the run's. */
|
|
64
|
+
export declare const TEST_FLOW_SCOPE_ENV = "LENSMCP_TEST_FLOW_SCOPE";
|
|
65
|
+
export declare const testFlowScope: (runId: string) => string;
|
|
66
|
+
/** A flow named as a test's (the flow categories' rule): `e2e-…`, `test-…`, `verify-…`, `smoke-…`, `load-…`. */
|
|
67
|
+
export declare const TEST_FLOW_ID: RegExp;
|
|
68
|
+
export interface TestRunRecord {
|
|
69
|
+
runId: string;
|
|
70
|
+
/** `running` · `passed` · `failed` · `errored` · `cancelled` · `timeout`. */
|
|
71
|
+
state: string;
|
|
72
|
+
flowScope: string;
|
|
73
|
+
action?: string;
|
|
74
|
+
project?: string;
|
|
75
|
+
target?: string;
|
|
76
|
+
counts?: {
|
|
77
|
+
passed: number;
|
|
78
|
+
failed: number;
|
|
79
|
+
total: number;
|
|
80
|
+
};
|
|
81
|
+
at: number;
|
|
82
|
+
}
|
|
83
|
+
export declare const ERROR_VERDICT_SET = "error-verdict-set";
|
|
84
|
+
export declare const ERROR_VERDICT_CLEARED = "error-verdict-cleared";
|
|
85
|
+
/** «This is a bug»: a person's word over the lens's, for a group (and the cause it was made from, and its events). */
|
|
86
|
+
export interface VerdictOverride {
|
|
87
|
+
kind: typeof ERROR_VERDICT_SET;
|
|
88
|
+
groupId: string;
|
|
89
|
+
causeId?: string;
|
|
90
|
+
eventIds: string[];
|
|
91
|
+
by?: DismissedBy;
|
|
92
|
+
at: number;
|
|
93
|
+
}
|
|
94
|
+
export interface VerdictOverrideCleared {
|
|
95
|
+
kind: typeof ERROR_VERDICT_CLEARED;
|
|
96
|
+
groupId: string;
|
|
97
|
+
causeId?: string;
|
|
98
|
+
}
|
|
99
|
+
export declare function readTestRun(e: Pick<BaseEvent, 'source' | 'timestamp' | 'raw'>): TestRunRecord | undefined;
|
|
100
|
+
export declare function readVerdictOverride(e: Pick<BaseEvent, 'source' | 'timestamp' | 'raw'>): VerdictOverride | VerdictOverrideCleared | undefined;
|
|
101
|
+
/** How long a client has to refresh and retry, or to go to sign-in, after a 401. */
|
|
102
|
+
export declare const RECOVERY_MS = 60000;
|
|
103
|
+
interface RestartWindow {
|
|
104
|
+
start: number;
|
|
105
|
+
end?: number;
|
|
106
|
+
how: string;
|
|
107
|
+
/** It was crash-looping: no evidence of a restart. */
|
|
108
|
+
looping?: true;
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* What the checks read, folded off the bus — restart windows per service, test runs, and per flow the requests and
|
|
112
|
+
* navigations a recovery is read from. Bounded; cheap per event. Both lens processes keep one (the dashboard's error
|
|
113
|
+
* log, the MCP server's runtime reducer), so both say the same.
|
|
114
|
+
*/
|
|
115
|
+
export declare class ErrorVerdictIndex {
|
|
116
|
+
private readonly windows;
|
|
117
|
+
/** Flow scope → its run's newest state. */
|
|
118
|
+
private readonly runs;
|
|
119
|
+
private readonly requests;
|
|
120
|
+
private readonly navigations;
|
|
121
|
+
private readonly tabOfFlow;
|
|
122
|
+
private readonly expired;
|
|
123
|
+
/** Learn from one bus event. True when a restart window or a test run changed — verdicts may read differently now. */
|
|
124
|
+
observe(e: Pick<BaseEvent, 'source' | 'timestamp' | 'severity' | 'context' | 'raw' | 'title' | 'message'>): boolean;
|
|
125
|
+
/** A stop opens a window, a crash loop spoils it, the service back closes it. True when a window changed. */
|
|
126
|
+
private lifecycle;
|
|
127
|
+
private request;
|
|
128
|
+
/** The page a navigation went to: the client runtime's `route` and `ready`, a route's own flow. */
|
|
129
|
+
private navigation;
|
|
130
|
+
/** The stop/restart window of this service the moment falls in — none while it was crash-looping. */
|
|
131
|
+
restartAround(service: string, at: number): (RestartWindow & {
|
|
132
|
+
service: string;
|
|
133
|
+
}) | undefined;
|
|
134
|
+
/** The test run whose flow scope this flow carries: the flow id, or a part of it that ends before a separator. */
|
|
135
|
+
testRunOf(flowId: string): TestRunRecord | undefined;
|
|
136
|
+
/** What said this occurrence's token or session had expired: its own words, or any event of its request. */
|
|
137
|
+
expiredSaid(o: VerdictOccurrence): string | undefined;
|
|
138
|
+
/** How the client recovered from a refused request within a minute: a refresh then the request again, or sign-in. */
|
|
139
|
+
recovery(o: VerdictOccurrence): {
|
|
140
|
+
line: string;
|
|
141
|
+
at: number;
|
|
142
|
+
} | undefined;
|
|
143
|
+
}
|
|
144
|
+
/** One occurrence's verdict: the first check that clears it, else the first that cannot read its evidence, else a bug. */
|
|
145
|
+
export declare function judgeOccurrence(o: VerdictOccurrence, index: ErrorVerdictIndex, now: number): ErrorVerdict;
|
|
146
|
+
/**
|
|
147
|
+
* A group's verdict from its occurrences' — or a cause's from its surfaces' (`of`). `counted`: how many occurrences the
|
|
148
|
+
* group counted, when more than it still holds to check.
|
|
149
|
+
*/
|
|
150
|
+
export declare function combineVerdicts(verdicts: readonly ErrorVerdict[], counted?: number, of?: string): ErrorVerdict;
|
|
151
|
+
/** What «Explain with Claude» answers beside its explanation — shown as Claude's, never applied as a rule. */
|
|
152
|
+
export interface ErrorJudgement {
|
|
153
|
+
verdict: 'bug' | 'not-a-bug' | 'unsure';
|
|
154
|
+
kind?: NotABugKind | 'other';
|
|
155
|
+
why: string;
|
|
156
|
+
}
|
|
157
|
+
/** The answer's key, as the review is asked for it. */
|
|
158
|
+
export declare const ERROR_JUDGEMENT_ASK: string;
|
|
159
|
+
/** Claude's verdict, field by field. A missing or malformed one reads `unsure`: it is never taken for a verdict it did not give. */
|
|
160
|
+
export declare function readErrorJudgement(raw: unknown): ErrorJudgement;
|
|
161
|
+
export {};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
"use strict";var q=Object.defineProperty;var p=(t,e)=>q(t,"name",{value:e,configurable:!0});var j=Object.defineProperty,c=p((t,e)=>j(t,"name",{value:e,configurable:!0}),"a");import{LENS_EVENT_SOURCE as I}from"./error-dismissal.js";export const NOT_A_BUG_KINDS=["restart","test-expected","auth-expired"];export function verdictOccurrence(t,e){return{at:t,...e.service?{service:e.service}:{},...e.flowId?{flowId:e.flowId}:{},...e.requestId?{requestId:e.requestId}:{},...e.status!==void 0?{status:e.status}:{},...e.method?{method:e.method}:{},...e.routes?{routes:e.routes}:{},...e.errorName?{errorName:e.errorName}:{},...e.message?{message:e.message}:{}}}p(verdictOccurrence,"verdictOccurrence"),c(verdictOccurrence,"verdictOccurrence");export const TEST_RUN="test-run",TEST_FLOW_SCOPE_ENV="LENSMCP_TEST_FLOW_SCOPE",testFlowScope=c(t=>`e2e-${t}`,"testFlowScope"),TEST_FLOW_ID=/^(verify|e2e|test|smoke|load)[-_:]/i,ERROR_VERDICT_SET="error-verdict-set",ERROR_VERDICT_CLEARED="error-verdict-cleared";const v=c(t=>typeof t=="object"&&t!==null&&!Array.isArray(t),"isObj"),a=c((t,e=300)=>typeof t=="string"&&t.trim()?t.trim().slice(0,e):void 0,"str"),m=c(t=>typeof t=="number"&&Number.isFinite(t)?t:void 0,"num"),N=200,F=new Set(["dashboard","cli","agent"]);export function readTestRun(t){if(t.source!==I||!v(t.raw)||t.raw.kind!==TEST_RUN)return;const e=t.raw,s=a(e.runId,120),n=a(e.state,20),i=a(e.flowScope,200);if(!s||!n||!i)return;const r=v(e.counts)?e.counts:void 0,o=m(r?.passed),u=m(r?.failed),l=m(r?.total);return{runId:s,state:n,flowScope:i,...a(e.action,40)?{action:a(e.action,40)}:{},...a(e.project,200)?{project:a(e.project,200)}:{},...a(e.target,200)?{target:a(e.target,200)}:{},...o!==void 0&&u!==void 0&&l!==void 0?{counts:{passed:o,failed:u,total:l}}:{},at:t.timestamp}}p(readTestRun,"readTestRun"),c(readTestRun,"readTestRun");export function readVerdictOverride(t){if(t.source!==I||!v(t.raw))return;const e=t.raw,s=a(e.groupId,2048);if(!s)return;const n=a(e.causeId,2048);if(e.kind===ERROR_VERDICT_CLEARED)return{kind:ERROR_VERDICT_CLEARED,groupId:s,...n?{causeId:n}:{}};if(e.kind!==ERROR_VERDICT_SET||e.verdict!=="bug")return;const i=Array.isArray(e.eventIds)?e.eventIds.filter(r=>typeof r=="string"&&r.length>0).slice(0,N):[];return{kind:ERROR_VERDICT_SET,groupId:s,...n?{causeId:n}:{},eventIds:i,...F.has(e.by)?{by:e.by}:{},at:t.timestamp}}p(readVerdictOverride,"readVerdictOverride"),c(readVerdictOverride,"readVerdictOverride");const E=2*6e4,A=1e4;export const RECOVERY_MS=6e4;const O=50,M=200,V=200,x=2e3,k=40,C=5e3,S={"service-restart":c(t=>`restarted${a(t.reason,80)?` (${a(t.reason,80)})`:""}`,"service-restart"),"pod-handoff-start":c(t=>`handed over to a new pod${a(t.reason,80)?` (${a(t.reason,80)})`:""}`,"pod-handoff-start"),"pod-recycle":c(t=>`its pod was recycled${a(t.reason,80)?` (${a(t.reason,80)})`:""}`,"pod-recycle"),"service-recycle":c(()=>"recycled after it stopped answering","service-recycle"),"idle-kill":c(()=>"stopped while idle","idle-kill"),"service-down":c(()=>"went down","service-down"),"service-respawn":c(()=>"started again by self-heal","service-respawn"),"service-starting":c(()=>"was starting","service-starting"),"worker-stopped":c(t=>`${y(t)} stopped`,"worker-stopped"),"worker-crashed":c(t=>`${y(t)} crashed and was started again`,"worker-crashed")};function y(t){const e=a(t.worker,80);return e?`its worker ${e}`:"its worker"}p(y,"x"),c(y,"workerOf");const z=new Set(["service-up","pod-handoff-complete","pod-handoff-failed","worker-started","worker-up"]),_=/\b(?:TokenExpired(?:Error)?|JWTExpired|jwt expired|(?:token|session|jwt|credentials?) (?:has |is |was )?expired|expired (?:token|session|jwt|credentials?)|"exp" claim)/i,B=/(?:^|[/._-])(?:refresh|renew|re-?auth|silent|token)(?:[/._-]|$)/i,D=/(?:^|\/)(?:log-?in|sign-?in)(?:\/|$)/i,L=/[-_:/.]/,U=new Set(["failed","errored","cancelled","timeout"]),W=new Set(["server-request","gateway-request","fetch-done","fetch"]),b=c(t=>{const e=t.split(/[?#]/)[0]??t,s=/^[a-z][a-z0-9+.-]*:\/\/[^/]+(\/.*)?$/i.exec(e);return s?s[1]??"/":e},"pathOf"),P=c(t=>t!==void 0&&t>=200&&t<300,"ok"),R=c(t=>new Date(t).toISOString().slice(11,19),"clock");function $(t,e,s,n,i){const r=t.get(e);if(r){r.push(s),r.length>n&&r.splice(0,r.length-n);return}t.set(e,[s]),t.size>i&&t.delete(t.keys().next().value)}p($,"E"),c($,"push");export class ErrorVerdictIndex{static{p(this,"ErrorVerdictIndex")}static{c(this,"ErrorVerdictIndex")}constructor(){this.windows=new Map,this.runs=new Map,this.requests=new Map,this.navigations=new Map,this.tabOfFlow=new Map,this.expired=new Map}observe(e){const s=v(e.raw)?e.raw:{},n=e.context??{},i=a(s.kind,60);if(e.source==="gateway"&&i&&this.lifecycle(i,s,e.timestamp))return!0;const r=readTestRun(e);if(r)return U.has(this.runs.get(r.flowScope)?.state??"")?!1:(this.runs.delete(r.flowScope),this.runs.set(r.flowScope,r),this.runs.size>V&&this.runs.delete(this.runs.keys().next().value),!0);const o=a(n.flowId,400),u=a(n.tabId,200),l=a(n.requestId,400);o&&u&&!this.tabOfFlow.has(o)&&(this.tabOfFlow.set(o,u),this.tabOfFlow.size>x&&this.tabOfFlow.delete(this.tabOfFlow.keys().next().value)),o&&i&&W.has(i)&&this.request(o,s,e.timestamp);const d=this.navigation(i,s,n);if(d&&(o&&$(this.navigations,`flow:${o}`,{at:e.timestamp,path:d},k,x),u&&$(this.navigations,`tab:${u}`,{at:e.timestamp,path:d},k,x)),l&&(e.severity==="warning"||e.severity==="error"||e.severity==="fatal")&&!this.expired.has(l)){const w=[(v(s.request)?s.request:{}).error,v(s.span)?s.span.error:void 0,s.error].filter(v),h=[e.title,e.message,...w.flatMap(f=>[f.name,f.message])].map(f=>a(f,600)).find(f=>f!==void 0&&_.test(f));h&&(this.expired.set(l,h.split(`
|
|
2
|
+
`)[0].slice(0,120)),this.expired.size>C&&this.expired.delete(this.expired.keys().next().value))}return!1}lifecycle(e,s,n){const i=a(s.project,200);if(!i)return!1;const r=this.windows.get(i)??[],o=r.find(l=>l.end===void 0&&n-l.start<=E),u=e==="service-crash-loop"||e==="worker-crashed"&&s.crashLooping===!0;if((e==="service-restart"?s.phase==="started":S[e])||u){const l=o??{start:n,how:(S[e]??(()=>"crash-looping"))(s)};u&&(l.looping=!0),o||r.push(l)}else if(z.has(e)||e==="service-restart"){if(!o)return!1;o.end=n}else return!1;return r.length>O&&r.splice(0,r.length-O),this.windows.delete(i),this.windows.set(i,r),this.windows.size>M&&this.windows.delete(this.windows.keys().next().value),!0}request(e,s,n){const i=v(s.request)?s.request:s,r=[a(i.route,400),a(i.url,2e3)?b(a(i.url,2e3)):void 0].filter(l=>!!l),o=a(i.method,10)?.toUpperCase(),u=m(i.status);$(this.requests,e,{at:n,...o?{method:o}:{},paths:r,...u!==void 0?{status:u}:{}},k,x)}navigation(e,s,n){if((e==="route"||e==="ready")&&a(s.url,2e3))return b(a(s.url,2e3));const i=a(n.originType,40);if(i!=="route-load"&&i!=="page-load")return;const r=a(n.originNodeId,400);return r?.startsWith("route:")?r.slice(6):a(n.route,400)??(a(n.url,2e3)?b(a(n.url,2e3)):void 0)}restartAround(e,s){const n=this.windows.get(e)?.find(i=>!i.looping&&s>=i.start&&s<=(i.end??i.start+E)+A);return n&&{...n,service:e}}testRunOf(e){if(this.runs.size)for(let s=e.length;s>0;s--){if(s<e.length&&!L.test(e[s]))continue;const n=this.runs.get(e.slice(0,s));if(n)return n}}expiredSaid(e){const s=[e.errorName,e.message].map(n=>a(n,600)).find(n=>n!==void 0&&_.test(n));return s?s.split(`
|
|
3
|
+
`)[0].slice(0,120):e.requestId?this.expired.get(e.requestId):void 0}recovery(e){if(!e.flowId)return;const s=c(d=>d>=e.at&&d<=e.at+RECOVERY_MS,"within"),n=new Set(e.routes??[]),i=(this.requests.get(e.flowId)??[]).filter(d=>s(d.at)&&P(d.status)),r=i.find(d=>d.paths.some(w=>B.test(w))&&!d.paths.some(w=>n.has(w))),o=r&&i.find(d=>d.at>=r.at&&d!==r&&(!e.method||!d.method||d.method===e.method)&&d.paths.some(w=>n.has(w)));if(r&&o)return{line:`refreshed (${r.method??""} ${r.paths[0]} \u2192 ${r.status}) and retried (${o.paths[0]} \u2192 ${o.status})`.replace("( ","("),at:o.at};const u=this.tabOfFlow.get(e.flowId),l=[...this.navigations.get(`flow:${e.flowId}`)??[],...u?this.navigations.get(`tab:${u}`)??[]:[]].find(d=>s(d.at)&&D.test(d.path));return l?{line:`went to sign-in (${l.path})`,at:l.at}:void 0}}const T={verdict:"bug"};export function judgeOccurrence(t,e,s){let n,i;if(t.service){const r=e.restartAround(t.service,t.at);if(r){const o=`${r.service} ${r.how} at ${R(r.start)}${r.end!==void 0?`, back at ${R(r.end)}`:""} UTC`;return{verdict:"not-a-bug",kind:"restart",line:o,evidence:[{kind:"restart",line:o,at:r.start,service:r.service}]}}}if(t.flowId){const r=e.testRunOf(t.flowId);if(r?.state==="passed"){const o=r.project?` (${r.project}${r.target?`:${r.target}`:""})`:"",u=`test run ${r.runId}${o} passed${r.counts?` \u2014 ${r.counts.passed} of ${r.counts.total} tests`:""}: the failure was part of the test`;return{verdict:"not-a-bug",kind:"test-expected",line:u,evidence:[{kind:"test-expected",line:u,at:r.at,runId:r.runId,flowId:t.flowId}]}}r?.state==="running"||r?.state==="queued"?n??={verdict:"unsure",kind:"test-expected",missing:`its test run ${r.runId} has not ended`}:r?i??=`its test run ${r.runId} ${r.state} \u2014 a failing run is no evidence it was expected`:TEST_FLOW_ID.test(t.flowId)&&(n??={verdict:"unsure",kind:"test-expected",missing:`flow ${t.flowId} is a test's, but no test run the lens holds names it`})}if(t.status===401||t.status===403)if(!t.flowId)n??={verdict:"unsure",kind:"auth-expired",missing:"not part of a flow: whether the client recovered cannot be followed"};else{const r=e.expiredSaid(t),o=e.recovery(t);if(r&&o){const u=`${t.status}: the app said \xAB${r}\xBB, and the client ${o.line}`;return{verdict:"not-a-bug",kind:"auth-expired",line:u,evidence:[{kind:"auth-expired",line:u,at:o.at,flowId:t.flowId}]}}o?n??={verdict:"unsure",kind:"auth-expired",missing:`the client ${o.line}, but nothing it recorded says the token had expired \u2014 a valid token refused reads the same`}:s-t.at<RECOVERY_MS?n??={verdict:"unsure",kind:"auth-expired",missing:"waiting up to a minute for the client to refresh and retry, or go to sign-in"}:r&&(i??=`its token had expired (\xAB${r}\xBB) and the client did not recover within a minute \u2014 no refresh and retry, no sign-in`)}return n??(i?{verdict:"bug",note:i}:T)}p(judgeOccurrence,"judgeOccurrence"),c(judgeOccurrence,"judgeOccurrence");const J={restart:"fell inside a restart","test-expected":"came from a passing test run","auth-expired":"were an expired session the client recovered from"},G=5;export function combineVerdicts(t,e=t.length,s="occurrences"){if(!t.length)return T;const n=t.filter(h=>h.verdict==="not-a-bug"),i=t.filter(h=>h.verdict==="bug"),r=new Map;for(const h of n)r.set(h.kind,(r.get(h.kind)??0)+1);const o=[...r].sort((h,f)=>f[1]-h[1])[0]?.[0];if(i.length){const h=i.find(g=>g.overridden)?.overridden,f=o?`${n.length} of ${t.length} ${s} ${J[o]}; ${i.length} did not`:i.find(g=>g.note)?.note;return{verdict:"bug",...f?{note:f}:{},...h?{overridden:h}:{}}}const u=t.find(h=>h.verdict==="unsure");if(u)return u;const l=e-t.length;if(l>0)return{verdict:"unsure",kind:o,missing:`${l} older occurrence${l===1?" is":"s are"} no longer held to check`};const d=[];for(const h of n)for(const f of h.evidence)d.length<G&&!d.some(g=>g.line===f.line)&&d.push(f);const w=n.find(h=>h.kind===o);return{verdict:"not-a-bug",kind:o,line:`${w.line}${d.length>1?` (and ${d.length-1} more)`:""}`,evidence:d}}p(combineVerdicts,"combineVerdicts"),c(combineVerdicts,"combineVerdicts");export const ERROR_JUDGEMENT_ASK=`"isBug": { "verdict": "bug" | "not-a-bug" | "unsure", "kind": ${NOT_A_BUG_KINDS.map(t=>`"${t}"`).join(" | ")} | "other" (only for not-a-bug), "why": "one line, citing the evidence" } \u2014 not-a-bug only when the evidence shows it is no defect: a service stopping or restarting, a test that expected it, a session that expired and the client recovered; unsure when the evidence cannot tell`;export function readErrorJudgement(t){if(!v(t))return{verdict:"unsure",why:"the review gave no verdict"};const e=a(t.why,400),s=t.verdict;if(s!=="bug"&&s!=="not-a-bug"&&s!=="unsure")return{verdict:"unsure",why:"the review's verdict was not one of bug, not-a-bug, unsure"};if(!e)return{verdict:"unsure",why:`the review said ${s} without saying why`};if(s!=="not-a-bug")return{verdict:s,why:e};const n=NOT_A_BUG_KINDS.includes(t.kind)?t.kind:"other";return{verdict:s,kind:n,why:e}}p(readErrorJudgement,"readErrorJudgement"),c(readErrorJudgement,"readErrorJudgement");
|
package/lib/event-loop.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
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");
|
package/lib/expected-failure.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var G=Object.defineProperty;var h=(t,e)=>G(t,"name",{value:e,configurable:!0});var J=Object.defineProperty,l=h((t,e)=>J(t,"name",{value:e,configurable:!0}),"h"),V=Object.defineProperty,p=l((t,e)=>V(t,"name",{value:e,configurable:!0}),"h"),Z=Object.defineProperty,m=p((t,e)=>Z(t,"name",{value:e,configurable:!0}),"h"),Q=Object.defineProperty,c=m((t,e)=>Q(t,"name",{value:e,configurable:!0}),"d");import{LENS_EVENT_SOURCE as Y}from"./error-dismissal.js";export const EXPECTED_RULE_SET="expected-rule-set",EXPECTED_RULE_REMOVED="expected-rule-removed";const U=new Set(["dashboard","cli","agent"]),v=60*6e4;export const EXPECTED_RULE_DEFAULT_TTL_MS=168*v,EXPECTED_RULE_MAX_TTL_MS=720*v,EXPECTED_RULE_MIN_REASON_CHARS=8,MAX_EXPECTED_REASON_CHARS=500;const k=300,ee=300,z=120,te=200,X=20,f=c(t=>!!t&&typeof t=="object"&&!Array.isArray(t),"isObj"),b=c((t,e)=>typeof t=="string"&&t.trim()?t.trim().slice(0,e):void 0,"text"),S=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(!f(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 i=t[r];if(i==null||i==="")continue;if(typeof i!="string")return{error:`\`${r}\` must be text`};const o=i.trim();if(o.length>k)return{error:`\`${r}\` is longer than ${k} characters`};o&&(e[r]=o)}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=f(s)?b(s.name,100):void 0,i=f(s)?typeof s.value=="number"?String(s.value):b(s.value,k):void 0;if(!r||!i)return{error:"`attribute` needs a `name` and a `value` (one attribute of the flow, such as a tenant id)"};e.attribute={name:r,value:i}}return EXPECTED_SCOPE_FIELDS.some(r=>S(e[r]))?e.status===void 0&&!S(e.error)&&!S(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"),l(checkExpectedMatch,"checkExpectedMatch"),p(checkExpectedMatch,"checkExpectedMatch"),m(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"),l(describeExpectedMatch,"describeExpectedMatch"),p(describeExpectedMatch,"describeExpectedMatch"),m(describeExpectedMatch,"describeExpectedMatch"),c(describeExpectedMatch,"describeExpectedMatch");export function readExpectedRule(t){if(t.source!==Y||!f(t.raw))return;const e=t.raw,s=b(e.id,z);if(!s)return;if(e.kind===EXPECTED_RULE_REMOVED)return{kind:EXPECTED_RULE_REMOVED,id:s,...U.has(e.by)?{by:e.by}:{}};if(e.kind!==EXPECTED_RULE_SET||!U.has(e.by))return;const r=b(e.reason,MAX_EXPECTED_REASON_CHARS);if(!r)return;const i=checkExpectedMatch(e.match);if("error"in i)return;const o=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:o+EXPECTED_RULE_DEFAULT_TTL_MS,a=b(e.title,ee);return{kind:EXPECTED_RULE_SET,id:s,match:i.match,reason:r,by:e.by,createdAt:o,expiresAt:Math.min(u,o+EXPECTED_RULE_MAX_TTL_MS),...a?{title:a}:{}}}h(readExpectedRule,"readExpectedRule"),l(readExpectedRule,"readExpectedRule"),p(readExpectedRule,"readExpectedRule"),m(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*v),EXPECTED_RULE_MAX_TTL_MS)}h(expectedRuleTtlMs,"expectedRuleTtlMs"),l(expectedRuleTtlMs,"expectedRuleTtlMs"),p(expectedRuleTtlMs,"expectedRuleTtlMs"),m(expectedRuleTtlMs,"expectedRuleTtlMs"),c(expectedRuleTtlMs,"expectedRuleTtlMs");function R(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(R,"R"),l(R,"j"),p(R,"F"),m(R,"z"),c(R,"hashOf");export function readRepositoryExpectedRules(t,e){const s=[],r=[];return t==null?{rules:s,problems:r}:Array.isArray(t)?(t.forEach((i,o)=>{if(!f(i))return void r.push(`expectedFailures[${o}] is not an object`);const u=checkExpectedMatch(f(i.match)?i.match:i);if("error"in u)return void r.push(`expectedFailures[${o}]: ${u.error}`);const a=b(i.reason,MAX_EXPECTED_REASON_CHARS);if(!a)return void r.push(`expectedFailures[${o}] has no reason \u2014 say why it is expected`);const d=`repository:${b(i.id,z)??R(JSON.stringify(u.match))}`;if(s.some(x=>x.id===d))return void r.push(`expectedFailures[${o}] 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"),l(readRepositoryExpectedRules,"readRepositoryExpectedRules"),p(readRepositoryExpectedRules,"readRepositoryExpectedRules"),m(readRepositoryExpectedRules,"readRepositoryExpectedRules"),c(readRepositoryExpectedRules,"readRepositoryExpectedRules");const n=c(t=>typeof t=="string"&&t?t:void 0,"str"),T=c(t=>typeof t=="number"&&Number.isFinite(t)?t:void 0,"num"),K=c(t=>{const e=t.split(/[?#]/)[0]??t,s=/^[a-z][a-z0-9+.-]*:\/\/[^/]+(\/.*)?$/i.exec(e);return s?s[1]??"/":e},"pathOf"),se=new Set(["sessionId","flowId","requestId","parentRequestId","runId","traceparent","originNodeId","causedByNodeId","userActionId","browserContextId","frameId","tabId","url","route","projectName"]),N=24;export function eventAttributes(t){let e;const s=c((a,d)=>{if(e&&Object.keys(e).length>=N)return;const x=typeof d=="string"?d:typeof d=="number"||typeof d=="boolean"?String(d):void 0;x===void 0||x.length>k||((e??={})[a]=x)},"put"),r=t.context??{};for(const a of Object.keys(r))se.has(a)||s(a,r[a]);const i=f(t.raw)?t.raw:void 0;if(!i)return e;const o=f(i.span)?i.span:void 0,u=f(i.request)?i.request:void 0;for(const a of[i.attributes,o?.attributes,u?.attributes,i.data,Array.isArray(o?.args)?o?.args[0]:o?.args])if(f(a))for(const d of Object.keys(a))s(d,a[d]);return e}h(eventAttributes,"eventAttributes"),l(eventAttributes,"eventAttributes"),p(eventAttributes,"eventAttributes"),m(eventAttributes,"eventAttributes"),c(eventAttributes,"eventAttributes");export function failureFacts(t){const e=f(t.raw)?t.raw:{},s=t.context??{},r=f(e.request)?e.request:{},i=f(e.span)?e.span:{},o=f(r.error)?r.error:{},u=f(i.error)?i.error:{},a=f(e.error)?e.error:{},d=n(e.kind),x=[],j=n(r.route)??(d==="egress"?n(e.path):void 0);j&&x.push(j);const A=n(e.url)??n(r.url);A&&x.push(K(A)),d!=="server-request"&&n(s.route)&&x.push(n(s.route));const g=[];if(d==="queue-failed"||d==="queue-enqueued"){const M=n(e.queue),O=e.jobId===void 0||e.jobId===null?void 0:String(e.jobId);M&&g.push(`job:${M}`),O&&g.push(`job:${O}`),M&&O&&g.push(`job:${M}#${O}`),n(e.name)&&g.push(`job:${n(e.name)}`)}const w=[o.errorKey,u.errorKey,a.errorKey,e.errorKey,o.reason,u.reason].map(n).filter(M=>!!M),F=n(o.message)??n(t.message)??n(u.message)??n(a.message)??n(e.failedReason)??n(e.error)??n(e.message)??n(t.title),B=T(r.status)??T(e.status),L=n(s.flowId)??n(i.flowId)??n(r.flowId),H=n(s.requestId)??n(r.requestId)??n(i.requestId),D=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)}:{},...x.length?{routes:x}:{},...n(i.name)?{span:n(i.name)}:{},...L?{flowId:L}:{},...g.length?{flowNames:g}:{},...B!==void 0?{status:B}:{},...n(o.name)??n(u.name)??n(a.name)?{errorName:n(o.name)??n(u.name)??n(a.name)}:{},...w.length?{errorKeys:w}:{},...F?{message:F}:{},...D?{attributes:D}:{},...H?{requestId:H}:{}}}h(failureFacts,"failureFacts"),l(failureFacts,"failureFacts"),p(failureFacts,"failureFacts"),m(failureFacts,"failureFacts"),c(failureFacts,"failureFacts");export class FailureContextIndex{static{h(this,"FailureContextIndex")}static{l(this,"FailureContextIndex")}static{p(this,"FailureContextIndex")}static{m(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=f(e.raw)?e.raw:void 0,r=e.context??{},i=n(r.flowId);if(i&&(s?.attributes!==void 0||f(s?.span)||r.tenantIdHash!==void 0||r.userIdHash!==void 0||s?.data!==void 0)){const A=eventAttributes(e);if(A){const g=this.flows.get(i);this.flows.delete(i);const w={...g??{},...A};this.flows.set(i,Object.keys(w).length>N?Object.fromEntries(Object.entries(w).slice(-N)):w),this.flows.size>this.maxFlows&&this.flows.delete(this.flows.keys().next().value)}}const o=n(s?.kind);if(!s||o!=="server-request"&&o!=="gateway-request")return;const u=f(s.request)?s.request:s,a=n(r.requestId)??n(u.requestId);if(!a)return;const d=this.requests.get(a)??{},x=n(u.url),j={...d,...n(s.project)&&(o==="server-request"||!d.service)?{service:n(s.project)}:{},...n(u.method)?{method:n(u.method)}:{},...o==="server-request"&&n(u.route)?{route:n(u.route)}:{},...x?{path:K(x)}:{},...T(u.status)!==void 0&&(o==="server-request"||d.status===void 0)?{status:T(u.status)}:{}};return this.requests.delete(a),this.requests.set(a,j),this.requests.size>this.maxRequests&&this.requests.delete(this.requests.keys().next().value),o==="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 i=[...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}:{},...i.length?{routes:[...new Set(i)]}:{},...e.status??s?.status!==void 0?{status:e.status??s?.status}:{},...r||e.attributes?{attributes:{...r??{},...e.attributes??{}}}:{}}}}const C=new Map,P=c((t,e)=>t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,e).replace(/\?/g,"."),"globBody");function y(t,e="whole"){const s=`${e}\0${t}`;let r=C.get(s);return r||(r=e==="whole"?new RegExp(`^${P(t,"[\\s\\S]*")}$`,"i"):e==="anywhere"?new RegExp(P(t,"[\\s\\S]*"),"i"):new RegExp(`(?:^|[^\\w.])${P(t,"[\\w.]*")}(?:$|[^\\w.])`,"i"),C.size>1e3&&C.clear(),C.set(s,r)),r}h(y,"w"),l(y,"E"),p(y,"M"),m(y,"S"),c(y,"globRe");const E=c((t,e)=>e!==void 0&&y(t).test(e),"glob");function I(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(i=>E(r[2],i)):s.some(i=>E(t,i))}h(I,"_"),l(I,"T"),p(I,"D"),m(I,"B"),c(I,"routeMatches");function $(t,e){const s=[e.flowId,...e.flowNames??[]].filter(i=>!!i),r=t.endsWith(":")?`${t}*`:t;return s.some(i=>E(r,i))}h($,"C"),l($,"O"),p($,"L"),m($,"G"),c($,"flowMatches");function q(t,e){return E(t,e.errorName)||(e.errorKeys??[]).some(s=>E(t,s))?!0:e.message!==void 0&&y(t,"word").test(e.message)}h(q,"O"),l(q,"N"),p(q,"U"),m(q,"W"),c(q,"errorMatches");export function expectedMatches(t,e){return!(t.service!==void 0&&!E(t.service,e.service)||t.route!==void 0&&!I(t.route,e)||t.span!==void 0&&!E(t.span,e.span)||t.flow!==void 0&&!$(t.flow,e)||t.status!==void 0&&e.status!==t.status||t.error!==void 0&&!q(t.error,e)||t.message!==void 0&&!(e.message!==void 0&&y(t.message,"anywhere").test(e.message))||t.attribute!==void 0&&!E(t.attribute.value,e.attributes?.[t.attribute.name]))}h(expectedMatches,"expectedMatches"),l(expectedMatches,"expectedMatches"),p(expectedMatches,"expectedMatches"),m(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"),l(expectedMatchIsPerOccurrence,"expectedMatchIsPerOccurrence"),p(expectedMatchIsPerOccurrence,"expectedMatchIsPerOccurrence"),m(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}:{},i=t.message?.split(`
|
|
2
|
-
`)[0]?.replace(/\d+/g,"*").replace(/\*+/g,"*").slice(0,120).trim(),
|
|
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");
|
package/lib/flood-guard.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
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");
|
package/lib/follow-ups.d.ts
CHANGED
|
@@ -110,6 +110,8 @@ export interface DashFollowUpProposal {
|
|
|
110
110
|
suggestions?: string[];
|
|
111
111
|
/** Open proposals it replaces (Reorganize all): made a goal, they read «combined». */
|
|
112
112
|
replaces?: string[];
|
|
113
|
+
/** The backlog items it covers (`bl-…`, Reorganize all): made a goal, they read `goal`. */
|
|
114
|
+
backlog?: string[];
|
|
113
115
|
/** The finished goals its items come from, by title. */
|
|
114
116
|
goals: Array<{
|
|
115
117
|
id: string;
|
|
@@ -223,6 +225,8 @@ export interface DashFollowUpEstimate {
|
|
|
223
225
|
items: number;
|
|
224
226
|
suggestions: number;
|
|
225
227
|
proposals: number;
|
|
228
|
+
/** Open backlog items it reads (Reorganize all). */
|
|
229
|
+
backlog?: number;
|
|
226
230
|
notRead?: string[];
|
|
227
231
|
model: string;
|
|
228
232
|
inputTokens: number;
|
package/lib/goal-design.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
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");
|
package/lib/host-agents.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var A=Object.defineProperty;var
|
|
1
|
+
"use strict";var A=Object.defineProperty;var s=(t,e)=>A(t,"name",{value:e,configurable:!0});var c=Object.defineProperty,o=s((t,e)=>c(t,"name",{value:e,configurable:!0}),"o");export const HOST_AGENT_CLIENTS=["claude","codex"],HOST_AGENTS_FILES={agents:"host-agents.json",ceilings:"host-ceilings.json"},HOST_AGENTS_LIMITS={accounts:32,windows:6,label:60,why:300,plan:40,name:40,agents:64},HOST_ACCOUNT_ID=/^ac-[a-z0-9]{1,12}-[a-f0-9]{6}$/;const n=[/\bsk-[A-Za-z0-9_-]{16,}/,/\b[rs]k_(?:live|test)_[A-Za-z0-9]{12,}/,/\bgh[pousr]_[A-Za-z0-9]{20,}|\bgithub_pat_[A-Za-z0-9_]{20,}/,/\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/,/\bxox[abposr]-[A-Za-z0-9-]{10,}/,/\bAIza[0-9A-Za-z_-]{30,}/,/\beyJ[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{4,}/,/-----BEGIN [A-Z ]*(?:PRIVATE KEY|CERTIFICATE)-----/,/\bbearer\s+[A-Za-z0-9._~+/=-]{12,}/i],r=/[A-Za-z0-9+/_=-]{32,}/g;export function tokenShaped(t){if(n.some(e=>e.test(t)))return!0;for(const e of t.match(r)??[])if(/\d/.test(e)&&/[A-Za-z]/.test(e))return!0;return!1}s(tokenShaped,"tokenShaped"),o(tokenShaped,"tokenShaped");export function withoutTokens(t){let e=t;for(const a of n)e=e.replace(new RegExp(a.source,a.flags.includes("g")?a.flags:`${a.flags}g`),"\u2026");return e.replace(r,a=>/\d/.test(a)&&/[A-Za-z]/.test(a)?"\u2026":a)}s(withoutTokens,"withoutTokens"),o(withoutTokens,"withoutTokens");
|
package/lib/hosts.d.ts
CHANGED
|
@@ -42,6 +42,8 @@ export interface HostVersionView {
|
|
|
42
42
|
at: number;
|
|
43
43
|
/** The waiting-for-person state's: the organizer's version is in the worker's store already. */
|
|
44
44
|
stored?: boolean;
|
|
45
|
+
/** The version folder the worker's launchd agent pins (written by an older install-agent): `detail` says what to run. */
|
|
46
|
+
launchdPins?: string;
|
|
45
47
|
}
|
|
46
48
|
/** A link between two Macs, as one side last saw it. */
|
|
47
49
|
export interface HostLinkView {
|
package/lib/lint-coverage.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var k=Object.defineProperty;var
|
|
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
|
|
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");
|
package/lib/metrics-reset.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
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");
|
package/lib/overseer-findings.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
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/peers.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
|
-
import { type DockerRunState, type DockerVmRead } from './docker-jobs.js';
|
|
2
|
+
import { type DockerRunState, type DockerVmRead, type LensJobLinkLoss } from './docker-jobs.js';
|
|
3
3
|
import type { HostAgentsAdvert } from './host-agents.js';
|
|
4
4
|
import type { WorkspaceActionLane, WorkspaceActionState } from './workspace-actions.js';
|
|
5
5
|
/**
|
|
@@ -67,6 +67,14 @@ export declare const PEER_PATHS: {
|
|
|
67
67
|
/** What a remote run streams to the organizer (§ 10; slice D16). */
|
|
68
68
|
export type RunUploadKind = 'log' | 'samples' | 'events' | 'artifacts';
|
|
69
69
|
export declare const RUN_UPLOAD_KINDS: readonly RunUploadKind[];
|
|
70
|
+
/**
|
|
71
|
+
* The headers of a log, samples or events upload that name the bytes of the worker's file it carries, `from` up to `to`
|
|
72
|
+
* (overseer-104): the organizer keeps only what follows what it holds, and answers how far it holds (`held`).
|
|
73
|
+
*/
|
|
74
|
+
export declare const RUN_UPLOAD_RANGE: {
|
|
75
|
+
readonly from: "x-lensmcp-from";
|
|
76
|
+
readonly to: "x-lensmcp-to";
|
|
77
|
+
};
|
|
70
78
|
/**
|
|
71
79
|
* `~/.lensmcp/peers/` (0700; every file 0600) — under `LENSMCP_HOME` when it is set (plan «The contract»):
|
|
72
80
|
*
|
|
@@ -329,6 +337,8 @@ export interface JobOffer {
|
|
|
329
337
|
proof?: boolean;
|
|
330
338
|
/** The longest it may run, minutes: the person's `--timeout`, else the commit's own. */
|
|
331
339
|
timeoutMinutes?: number;
|
|
340
|
+
/** A dropped link (overseer-104): cancelled at once, or how long it goes on — as the organizer read it. None: 15 minutes. */
|
|
341
|
+
onLinkLoss?: LensJobLinkLoss;
|
|
332
342
|
/**
|
|
333
343
|
* The provider keys the job names in `inputs.secrets`, by name → value — ONLY for a paid run the person authorized
|
|
334
344
|
* (`--allow-paid` from their own terminal, § 10). Written 0600 in the run folder, redacted from every log the worker
|
|
@@ -1287,6 +1297,9 @@ export declare const PEER_WORK_SCHEMAS: {
|
|
|
1287
1297
|
vmMb: z.ZodOptional<z.ZodNumber>;
|
|
1288
1298
|
proof: z.ZodOptional<z.ZodBoolean>;
|
|
1289
1299
|
timeoutMinutes: z.ZodOptional<z.ZodNumber>;
|
|
1300
|
+
onLinkLoss: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<"cancel">, z.ZodObject<{
|
|
1301
|
+
continueMinutes: z.ZodNumber;
|
|
1302
|
+
}, z.core.$strict>]>>;
|
|
1290
1303
|
secrets: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
|
|
1291
1304
|
origin: z.ZodOptional<z.ZodString>;
|
|
1292
1305
|
}, z.core.$strict>;
|