@tenhaw/delivery-metrics 0.0.0-stage → 1.0.0

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Tenhaw
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,15 @@
1
+ Tenhaw AI Readiness Framework and authored framework content in spec/content
2
+ are licensed under the Creative Commons Attribution 4.0 International licence.
3
+ Copyright (c) 2026 Tenhaw.
4
+
5
+ Licence: https://creativecommons.org/licenses/by/4.0/
6
+ Legal code: https://creativecommons.org/licenses/by/4.0/legalcode.en
7
+
8
+ When sharing or adapting this content, provide appropriate credit, a licence
9
+ link, and an indication of changes. A suitable credit is:
10
+ "Tenhaw AI Readiness Framework, CC BY 4.0, https://tenhaw.com."
11
+
12
+ Numerical results and user-supplied evidence remain the user's material.
13
+ The optional audit promotion can be suppressed independently of applicable
14
+ framework-content credits. Code is MIT; third-party sources retain their own
15
+ rights and are summarised with links rather than relicensed here.
package/README.md CHANGED
@@ -1,3 +1,34 @@
1
- # Temporary Holding Version
1
+ # @tenhaw/delivery-metrics
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Compute five DORA performance metrics and flow measures from explicitly linked events.
4
+
5
+ ## When to use
6
+
7
+ - Use this when building a service delivery dashboard from GitHub, Jira or offline delivery events.
8
+ - Do not use this for ranking unrelated teams, inferring deployments from merges or inventing missing recovery data.
9
+
10
+ ## Install
11
+
12
+ ```sh
13
+ npm install @tenhaw/delivery-metrics
14
+ ```
15
+
16
+ ## Quick start
17
+
18
+ ```ts
19
+ import { computeMetrics } from '@tenhaw/delivery-metrics';
20
+ const report = computeMetrics([], { since: '2026-01-01T00:00:00Z', until: '2026-02-01T00:00:00Z' });
21
+ console.log(report.metrics.changeLeadTime.value); // null
22
+ ```
23
+
24
+ ## API
25
+
26
+ `computeMetrics(events,{since,until,productionEnvironment?,service?})`, `scoreDeliveryHealth(report)`, `renderDeliveryReport(report,format,options?)`. Event types: commit, deployment, incident, work-item and pull-request. See bundled `delivery-events` schema. Local-only collectors are exported from `@tenhaw/delivery-metrics/collectors`; no tokens enter the pure scoring API.
27
+
28
+ ## Methodology and sources
29
+
30
+ DORA source: https://dora.dev/guides/dora-metrics/. Computes deployment frequency, change lead time, change fail rate, failed deployment recovery time and deployment rework rate. Deployment frequency is deployments per calendar day. Durations are means in hours. Periods are half-open `[since,until)` with explicit timezones. One service per report prevents context mixing. Only observed production deployments count; proxy deployments are excluded. First observed successful commit delivery determines change lead time. Failure rate assumes supplied statuses and incident links are complete. Recovery needs linked incident/restoration timestamps. Rework rate requires a classification for every deployment. Flow WIP is a period-end observation. Missing samples are null, not zero. No composite industry score is invented.
31
+
32
+ ## Built by Tenhaw
33
+
34
+ Tenhaw is a founder-led UK AI consultancy and venture studio. For expert help applying this, [book an AI readiness audit](https://tenhaw.com/contact?utm_source=npm&utm_medium=readme&utm_campaign=tenhaw-kit&utm_content=delivery-metrics#book).
@@ -0,0 +1,29 @@
1
+ import { DeliveryEvent } from './index.js';
2
+ import '@tenhaw/core';
3
+
4
+ declare class CollectorError extends Error {
5
+ readonly exitCode: 3 | 4;
6
+ constructor(message: string, exitCode?: 3 | 4);
7
+ }
8
+ type Context = {
9
+ fetch?: typeof fetch;
10
+ env?: NodeJS.ProcessEnv;
11
+ sleep?: (ms: number) => Promise<void>;
12
+ cacheDir?: string;
13
+ };
14
+ type Options = {
15
+ since: string;
16
+ until?: string;
17
+ noCache?: boolean;
18
+ };
19
+ declare function collectGithub(options: Options & {
20
+ repos: string[];
21
+ }, context?: Context): Promise<DeliveryEvent[]>;
22
+ declare function collectJira(options: Options & {
23
+ jql: string;
24
+ config?: {
25
+ statusToStage?: Record<string, string>;
26
+ };
27
+ }, context?: Context): Promise<DeliveryEvent[]>;
28
+
29
+ export { CollectorError, collectGithub, collectJira };
@@ -0,0 +1,201 @@
1
+ // src/collectors.ts
2
+ import { createHmac } from "crypto";
3
+ import { mkdir, readFile, rename, stat, writeFile } from "fs/promises";
4
+ import { join } from "path";
5
+ var CollectorError = class extends Error {
6
+ constructor(message, exitCode = 3) {
7
+ super(message);
8
+ this.exitCode = exitCode;
9
+ this.name = "CollectorError";
10
+ }
11
+ exitCode;
12
+ };
13
+ var delay = (ms) => new Promise((r) => setTimeout(r, ms));
14
+ function required(env, name) {
15
+ const value = env[name];
16
+ if (!value) throw new CollectorError(`Set ${name} for local collection.`, 4);
17
+ return value;
18
+ }
19
+ function redact(value, secrets) {
20
+ if (typeof value === "string") return secrets.reduce((v, s) => s ? v.split(s).join("[redacted]") : v, value);
21
+ if (Array.isArray(value)) return value.map((v) => redact(v, secrets));
22
+ if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, redact(v, secrets)]));
23
+ return value;
24
+ }
25
+ function date(value) {
26
+ const n = Date.parse(value);
27
+ if (!Number.isFinite(n) || !/(Z|[+-]\d\d:\d\d)$/.test(value)) throw new CollectorError("Collection dates need ISO timestamps with a timezone.");
28
+ return n;
29
+ }
30
+ async function request(url, headers, context) {
31
+ for (let attempt = 0; attempt < 5; attempt++) {
32
+ let response;
33
+ try {
34
+ response = await (context.fetch ?? fetch)(url, { headers, redirect: "error", signal: AbortSignal.timeout(2e4) });
35
+ } catch {
36
+ if (attempt === 4) throw new CollectorError("Upstream request failed after retries.");
37
+ await (context.sleep ?? delay)(Math.min(2 ** attempt, 8) * 1e3);
38
+ continue;
39
+ }
40
+ if (response.status === 429 || response.status >= 500 || response.status === 403 && response.headers.get("x-ratelimit-remaining") === "0") {
41
+ if (attempt === 4) throw new CollectorError(`Upstream HTTP ${response.status} after retries.`);
42
+ const raw = response.headers.get("retry-after");
43
+ const seconds = raw ? Number.isFinite(Number(raw)) ? Number(raw) : Math.max(0, (Date.parse(raw) - Date.now()) / 1e3) : 2 ** attempt;
44
+ if (!Number.isFinite(seconds) || seconds > 60) throw new CollectorError("Upstream rate limit requires a wait longer than 60 seconds.");
45
+ await (context.sleep ?? delay)(Math.max(0, seconds) * 1e3);
46
+ continue;
47
+ }
48
+ if (!response.ok) throw new CollectorError(`Upstream returned HTTP ${response.status}.`);
49
+ try {
50
+ return await response.json();
51
+ } catch {
52
+ throw new CollectorError("Upstream returned invalid JSON.");
53
+ }
54
+ }
55
+ throw new CollectorError("Upstream retries exhausted.");
56
+ }
57
+ async function cached(identity, secrets, options, ctx, load) {
58
+ const principalKey = secrets.reduce((tag, secret) => createHmac("sha256", secret).update(tag).digest("hex"), "tenhaw-kit-cache-principal-v1");
59
+ const key = createHmac("sha256", principalKey).update(JSON.stringify(identity)).digest("hex");
60
+ const directory = ctx.cacheDir ?? ".tenhaw/cache", file = join(directory, `${key}.json`);
61
+ if (!options.noCache) try {
62
+ if (Date.now() - (await stat(file)).mtimeMs < 3e5) {
63
+ const value = JSON.parse(await readFile(file, "utf8"));
64
+ if (Array.isArray(value)) return redact(value, secrets);
65
+ }
66
+ } catch {
67
+ }
68
+ const events = redact(await load(), secrets);
69
+ if (!options.noCache) {
70
+ await mkdir(directory, { recursive: true, mode: 448 });
71
+ const temporary = `${file}.${process.pid}.tmp`;
72
+ await writeFile(temporary, JSON.stringify(events), { mode: 384 });
73
+ await rename(temporary, file);
74
+ }
75
+ return events;
76
+ }
77
+ async function collectGithub(options, context = {}) {
78
+ const token = required(context.env ?? process.env, "GITHUB_TOKEN");
79
+ const start = date(options.since), end = date(options.until ?? (/* @__PURE__ */ new Date()).toISOString());
80
+ if (end <= start || !options.repos.length || options.repos.some((r) => !/^[-\w.]+\/[-\w.]+$/.test(r))) throw new CollectorError("Use owner/repository names and an increasing date range.");
81
+ const headers = { Authorization: `Bearer ${token}`, Accept: "application/vnd.github+json", "X-GitHub-Api-Version": "2022-11-28" };
82
+ const get = (path, params = {}) => {
83
+ const url = new URL(path, "https://api.github.com");
84
+ for (const [k, v] of Object.entries(params)) url.searchParams.set(k, v);
85
+ return request(url, headers, context);
86
+ };
87
+ const pages = async (path, params = {}) => {
88
+ const rows = [];
89
+ for (let page = 1; page <= 1e3; page++) {
90
+ const data = await get(path, { ...params, per_page: "100", page: String(page) });
91
+ if (!Array.isArray(data)) throw new CollectorError("Unexpected GitHub response shape.");
92
+ rows.push(...data);
93
+ if (data.length < 100) return rows;
94
+ }
95
+ throw new CollectorError("GitHub pagination limit reached; narrow the collection.");
96
+ };
97
+ return cached(["github", options], [token], options, context, async () => {
98
+ const events = [];
99
+ for (const repo of options.repos) {
100
+ const base = `/repos/${repo}`, commits = /* @__PURE__ */ new Map();
101
+ const deployments = await pages(`${base}/deployments`);
102
+ const defaultBranch = !deployments.length ? (await get(base)).default_branch : void 0;
103
+ for (const deployment of deployments) {
104
+ if (!deployment.created_at || date(deployment.created_at) >= end) continue;
105
+ const statuses = await pages(`${base}/deployments/${deployment.id}/statuses`);
106
+ const final = statuses.find((s) => ["success", "failure", "error"].includes(s.state) && s.created_at && date(s.created_at) < end);
107
+ if (!final?.created_at || date(final.created_at) < start || date(final.created_at) >= end) continue;
108
+ const changeFailure = deployment.payload?.tenhaw?.changeFailure === true;
109
+ if (final.state !== "success" && !changeFailure) continue;
110
+ const sha = String(deployment.sha ?? "");
111
+ if (sha && !commits.has(sha)) {
112
+ const commit = await get(`${base}/commits/${encodeURIComponent(sha)}`), timestamp = commit.commit?.committer?.date;
113
+ if (timestamp) commits.set(sha, { id: `${repo}:commit:${sha}`, type: "commit", timestamp, service: repo });
114
+ }
115
+ events.push({ id: `${repo}:deployment:${deployment.id}`, type: "deployment", timestamp: final.created_at, service: repo, environment: deployment.environment ?? "production", commitIds: commits.has(sha) ? [`${repo}:commit:${sha}`] : [], status: changeFailure ? "failed" : "success", ...typeof deployment.payload?.tenhaw?.rework === "boolean" ? { rework: deployment.payload.tenhaw.rework } : {} });
116
+ }
117
+ const pulls = await pages(`${base}/pulls`, { state: "closed", sort: "updated", direction: "desc" });
118
+ for (const pull of pulls) {
119
+ if (!pull.merged_at || date(pull.merged_at) < start || date(pull.merged_at) >= end) continue;
120
+ const detail = await get(`${base}/pulls/${pull.number}`), reviews = await pages(`${base}/pulls/${pull.number}/reviews`);
121
+ const first = reviews.filter((r) => r.submitted_at && date(r.submitted_at) <= date(pull.merged_at)).sort((a, b) => date(a.submitted_at) - date(b.submitted_at))[0];
122
+ events.push({ id: `${repo}:pr:${pull.number}`, type: "pull-request", service: repo, createdAt: pull.created_at, mergedAt: pull.merged_at, ...first ? { firstReviewAt: first.submitted_at } : {}, ...Number.isInteger(detail.additions) ? { additions: detail.additions } : {}, ...Number.isInteger(detail.deletions) ? { deletions: detail.deletions } : {} });
123
+ if (!deployments.length && pull.base?.ref === defaultBranch) events.push({ id: `${repo}:merge-proxy:${pull.number}`, type: "deployment", timestamp: pull.merged_at, service: repo, environment: "production", commitIds: [], status: "success", proxy: true });
124
+ }
125
+ for (const issue of await pages(`${base}/issues`, { labels: "incident", state: "all", since: options.since })) {
126
+ if (issue.pull_request) continue;
127
+ const body = String(issue.body ?? ""), deploymentId = /tenhaw-deployment:\s*(\S+)/i.exec(body)?.[1], startedAt = /tenhaw-started:\s*(\S+)/i.exec(body)?.[1], restoredAt = /tenhaw-restored:\s*(\S+)/i.exec(body)?.[1];
128
+ if (!deploymentId || !startedAt) continue;
129
+ date(startedAt);
130
+ if (restoredAt) date(restoredAt);
131
+ events.push({ id: `${repo}:incident:${issue.number}`, type: "incident", service: repo, deploymentId: `${repo}:deployment:${deploymentId}`, startedAt, ...restoredAt ? { restoredAt } : {} });
132
+ }
133
+ events.push(...commits.values());
134
+ }
135
+ return events;
136
+ });
137
+ }
138
+ async function collectJira(options, context = {}) {
139
+ const env = context.env ?? process.env, token = required(env, "JIRA_API_TOKEN"), email = required(env, "JIRA_EMAIL"), origin = required(env, "JIRA_BASE_URL");
140
+ let base;
141
+ try {
142
+ base = new URL(origin);
143
+ } catch {
144
+ throw new CollectorError("JIRA_BASE_URL must be a Jira Cloud HTTPS origin.");
145
+ }
146
+ if (base.protocol !== "https:" || !base.hostname.endsWith(".atlassian.net") || base.username || base.password || base.search || base.hash || base.pathname !== "/") throw new CollectorError("JIRA_BASE_URL must be a Jira Cloud HTTPS origin.");
147
+ const start = date(options.since), end = date(options.until ?? (/* @__PURE__ */ new Date()).toISOString());
148
+ if (end <= start) throw new CollectorError("Use an increasing date range.");
149
+ const mapping = Object.fromEntries(Object.entries(options.config?.statusToStage ?? {}).map(([k, v]) => [k.toLowerCase(), v]));
150
+ if (!Object.keys(mapping).length) throw new CollectorError("Jira collection requires config.statusToStage mappings for active and done statuses.");
151
+ if (Object.values(mapping).some((v) => !["todo", "active", "waiting", "done"].includes(v))) throw new CollectorError("Status stages must be todo, active, waiting or done.");
152
+ const headers = { Authorization: `Basic ${Buffer.from(`${email}:${token}`).toString("base64")}`, Accept: "application/json" };
153
+ const get = (path, params = {}) => {
154
+ const url = new URL(path, base);
155
+ for (const [k, v] of Object.entries(params)) url.searchParams.set(k, v);
156
+ return request(url, headers, context);
157
+ };
158
+ return cached(["jira", origin, options, mapping], [token, email], options, context, async () => {
159
+ const events = [], tokens = /* @__PURE__ */ new Set();
160
+ let nextPageToken;
161
+ for (let page = 0; page < 1e3; page++) {
162
+ const response = await get("/rest/api/3/search/jql", { jql: options.jql, maxResults: "100", fields: "created,status,project", ...nextPageToken ? { nextPageToken } : {} });
163
+ if (!Array.isArray(response.issues)) throw new CollectorError("Unexpected Jira response shape.");
164
+ for (const issue of response.issues) {
165
+ const transitions = [];
166
+ let offset = 0;
167
+ for (let page2 = 0; page2 < 1e3; page2++) {
168
+ const data = await get(`/rest/api/3/issue/${encodeURIComponent(issue.id)}/changelog`, { startAt: String(offset), maxResults: "100" });
169
+ if (!Array.isArray(data.values)) throw new CollectorError("Unexpected Jira changelog shape.");
170
+ for (const history of data.values) for (const item of history.items ?? []) if (item.field === "status") transitions.push({ at: history.created, status: item.toString ?? "" });
171
+ offset += data.values.length;
172
+ if (data.isLast || offset >= data.total || !data.values.length) break;
173
+ if (page2 === 999) throw new CollectorError("Jira changelog limit reached.");
174
+ }
175
+ transitions.sort((a, b) => date(a.at) - date(b.at));
176
+ let startedAt, completedAt, previousAt, previousStage = "todo", active = 0;
177
+ for (const transition of transitions) {
178
+ if (date(transition.at) >= end) break;
179
+ const stage = mapping[transition.status.toLowerCase()];
180
+ if (previousStage === "active" && previousAt) active += Math.max(0, date(transition.at) - date(previousAt)) / 6e4;
181
+ if (stage === "active" && !startedAt) startedAt = transition.at;
182
+ if (stage === "done") completedAt = transition.at;
183
+ else if (stage) completedAt = void 0;
184
+ previousAt = transition.at;
185
+ previousStage = stage ?? "unknown";
186
+ }
187
+ if (startedAt && (!completedAt || date(completedAt) >= start)) events.push({ id: `${base.hostname}:${issue.key}`, type: "work-item", service: issue.fields.project.key, startedAt, ...completedAt ? { completedAt, activeMinutes: active } : {} });
188
+ }
189
+ nextPageToken = response.nextPageToken;
190
+ if (response.isLast || !nextPageToken) return events;
191
+ if (tokens.has(nextPageToken)) throw new CollectorError("Jira repeated a pagination token.");
192
+ tokens.add(nextPageToken);
193
+ }
194
+ throw new CollectorError("Jira pagination limit reached; narrow the query.");
195
+ });
196
+ }
197
+ export {
198
+ CollectorError,
199
+ collectGithub,
200
+ collectJira
201
+ };
@@ -0,0 +1,310 @@
1
+ import { AttributionOptions } from '@tenhaw/core';
2
+
3
+ type DeliveryEvent = {
4
+ id: string;
5
+ type: 'commit';
6
+ timestamp: string;
7
+ service: string;
8
+ } | {
9
+ id: string;
10
+ type: 'deployment';
11
+ timestamp: string;
12
+ service: string;
13
+ environment: string;
14
+ commitIds: string[];
15
+ status: 'success' | 'failed';
16
+ rework?: boolean;
17
+ proxy?: boolean;
18
+ } | {
19
+ id: string;
20
+ type: 'incident';
21
+ startedAt: string;
22
+ restoredAt?: string;
23
+ service: string;
24
+ deploymentId: string;
25
+ } | {
26
+ id: string;
27
+ type: 'work-item';
28
+ startedAt: string;
29
+ completedAt?: string;
30
+ service: string;
31
+ activeMinutes?: number;
32
+ } | {
33
+ id: string;
34
+ type: 'pull-request';
35
+ createdAt: string;
36
+ firstReviewAt?: string;
37
+ mergedAt?: string;
38
+ service: string;
39
+ additions?: number;
40
+ deletions?: number;
41
+ };
42
+ type MetricsConfig = {
43
+ since: string;
44
+ until: string;
45
+ productionEnvironment?: string;
46
+ service?: string;
47
+ };
48
+ declare function computeMetrics(input: DeliveryEvent[], cfg: MetricsConfig): {
49
+ period: {
50
+ since: string;
51
+ until: string;
52
+ };
53
+ metrics: {
54
+ deploymentFrequency: {
55
+ value: number | null;
56
+ unit: string;
57
+ sampleSize: number;
58
+ period: {
59
+ since: string;
60
+ until: string;
61
+ };
62
+ dataSource: string;
63
+ caveats: string[];
64
+ };
65
+ changeLeadTime: {
66
+ value: number | null;
67
+ unit: string;
68
+ sampleSize: number;
69
+ period: {
70
+ since: string;
71
+ until: string;
72
+ };
73
+ dataSource: string;
74
+ caveats: string[];
75
+ };
76
+ changeFailRate: {
77
+ value: number | null;
78
+ unit: string;
79
+ sampleSize: number;
80
+ period: {
81
+ since: string;
82
+ until: string;
83
+ };
84
+ dataSource: string;
85
+ caveats: string[];
86
+ };
87
+ failedDeploymentRecoveryTime: {
88
+ value: number | null;
89
+ unit: string;
90
+ sampleSize: number;
91
+ period: {
92
+ since: string;
93
+ until: string;
94
+ };
95
+ dataSource: string;
96
+ caveats: string[];
97
+ };
98
+ deploymentReworkRate: {
99
+ value: number | null;
100
+ unit: string;
101
+ sampleSize: number;
102
+ period: {
103
+ since: string;
104
+ until: string;
105
+ };
106
+ dataSource: string;
107
+ caveats: string[];
108
+ };
109
+ cycleTime: {
110
+ value: number | null;
111
+ unit: string;
112
+ sampleSize: number;
113
+ period: {
114
+ since: string;
115
+ until: string;
116
+ };
117
+ dataSource: string;
118
+ caveats: string[];
119
+ };
120
+ throughput: {
121
+ value: number | null;
122
+ unit: string;
123
+ sampleSize: number;
124
+ period: {
125
+ since: string;
126
+ until: string;
127
+ };
128
+ dataSource: string;
129
+ caveats: string[];
130
+ };
131
+ wip: {
132
+ value: number | null;
133
+ unit: string;
134
+ sampleSize: number;
135
+ period: {
136
+ since: string;
137
+ until: string;
138
+ };
139
+ dataSource: string;
140
+ caveats: string[];
141
+ };
142
+ flowEfficiency: {
143
+ value: number | null;
144
+ unit: string;
145
+ sampleSize: number;
146
+ period: {
147
+ since: string;
148
+ until: string;
149
+ };
150
+ dataSource: string;
151
+ caveats: string[];
152
+ };
153
+ prReviewTime: {
154
+ value: number | null;
155
+ unit: string;
156
+ sampleSize: number;
157
+ period: {
158
+ since: string;
159
+ until: string;
160
+ };
161
+ dataSource: string;
162
+ caveats: string[];
163
+ };
164
+ prSize: {
165
+ value: number | null;
166
+ unit: string;
167
+ sampleSize: number;
168
+ period: {
169
+ since: string;
170
+ until: string;
171
+ };
172
+ dataSource: string;
173
+ caveats: string[];
174
+ };
175
+ };
176
+ caveats: string[];
177
+ };
178
+ type DeliveryReport = ReturnType<typeof computeMetrics>;
179
+ declare function scoreDeliveryHealth(report: DeliveryReport): {
180
+ status: string;
181
+ metrics: {
182
+ deploymentFrequency: {
183
+ value: number | null;
184
+ unit: string;
185
+ sampleSize: number;
186
+ period: {
187
+ since: string;
188
+ until: string;
189
+ };
190
+ dataSource: string;
191
+ caveats: string[];
192
+ };
193
+ changeLeadTime: {
194
+ value: number | null;
195
+ unit: string;
196
+ sampleSize: number;
197
+ period: {
198
+ since: string;
199
+ until: string;
200
+ };
201
+ dataSource: string;
202
+ caveats: string[];
203
+ };
204
+ changeFailRate: {
205
+ value: number | null;
206
+ unit: string;
207
+ sampleSize: number;
208
+ period: {
209
+ since: string;
210
+ until: string;
211
+ };
212
+ dataSource: string;
213
+ caveats: string[];
214
+ };
215
+ failedDeploymentRecoveryTime: {
216
+ value: number | null;
217
+ unit: string;
218
+ sampleSize: number;
219
+ period: {
220
+ since: string;
221
+ until: string;
222
+ };
223
+ dataSource: string;
224
+ caveats: string[];
225
+ };
226
+ deploymentReworkRate: {
227
+ value: number | null;
228
+ unit: string;
229
+ sampleSize: number;
230
+ period: {
231
+ since: string;
232
+ until: string;
233
+ };
234
+ dataSource: string;
235
+ caveats: string[];
236
+ };
237
+ cycleTime: {
238
+ value: number | null;
239
+ unit: string;
240
+ sampleSize: number;
241
+ period: {
242
+ since: string;
243
+ until: string;
244
+ };
245
+ dataSource: string;
246
+ caveats: string[];
247
+ };
248
+ throughput: {
249
+ value: number | null;
250
+ unit: string;
251
+ sampleSize: number;
252
+ period: {
253
+ since: string;
254
+ until: string;
255
+ };
256
+ dataSource: string;
257
+ caveats: string[];
258
+ };
259
+ wip: {
260
+ value: number | null;
261
+ unit: string;
262
+ sampleSize: number;
263
+ period: {
264
+ since: string;
265
+ until: string;
266
+ };
267
+ dataSource: string;
268
+ caveats: string[];
269
+ };
270
+ flowEfficiency: {
271
+ value: number | null;
272
+ unit: string;
273
+ sampleSize: number;
274
+ period: {
275
+ since: string;
276
+ until: string;
277
+ };
278
+ dataSource: string;
279
+ caveats: string[];
280
+ };
281
+ prReviewTime: {
282
+ value: number | null;
283
+ unit: string;
284
+ sampleSize: number;
285
+ period: {
286
+ since: string;
287
+ until: string;
288
+ };
289
+ dataSource: string;
290
+ caveats: string[];
291
+ };
292
+ prSize: {
293
+ value: number | null;
294
+ unit: string;
295
+ sampleSize: number;
296
+ period: {
297
+ since: string;
298
+ until: string;
299
+ };
300
+ dataSource: string;
301
+ caveats: string[];
302
+ };
303
+ };
304
+ actions: string[];
305
+ limitations: string[];
306
+ sources: string[];
307
+ };
308
+ declare function renderDeliveryReport(report: DeliveryReport, format: 'md' | 'html' | 'json', options?: AttributionOptions): string;
309
+
310
+ export { type DeliveryEvent, type DeliveryReport, type MetricsConfig, computeMetrics, renderDeliveryReport, scoreDeliveryHealth };
package/dist/index.js ADDED
@@ -0,0 +1,97 @@
1
+ // src/index.ts
2
+ import { invariant, round, validateInput, validateDateTime, renderReport } from "@tenhaw/core";
3
+ var HOUR = 36e5;
4
+ var DAY = 24 * HOUR;
5
+ function computeMetrics(input, cfg) {
6
+ validateInput("delivery-events", input);
7
+ invariant(cfg, "/period", "Explicit since and until timestamps are required");
8
+ validateDateTime(cfg.since, "/period/since");
9
+ validateDateTime(cfg.until, "/period/until");
10
+ const start = Date.parse(cfg.since), end = Date.parse(cfg.until);
11
+ invariant(end > start, "/period", "until must be after since");
12
+ const seen = /* @__PURE__ */ new Map();
13
+ for (const event of input) {
14
+ const old = seen.get(event.id);
15
+ invariant(!old || JSON.stringify(old) === JSON.stringify(event), `/events/${event.id}`, "Conflicting duplicate event ID");
16
+ seen.set(event.id, event);
17
+ }
18
+ const events = [...seen.values()].filter((e) => !cfg.service || e.service === cfg.service);
19
+ invariant(new Set(events.map((e) => e.service)).size <= 1, "/service", "Compute each service separately; supply config.service when multiple services are present");
20
+ for (const e of events) {
21
+ for (const [key, value] of Object.entries(e)) if (["timestamp", "startedAt", "restoredAt", "completedAt", "createdAt", "firstReviewAt", "mergedAt"].includes(key)) validateDateTime(value, `/events/${e.id}/${key}`);
22
+ if (e.type === "incident" && e.restoredAt) invariant(Date.parse(e.restoredAt) >= Date.parse(e.startedAt), `/events/${e.id}/restoredAt`, "Restoration cannot precede incident start");
23
+ if (e.type === "work-item" && e.completedAt) invariant(Date.parse(e.completedAt) >= Date.parse(e.startedAt), `/events/${e.id}/completedAt`, "Completion cannot precede start");
24
+ if (e.type === "pull-request") {
25
+ if (e.firstReviewAt) invariant(Date.parse(e.firstReviewAt) >= Date.parse(e.createdAt), `/events/${e.id}/firstReviewAt`, "Review cannot precede creation");
26
+ if (e.mergedAt) invariant(Date.parse(e.mergedAt) >= Date.parse(e.createdAt), `/events/${e.id}/mergedAt`, "Merge cannot precede creation");
27
+ }
28
+ }
29
+ const inside = (date) => Date.parse(date) >= start && Date.parse(date) < end;
30
+ const period = { since: cfg.since, until: cfg.until };
31
+ const metric = (value, unit, sampleSize, caveats = []) => ({ value: value === null ? null : round(value), unit, sampleSize, period, dataSource: "supplied events", caveats });
32
+ const mean = (v) => v.length ? v.reduce((a, b) => a + b, 0) / v.length : null;
33
+ const observedDeployments = events.filter((e) => e.type === "deployment" && e.environment === (cfg.productionEnvironment ?? "production") && !e.proxy);
34
+ const deployments = observedDeployments.filter((e) => inside(e.timestamp));
35
+ const commits = new Map(events.filter((e) => e.type === "commit").map((e) => [e.id, e]));
36
+ const incidents = events.filter((e) => e.type === "incident" && Date.parse(e.startedAt) < end && deployments.some((d) => d.id === e.deploymentId && Date.parse(e.startedAt) >= Date.parse(d.timestamp)));
37
+ const firstDelivery = /* @__PURE__ */ new Map();
38
+ const delivered = /* @__PURE__ */ new Set();
39
+ for (const d of [...observedDeployments].sort((a, b) => Date.parse(a.timestamp) - Date.parse(b.timestamp))) if (d.status === "success") for (const id of d.commitIds) {
40
+ const c = commits.get(id);
41
+ if (c && Date.parse(c.timestamp) <= Date.parse(d.timestamp) && !delivered.has(id)) {
42
+ delivered.add(id);
43
+ if (inside(d.timestamp)) firstDelivery.set(id, (Date.parse(d.timestamp) - Date.parse(c.timestamp)) / HOUR);
44
+ }
45
+ }
46
+ const failed = new Set(deployments.filter((d) => d.status === "failed").map((d) => d.id));
47
+ for (const i of incidents) failed.add(i.deploymentId);
48
+ const recovery = incidents.filter((i) => i.restoredAt && Date.parse(i.restoredAt) <= end).map((i) => (Date.parse(i.restoredAt) - Date.parse(i.startedAt)) / HOUR);
49
+ const classified = deployments.filter((d) => typeof d.rework === "boolean");
50
+ const work = events.filter((e) => e.type === "work-item" && Date.parse(e.startedAt) < end);
51
+ const completed = work.filter((e) => e.completedAt && inside(e.completedAt));
52
+ const cycle = completed.map((e) => (Date.parse(e.completedAt) - Date.parse(e.startedAt)) / HOUR);
53
+ const efficiency = completed.filter((e) => e.activeMinutes !== void 0 && Date.parse(e.completedAt) > Date.parse(e.startedAt)).map((e) => {
54
+ const elapsed = (Date.parse(e.completedAt) - Date.parse(e.startedAt)) / 6e4;
55
+ invariant(e.activeMinutes <= elapsed, `/events/${e.id}/activeMinutes`, "Active time cannot exceed elapsed cycle time");
56
+ return e.activeMinutes / elapsed * 100;
57
+ });
58
+ const prs = events.filter((e) => e.type === "pull-request" && !!e.mergedAt && inside(e.mergedAt));
59
+ const reviews = prs.filter((e) => e.firstReviewAt).map((e) => (Date.parse(e.firstReviewAt) - Date.parse(e.createdAt)) / HOUR);
60
+ const sizes = prs.filter((e) => e.additions !== void 0 && e.deletions !== void 0).map((e) => e.additions + e.deletions);
61
+ const noDeploy = ["No observed production deployments in the requested period."];
62
+ const missing = (n, label) => n ? [] : [label];
63
+ return { period, metrics: {
64
+ deploymentFrequency: metric(deployments.length ? deployments.length / ((end - start) / DAY) : null, "deployments/day", deployments.length, deployments.length ? [] : noDeploy),
65
+ changeLeadTime: metric(mean([...firstDelivery.values()]), "hours", firstDelivery.size, missing(firstDelivery.size, "No linked commit-to-production observations.")),
66
+ changeFailRate: metric(deployments.length ? failed.size / deployments.length * 100 : null, "percent", deployments.length, deployments.length ? ["Assumes supplied deployment statuses and incident links are complete."] : noDeploy),
67
+ failedDeploymentRecoveryTime: metric(mean(recovery), "hours", recovery.length, missing(recovery.length, "No linked incidents with observed restoration.")),
68
+ deploymentReworkRate: metric(deployments.length && classified.length === deployments.length ? classified.filter((d) => d.rework).length / deployments.length * 100 : null, "percent", classified.length, classified.length === deployments.length && deployments.length ? [] : ["Every deployment needs explicit rework classification."]),
69
+ cycleTime: metric(mean(cycle), "hours", cycle.length, missing(cycle.length, "No completed work items in the period.")),
70
+ throughput: metric(work.length ? completed.length / ((end - start) / (7 * DAY)) : null, "items/week", completed.length, work.length ? [] : ["No work-item observations."]),
71
+ wip: metric(work.length ? work.filter((e) => !e.completedAt || Date.parse(e.completedAt) >= end).length : null, "items at period end", work.length, work.length ? [] : ["No work-item observations."]),
72
+ flowEfficiency: metric(mean(efficiency), "percent", efficiency.length, missing(efficiency.length, "No completed work items with active time.")),
73
+ prReviewTime: metric(mean(reviews), "hours", reviews.length, missing(reviews.length, "No merged pull requests with a first review timestamp.")),
74
+ prSize: metric(mean(sizes), "changed lines", sizes.length, missing(sizes.length, "No merged pull requests with additions and deletions."))
75
+ }, caveats: ["Metrics describe one service and the supplied event window; missing links remain unavailable.", ...events.some((e) => e.type === "deployment" && e.proxy) ? ["Proxy deployment events are excluded from DORA metrics."] : []] };
76
+ }
77
+ function scoreDeliveryHealth(report) {
78
+ validateInput("delivery-report", report);
79
+ validateDateTime(report.period.since, "/period/since");
80
+ validateDateTime(report.period.until, "/period/until");
81
+ invariant(Number.isFinite(Date.parse(report.period.since)) && Number.isFinite(Date.parse(report.period.until)) && Date.parse(report.period.until) > Date.parse(report.period.since), "/period", "Use an increasing observed period");
82
+ for (const [name, metric] of Object.entries(report.metrics)) invariant(metric.period.since === report.period.since && metric.period.until === report.period.until, `/metrics/${name}/period`, "All metrics must use the report period");
83
+ const actions = [];
84
+ if (report.metrics.changeLeadTime.value === null) actions.push("Link commits to observed production deployments.");
85
+ if (report.metrics.failedDeploymentRecoveryTime.value === null) actions.push("Record incident-to-deployment links and restoration timestamps.");
86
+ if (report.metrics.deploymentReworkRate.value === null) actions.push("Classify planned and incident-driven deployments.");
87
+ if (actions.length === 0) actions.push("Review trends for this service with the team before choosing an improvement.");
88
+ return { status: "informational", metrics: report.metrics, actions: actions.slice(0, 3), limitations: ["No composite score or cross-team ranking is inferred.", "DORA defines five delivery performance metrics; context and data completeness matter."], sources: ["https://dora.dev/guides/dora-metrics/"] };
89
+ }
90
+ function renderDeliveryReport(report, format, options = {}) {
91
+ return renderReport(report, format, { content: "delivery-metrics", ...options });
92
+ }
93
+ export {
94
+ computeMetrics,
95
+ renderDeliveryReport,
96
+ scoreDeliveryHealth
97
+ };
package/package.json CHANGED
@@ -1,6 +1,46 @@
1
1
  {
2
2
  "name": "@tenhaw/delivery-metrics",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "1.0.0",
4
+ "description": "Five DORA metrics and flow measures from linked delivery events",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.js"
12
+ },
13
+ "./collectors": {
14
+ "types": "./dist/collectors.d.ts",
15
+ "import": "./dist/collectors.js"
16
+ }
17
+ },
18
+ "files": [
19
+ "dist",
20
+ "README.md",
21
+ "LICENSE",
22
+ "LICENSE-CONTENT"
23
+ ],
24
+ "dependencies": {
25
+ "@tenhaw/core": "1.0.0"
26
+ },
27
+ "author": "Tenhaw (https://tenhaw.com)",
28
+ "license": "MIT",
29
+ "repository": {
30
+ "type": "git",
31
+ "url": "https://github.com/Tenhaw/tenhaw-kit.git",
32
+ "directory": "packages/delivery-metrics"
33
+ },
34
+ "homepage": "https://kit.tenhaw.com/tools/delivery-metrics",
35
+ "publishConfig": {
36
+ "access": "public"
37
+ },
38
+ "engines": {
39
+ "node": ">=22"
40
+ },
41
+ "scripts": {
42
+ "build": "tsup src/index.ts src/collectors.ts --format esm --dts",
43
+ "test": "vitest run --passWithNoTests",
44
+ "typecheck": "tsc --noEmit"
45
+ }
6
46
  }