@juangcarmona/lighthouse-sdlc 0.26.0 → 0.28.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/README.md +8 -0
- package/commands/delivery-acceptance.md +5 -0
- package/commands/measurements.md +5 -0
- package/contract.json +1 -1
- package/delivery-acceptance.md +64 -0
- package/measurements.md +74 -0
- package/package.json +13 -4
- package/src/delivery-acceptance-cli.mjs +25 -0
- package/src/delivery-acceptance.mjs +191 -0
- package/src/install-workflows.mjs +2 -1
- package/src/measurement-cli.mjs +39 -0
- package/src/measurement-github.mjs +165 -0
- package/src/measurement-report.mjs +37 -0
- package/src/measurement.mjs +124 -0
- package/src/sdlc.mjs +9 -3
- package/workflows/lighthouse-delivery-acceptance.yml +38 -0
package/README.md
CHANGED
|
@@ -14,6 +14,14 @@ The policy includes reviewed immutable [source pins](skills/audience-guidance/so
|
|
|
14
14
|
|
|
15
15
|
When repository instructions explicitly authorize it, the [code and architecture fallback](skills/audience-guidance/SKILL.md#code-and-architecture-review) lets an isolated worker complete its required review without a missing global helper. Record the fallback method, reviewed source, findings and missing evidence. Packaging that guidance does not prove a native worker used it or change any approval gate.
|
|
16
16
|
|
|
17
|
+
## Delivery measurements
|
|
18
|
+
|
|
19
|
+
Use the optional [versioned measurements](measurements.md) to derive repository-scoped observations with explicit source coverage and missing-data states.
|
|
20
|
+
|
|
21
|
+
## Delivery acceptance
|
|
22
|
+
|
|
23
|
+
Use the optional [owner delivery-decision producer and source verifier](delivery-acceptance.md) to record acceptance of an exact candidate. It requires separate adoption and a new explicit owner decision.
|
|
24
|
+
|
|
17
25
|
## GitHub Actions
|
|
18
26
|
|
|
19
27
|
These actions require installed workers, enabled automation and the repository owner as actor. Opening an issue alone starts no agent. Every result links to its execution; an Actions success can contain a blocked assessment.
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
# Delivery acceptance
|
|
2
|
+
|
|
3
|
+
Read the [source and adoption contract](../delivery-acceptance.md). Prepare the exact binding with `lighthouse-sdlc delivery-acceptance prepare`; the repository owner authors the resulting decision comment. Record it through the adopted non-agent workflow, then run `verify` with independently readable sources and all retained receipts for that binding.
|
|
4
|
+
|
|
5
|
+
Report the observed status and source limitations. Product approval, engineering results and lifecycle events retain their existing meanings. Acceptance grants no mutation authority. An undeclared route, expired source or incomplete correction history is unavailable; a healthy route without a decision is pending.
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
# Delivery measurements
|
|
2
|
+
|
|
3
|
+
Read the [measurement contract](../measurements.md). Inspect versioned formulas with `lighthouse-sdlc measurements definitions`. Derive the report from a retained repository/window bundle using `lighthouse-sdlc measurements derive --input frozen.json`.
|
|
4
|
+
|
|
5
|
+
Report each metric's status, numerator, denominator, coverage, censoring and source links. Offline integrity does not establish live source authenticity. Keep missing fields unknown and preserve historical source revisions. Use `collect --repo owner/repo --start UTC --end UTC --output frozen.json` for the bounded read-only GitHub observation, and `render --input frozen.json --output report.html` for a self-contained offline report. Only collection needs a read-only credential. No operation mutates repository policy or work items.
|
package/contract.json
CHANGED
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
{ "name": "integrate", "skill": "skills/integrate/SKILL.md", "command": "commands/integrate.md", "gate": "done" },
|
|
11
11
|
{ "name": "review", "skill": "skills/review/SKILL.md", "command": "commands/review.md", "gate": null }
|
|
12
12
|
],
|
|
13
|
-
"utilities": ["status", "aliases", "route", "state", "stage-result", "control-plane", "memory", "launch", "decompose", "stacked", "browser-e2e", "evidence", "github-triage", "github-decompose", "reconcile-labels", "github-labels", "practices"],
|
|
13
|
+
"utilities": ["status", "aliases", "route", "state", "stage-result", "control-plane", "memory", "launch", "decompose", "stacked", "browser-e2e", "evidence", "github-triage", "github-decompose", "reconcile-labels", "github-labels", "practices", "delivery-acceptance", "measurements"],
|
|
14
14
|
"routes": ["supervised", "plan-only", "unattended", "hotfix", "stacked"],
|
|
15
15
|
"metaCommands": ["ff", "hotfix", "decompose", "stacked"],
|
|
16
16
|
"gates": ["triaged", "ready", "planned", "done"],
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
# Delivery acceptance
|
|
2
|
+
|
|
3
|
+
The `repository-owner` route records a new owner decision about an exact PR candidate. `prepare` reads sources and prints a comment for the owner to review and post. The non-agent producer authenticates that comment and retains `receipt.json` in its Actions artifact. `verify` independently reads GitHub sources, the adopted workflow and its retained artifact. All three operations use read-only GitHub permissions. Artifact retention is 90 days; deletion or expiry makes current verification unavailable.
|
|
4
|
+
|
|
5
|
+
## Adopt the producer
|
|
6
|
+
|
|
7
|
+
Install workflows with `--with-delivery-acceptance` and an immutable Lighthouse source revision or an exact published package containing this feature. Review `.github/workflows/lighthouse-delivery-acceptance.yml`, then commit an explicit `.lighthouse/delivery-acceptance.json` policy:
|
|
8
|
+
|
|
9
|
+
```json
|
|
10
|
+
{
|
|
11
|
+
"schemaVersion": 1,
|
|
12
|
+
"enabled": true,
|
|
13
|
+
"route": "repository-owner",
|
|
14
|
+
"repositoryId": 123,
|
|
15
|
+
"ownerId": 456,
|
|
16
|
+
"producer": {
|
|
17
|
+
"workflow": ".github/workflows/lighthouse-delivery-acceptance.yml",
|
|
18
|
+
"workflowBlob": "REPLACE_WITH_REVIEWED_GIT_BLOB_SHA",
|
|
19
|
+
"operator": "repository-owner"
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
Use GitHub's numeric repository and owner IDs. Obtain the reviewed workflow blob with `git hash-object .github/workflows/lighthouse-delivery-acceptance.yml`. The policy and workflow must be on the default branch, with the workflow active. Changing either requires reviewed adoption and a fresh decision bound to the new policy. The adopting repository owner operates the producer and retains its source permissions: Contents/read, Issues/read, Pull requests/read and Actions/read. Receipt upload uses Actions' native artifact credentials; the job has no repository write permission. Personal repositories are supported first; organization, delegated and artifact-candidate routes remain unavailable.
|
|
25
|
+
|
|
26
|
+
## Prepare and record a decision
|
|
27
|
+
|
|
28
|
+
Create `candidate.json` with the issue and PR numbers, the full policy commit SHA and immutable text files defining the scope and criteria:
|
|
29
|
+
|
|
30
|
+
```json
|
|
31
|
+
{
|
|
32
|
+
"issue": 12,
|
|
33
|
+
"pullRequest": 34,
|
|
34
|
+
"policyRevision": "FULL_40_CHARACTER_COMMIT_SHA",
|
|
35
|
+
"scope": { "path": "openspec/changes/example/proposal.md", "revision": "FULL_40_CHARACTER_COMMIT_SHA" },
|
|
36
|
+
"criteria": { "path": "openspec/changes/example/tasks.md", "revision": "FULL_40_CHARACTER_COMMIT_SHA" }
|
|
37
|
+
}
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
```sh
|
|
41
|
+
lighthouse-sdlc delivery-acceptance prepare --repo owner/repo --input candidate.json --output prepared.json
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
Review the complete `binding` and comment. The owner posts a new comment on that issue with the prepared marker and JSON, supplies a specific reason and chooses `accepted` or `rejected`. Preparing a comment creates no decision. Product approval, merge authorization and delivery acceptance remain separate decisions.
|
|
45
|
+
|
|
46
|
+
Dispatch **Lighthouse delivery acceptance** with that numeric comment ID. Only owner dispatches and owner reruns can produce receipts. Download the resulting `receipt.json`. Keep the original bytes and source URLs; a digest or producer name by itself proves no authority.
|
|
47
|
+
|
|
48
|
+
To withdraw a decision, post a new comment with the same binding, outcome `revoked`, a reason and `corrects` containing the original logical ID (`github:REPOSITORY_ID:issue-comment:COMMENT_ID`). `superseded` also requires a `replacement` decision ID. A replacement is verified separately against its own candidate. A new accepted or rejected decision after an earlier decision must explicitly correct it. Sources are immutable: editing or deleting a source makes verification unavailable. Producer retries retain the same logical decision ID and separate run attempts; they never add accepted deliveries.
|
|
49
|
+
|
|
50
|
+
## Verify independently
|
|
51
|
+
|
|
52
|
+
Create a JSON input containing the prepared `binding` and an array of all retained `receipts` for that binding, then run:
|
|
53
|
+
|
|
54
|
+
```sh
|
|
55
|
+
lighthouse-sdlc delivery-acceptance verify --repo owner/repo --input verification.json --output verified.json
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
The verifier reports `accepted`, `rejected`, `revoked`, `superseded`, `pending` or `unavailable`, with observation time, history coverage and source links. A healthy adopted route without a decision is pending. Missing adoption, inaccessible or edited sources, stale candidates, missing receipts, expired artifacts, wrong actors or conflicting history are unavailable and name the repository owner as recovery owner. The verifier enumerates retained producer artifacts independently, including decisions whose source comments were later deleted. Supply every retained receipt for the requested binding. History is bounded to 1,000 issue comments, 1,000 producer runs and 100 input receipts. Expired producer history makes current verification unavailable, including when that history might contain an omitted correction. Verification cannot establish unobserved future revocations. A historical source remains historical when the PR head changes.
|
|
59
|
+
|
|
60
|
+
Receipts contain schema version, stable source-derived decision ID, route, exact binding, retained source bytes and digest, authenticated actor, creation/update time, and producer run/attempt/revision/workflow blob. Identity comparisons use numeric provider IDs and full Git hashes; locators aid navigation. Scope, criteria and policy retain Git blob and SHA-256 identities. JSON object keys are canonically sorted for binding comparison. Unsupported versions fail closed. The SDK exports `prepareAcceptance`, `produceAcceptance` and `verifyAcceptance` from `@juangcarmona/lighthouse-sdlc/delivery-acceptance`; supplying fixture observations to tests does not establish live authenticity.
|
|
61
|
+
|
|
62
|
+
## Consumer handoff
|
|
63
|
+
|
|
64
|
+
Consumers must retain the source records and report current verification separately from execution, integration, release, deployment and closure. The producer's accountable owner is the adopting repository owner. No real delivery acceptance is asserted by shipping this contract. Until adoption and an independently verifiable owner source exist, consumer acceptance is explicitly unavailable; this is the handoff contract for consumers awaiting their first qualifying example. A verified acceptance authorizes no lifecycle mutation.
|
package/measurements.md
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
# Delivery and attention measurements
|
|
2
|
+
|
|
3
|
+
Use `lighthouse-sdlc measurements definitions` for the 13 versioned definitions. Every definition includes its purpose, unit, formula, source identity requirements, window/cohort rules, deduplication, coverage, privacy, classification and unavailable reason. `lighthouse-sdlc measurements derive --input frozen.json --output metrics.json` computes the same projection offline from identical frozen inputs. It makes no network request or remote mutation.
|
|
4
|
+
|
|
5
|
+
## Selected measurements
|
|
6
|
+
|
|
7
|
+
| Definition | Numerator and denominator | Source and interpretation |
|
|
8
|
+
| --- | --- | --- |
|
|
9
|
+
| `evidence.completeness.v1` | Valid retained records / enumerated records | Structural source identities and content hashes; missing source collections remain coverage gaps |
|
|
10
|
+
| `execution.stage-outcome.v1` | Explicit status counts / stage results | Passed, failed, blocked and uncertain assessments; Actions success has separate meaning |
|
|
11
|
+
| `execution.attempt-outcome.v1` | Native conclusion counts / workflow attempts | Run ID plus attempt; retries remain separate technical observations |
|
|
12
|
+
| `execution.blocking-reason.v1` | Explicit cause counts / blocked results | Human, technical or unknown; technical failure creates no human waiting interval |
|
|
13
|
+
| `delivery.issue-to-pr.v1` | Sum of observed seconds / observed issue-to-first-PR pairs | Issue creation cohort; explicit retained PR relation required; unmatched issues are right-censored |
|
|
14
|
+
| `delivery.issue-to-integration.v1` | Sum of observed seconds / observed issue-to-first-merge pairs | Same cohort; explicit merged PR and full merge SHA required; issue closure provides no merge evidence |
|
|
15
|
+
| `autonomy.human-touches.v1` | User comment/review events / enumerated eligible touches | Bots excluded; observable interactions provide no active effort estimate |
|
|
16
|
+
| `autonomy.human-wait-time.v1` | Sum of clipped wait seconds / explicit human-wait intervals | Window clipping and unresolved interval censoring; sums describe work-item intervals, which can overlap |
|
|
17
|
+
| `autonomy.delegated-integration.v1` | Unique qualified head/merge pairs / eligible integration records | Retained integration-verifier assessment and exact authorization/merge source bindings |
|
|
18
|
+
| `delivery.confirmed-reverts.v1` | Unique qualified reversal pairs / eligible reversal records | Explicit original/reversal revision relation from a declared verifier; title matching is excluded |
|
|
19
|
+
| `execution.agent-step-duration.v1` | Sum of observed seconds / measured native agent steps | Exact run/attempt/job/step; wrapper wall time, excluding queue and whole-workflow duration |
|
|
20
|
+
| `model.token-usage.v1` | Per-field token sum with measured N / eligible invocation M | Missing fields remain null; requested, resolved and provider-reported identity plus authentication route are retained separately |
|
|
21
|
+
| `evidence.external-unknowns.v1` | No fabricated numerator/denominator | Provider confirmation, billing, deployment, incidents, active human effort and accepted delivery remain unknown without their own sources |
|
|
22
|
+
|
|
23
|
+
All event windows are UTC `[start,end)`. Lead-time eligibility uses issues created in that window; linked PR or merge completion must precede `end`. Means use observed pairs only and expose their censored cohort. Waiting intervals intersect the window and unresolved intervals report lower bounds. Counts may be zero only for an explicitly complete empty inventory. Missing inventories produce unavailable results. Partial or conflicting inputs retain their limitations alongside any observed subtotal.
|
|
24
|
+
|
|
25
|
+
## Frozen input and source trust
|
|
26
|
+
|
|
27
|
+
A v1 bundle contains `repository: {id, fullName}`, `window: {start, end}`, `records` and `collections`. Each collection names a record `kind`, `status` (`complete`, `incomplete` or `unavailable`) and a reason when incomplete. Each record contains `kind`, stable logical `id`, event `time`, producer `data` and a retained `source` with numeric repository identity, provider event identity, safe source URL, full Git revision or `sha256:` snapshot identity, SHA-256 of the canonical `{kind, time, data}` envelope, and retrieval `observedAt`. Mutable GitHub observations use their frozen content identity. Git/API sources remain authoritative.
|
|
28
|
+
|
|
29
|
+
Use the exported `measurementRecord` helper to form source-bound records. The SDK export is `@juangcarmona/lighthouse-sdlc/measurement`. Inputs are bounded to 10,000 records and 4 MiB. Identical logical events deduplicate; workflow attempts use run/attempt identity and usage uses invocation identity. Changed data at one identity is conflicting and excluded. Retries with identical event content and different retrieval times remain one observation. Keep the frozen input: every output includes its digest and each measured number exposes source references and N/M coverage.
|
|
30
|
+
|
|
31
|
+
Offline checks establish retained content integrity and deterministic interpretation. They cannot authenticate a producer, an arbitrary JSON claim or current source freshness. A collector must authenticate GitHub and invoke the owning verifier before declaring a qualified integration assessment. A source name, `authenticated: true` or a generic evidence coverage status cannot qualify delegated integration or accepted delivery. The report labels retained verification as an observation at collection time. Live acceptance uses the separate [delivery-acceptance verifier](delivery-acceptance.md).
|
|
32
|
+
|
|
33
|
+
### Producer data
|
|
34
|
+
|
|
35
|
+
Stage records retain explicit assessment `status` and optional `blockingCause`; attempts retain native `runId`, `attempt` and `conclusion`. Issues retain provider `id`; PRs retain `createdAt`, `mergedAt`, `merged`, `mergeCommitSha`, `linkedIssueIds` and retained `linkProof`. A PR relation proof identifies the issue, source event and content hash. Lead-time samples describe the first retained related PR or related merge; a cross-reference can concern documentation or a dependency and establishes no work-item completion. Delivery acceptance retains its own exact binding and source decision. Missing relation evidence censors the issue instead of guessing from text.
|
|
36
|
+
|
|
37
|
+
Human touches retain `actorType`, numeric `actorId` and `event` (`comment` or `review`). Human waits retain explicit `cause: human`, `start` and an `end` timestamp or null. Agent steps retain run/attempt/job identity, step number, exact adopted name `OpenCode progress and result`, start/completion timestamps and conclusion. A skipped step is excluded from invocation eligibility.
|
|
38
|
+
|
|
39
|
+
Usage records retain `invocationId`, source coverage, `usageSource`, `authenticationRoute`, separate identity dimensions and nullable input/output/reasoning/cache token fields. Each field has its own N/M coverage. Reasoning is retained separately and never added again to output. Currency and billable token counts remain unknown; this implementation adds no price estimate or new usage emitter.
|
|
40
|
+
|
|
41
|
+
Qualified delegated integrations retain full `head` and `merge`, a `lighthouse.integration.v1` verification assessment, its repository/head/merge binding hash and references to source-bound authorization and merge records. Confirmed reversals require a `lighthouse.revert.v1` assessment and explicit `reverts`/`reversal` relation. A collector without those authenticated adapters declares the collection unavailable. It never manufactures a receipt to fill a metric.
|
|
42
|
+
|
|
43
|
+
## Coverage inventory
|
|
44
|
+
|
|
45
|
+
| Capability | Delivery boundary |
|
|
46
|
+
| --- | --- |
|
|
47
|
+
| Existing issue, PR, Actions run/attempt and exact job-step observations | Supported by deterministic derivation; collected separately by the optional read-only collector |
|
|
48
|
+
| Stage outcomes, blocking causes, usage and human waiting | Existing producer payloads; missing/expired payloads remain unavailable and require bounded adapters rather than inferred replacements |
|
|
49
|
+
| Delegated integration | Existing integration verifier; the collector must retain a verified exact binding before enabling this metric |
|
|
50
|
+
| Explicit reversal proof | Requires a declared source producer; unsupported sources remain unavailable |
|
|
51
|
+
| Provider-reported settings, attributable billing, deployment and incidents | Separate external producers; no first-report proxy or synthetic DORA rate |
|
|
52
|
+
| Active human effort, personal productivity, health scores and automatic policy tuning | Excluded |
|
|
53
|
+
|
|
54
|
+
The [research inventory](../../../docs/roadmap/engineering-measurement-research.md) remains historical context. The executable definitions and deterministic cases govern this bounded report; the original proposed fixtures do not authenticate sources or establish live outcomes. No benchmark, scheduler, service, database, cross-repository crawler or policy automation is introduced.
|
|
55
|
+
|
|
56
|
+
## Read GitHub and render offline
|
|
57
|
+
|
|
58
|
+
The optional collector uses GET requests for one explicitly named repository and UTC window. Use a read-only credential with Contents/read, Issues/read, Pull requests/read and Actions/read. It retains selected provider fields, content identities, retrieval times, run/attempt lineage, artifact observations and exact collection gaps. It stores no issue bodies, transcripts or raw logs. Worker assessments retain their declared meaning; they never become acceptance or integration authority.
|
|
59
|
+
|
|
60
|
+
```sh
|
|
61
|
+
lighthouse-sdlc measurements collect --repo owner/repo --start 2026-01-01T00:00:00Z --end 2026-02-01T00:00:00Z --output frozen.json
|
|
62
|
+
lighthouse-sdlc measurements derive --input frozen.json --output metrics.json
|
|
63
|
+
lighthouse-sdlc measurements render --input frozen.json --output report.html
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
Only `collect` needs `GH_TOKEN`; the existing bounded artifact reader also requires the `gh` executable in the operator environment. `derive` and `render` use the frozen bytes without credentials or network access. Output files are exclusive creations; retain each collection separately and rerender to another path when comparing bytes. Identical frozen input and implementation produce byte-identical output. There is no resume cursor or scheduler; retrying a collection creates a new observation, and logical source identity prevents duplicates within its derivation.
|
|
67
|
+
|
|
68
|
+
Default bounds are two pages per inventory, 20 issues, 20 PRs, 20 runs, three attempts per run and 200 read requests. Set `--max-pages`, `--max-issues`, `--max-prs`, `--max-runs` or `--max-requests` explicitly for a different bounded sample. `--workflows file.lock.yml,other.lock.yml` selects at most eight repository workflow files. Run selection uses the GitHub creation cohort. Earlier-created runs that finish inside the window are not enumerated, so event-window completeness remains an explicit gap. Selection and truncation remain visible; a selected population is never described as exhaustive repository coverage. Human interaction collection covers the selected issue/PR cohorts and explicitly linked PRs; other work-item interactions remain a population gap.
|
|
69
|
+
|
|
70
|
+
The collector reads issue timelines for explicit same-repository PR relations, current PR details, comments/reviews, run attempts, native jobs and the exact agent wrapper step. It reads existing bounded result and telemetry JSON artifacts through the shared archive reader. Source denial, invalid or partial inventories, pagination/request limits, expired artifacts and incompatible payloads remain named gaps. A workflow success can retain a blocked assessment, and a failed publication remains a native failure independently of the worker's result.
|
|
71
|
+
|
|
72
|
+
Stage blocking cause uses an explicit handoff where present; prose is never parsed into human waiting. The current collector leaves human waiting, delegated integration and reversal collections unavailable because it does not run their independent source-verification adapters. Their metric definitions remain supported for qualified retained observations supplied by an owning adapter. Billing, deployment, provider confirmation, incident rates, active effort and delivery acceptance also retain their independent source boundaries.
|
|
73
|
+
|
|
74
|
+
The self-contained HTML report includes formulas, status, numerator/denominator, N/M coverage, censoring, content/revision identities, source links, collection gaps and operator findings. It escapes source prose, restricts active links to the selected GitHub repository and uses a content policy that permits no scripts, forms or network calls. The renderer inlines the pinned Lighthouse UI token stylesheet during generation; appearance follows the system theme without an asset request. It contains no browser token or action controls. Publishing or scheduling the report remains an explicit operator action; ordinary collection does neither.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@juangcarmona/lighthouse-sdlc",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.28.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Provider-neutral SDLC skills, commands and route contracts for Lighthouse adopters",
|
|
6
6
|
"repository": {
|
|
@@ -48,7 +48,9 @@
|
|
|
48
48
|
"NOTICE",
|
|
49
49
|
"telemetry.md",
|
|
50
50
|
"issue-control.md",
|
|
51
|
-
"practice-evidence.md"
|
|
51
|
+
"practice-evidence.md",
|
|
52
|
+
"delivery-acceptance.md",
|
|
53
|
+
"measurements.md"
|
|
52
54
|
],
|
|
53
55
|
"bin": {
|
|
54
56
|
"lighthouse-sdlc": "./src/sdlc.mjs"
|
|
@@ -108,7 +110,14 @@
|
|
|
108
110
|
"./practice-observation": "./src/practice-observation.mjs",
|
|
109
111
|
"./practice-evaluator": "./src/practice-evaluator.mjs",
|
|
110
112
|
"./practice-github": "./src/practice-github.mjs",
|
|
111
|
-
"./practice-history": "./src/practice-history.mjs"
|
|
113
|
+
"./practice-history": "./src/practice-history.mjs",
|
|
114
|
+
"./delivery-acceptance": "./src/delivery-acceptance.mjs",
|
|
115
|
+
"./measurement": "./src/measurement.mjs",
|
|
116
|
+
"./measurement-github": "./src/measurement-github.mjs",
|
|
117
|
+
"./measurement-report": "./src/measurement-report.mjs"
|
|
112
118
|
},
|
|
113
|
-
"license": "Apache-2.0"
|
|
119
|
+
"license": "Apache-2.0",
|
|
120
|
+
"dependencies": {
|
|
121
|
+
"@juangcarmona/lighthouse-ui": "0.2.1"
|
|
122
|
+
}
|
|
114
123
|
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { readFile, writeFile } from 'node:fs/promises';
|
|
2
|
+
import { createIssueApi } from './github-rest.mjs';
|
|
3
|
+
import { prepareAcceptance, produceAcceptance, verifyAcceptance } from './delivery-acceptance.mjs';
|
|
4
|
+
|
|
5
|
+
export async function acceptanceCli(args, env = process.env) {
|
|
6
|
+
const operation = args[0], option = name => args[args.indexOf(name) + 1];
|
|
7
|
+
const repository = args.includes('--repo') ? option('--repo') : env.GITHUB_REPOSITORY;
|
|
8
|
+
if (!['prepare', 'produce', 'verify'].includes(operation) || !/^[\w.-]+\/[\w.-]+$/.test(repository ?? '') || !env.GH_TOKEN) throw Error('Usage: lighthouse-sdlc delivery-acceptance <prepare|produce|verify> --repo owner/name --input file [--output file]; requires GH_TOKEN with read-only source permissions');
|
|
9
|
+
const api = createIssueApi(repository, env);
|
|
10
|
+
let result;
|
|
11
|
+
if (operation === 'produce') {
|
|
12
|
+
result = await produceAcceptance(api, repository, Number(env.LIGHTHOUSE_DECISION_COMMENT), { runId: Number(env.GITHUB_RUN_ID), attempt: Number(env.GITHUB_RUN_ATTEMPT), revision: env.GITHUB_SHA });
|
|
13
|
+
} else {
|
|
14
|
+
if (!args.includes('--input')) throw Error('A bounded input JSON file is required');
|
|
15
|
+
const bytes = await readFile(option('--input'));
|
|
16
|
+
if (bytes.length > 1024 * 1024) throw Error('Acceptance input exceeds 1 MiB');
|
|
17
|
+
const input = JSON.parse(bytes);
|
|
18
|
+
result = operation === 'prepare' ? await prepareAcceptance(api, repository, input) : await verifyAcceptance(api, repository, input);
|
|
19
|
+
}
|
|
20
|
+
const text = JSON.stringify(result, null, 2) + '\n';
|
|
21
|
+
if (args.includes('--output')) await writeFile(option('--output'), text, { flag: 'wx', mode: 0o600 });
|
|
22
|
+
else process.stdout.write(text);
|
|
23
|
+
if (operation === 'verify' && result.status === 'unavailable') process.exitCode = 1;
|
|
24
|
+
return result;
|
|
25
|
+
}
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { validatePublishable } from './process-publication.mjs';
|
|
3
|
+
import { readActionsJson } from './actions-artifact.mjs';
|
|
4
|
+
|
|
5
|
+
const sha = value => createHash('sha256').update(value).digest('hex');
|
|
6
|
+
export const canonical = value => JSON.stringify(value, (_key, item) => item && typeof item === 'object' && !Array.isArray(item) ? Object.fromEntries(Object.keys(item).sort().map(key => [key, item[key]])) : item);
|
|
7
|
+
export const acceptanceDigest = value => sha(canonical(value));
|
|
8
|
+
const revision = value => /^[a-f0-9]{40}$/.test(value ?? '');
|
|
9
|
+
const positive = value => Number.isSafeInteger(value) && value > 0;
|
|
10
|
+
function parseJson(text) { try { return JSON.parse(text); } catch { throw Error('Invalid source JSON'); } }
|
|
11
|
+
const marker = '<!-- lighthouse-delivery-decision:v1 -->';
|
|
12
|
+
const policyPath = '.lighthouse/delivery-acceptance.json';
|
|
13
|
+
function requireThat(condition, reason) { if (!condition) throw Error(reason); }
|
|
14
|
+
|
|
15
|
+
async function sourceFile(api, path, ref) {
|
|
16
|
+
requireThat(revision(ref) && typeof path === 'string' && /^[\w./-]+$/.test(path) && !path.split('/').some(part => !part || part === '.' || part === '..'), 'Invalid immutable source reference');
|
|
17
|
+
const file = await api(`contents/${path}?ref=${ref}`);
|
|
18
|
+
requireThat(file.type === 'file' && file.encoding === 'base64' && file.size <= 65536, 'Source file unavailable or exceeds 64 KiB');
|
|
19
|
+
const bytes = Buffer.from(file.content, 'base64');
|
|
20
|
+
requireThat(bytes.length === file.size && createHash('sha1').update(Buffer.concat([Buffer.from(`blob ${bytes.length}\0`), bytes])).digest('hex') === file.sha, 'Source file content identity mismatch');
|
|
21
|
+
return { path, revision: ref, blob: file.sha, sha256: sha(bytes), content: bytes.toString('utf8') };
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export async function acceptancePolicy(api, repository, ref) {
|
|
25
|
+
const repo = await api('');
|
|
26
|
+
requireThat(repo.full_name === repository && positive(repo.id) && repo.owner?.type === 'User' && positive(repo.owner.id), 'First acceptance route requires an identified personal repository owner');
|
|
27
|
+
const file = await sourceFile(api, policyPath, ref);
|
|
28
|
+
const policy = parseJson(file.content);
|
|
29
|
+
requireThat(policy.schemaVersion === 1 && policy.enabled === true && policy.route === 'repository-owner' && policy.repositoryId === repo.id && policy.ownerId === repo.owner.id && policy.producer?.workflow === '.github/workflows/lighthouse-delivery-acceptance.yml' && revision(policy.producer.workflowBlob) && typeof policy.producer.operator === 'string' && policy.producer.operator.length > 0, 'Acceptance route or producer not explicitly adopted');
|
|
30
|
+
const tip = await api(`commits/${encodeURIComponent(repo.default_branch)}`);
|
|
31
|
+
const current = await sourceFile(api, policyPath, tip.sha);
|
|
32
|
+
requireThat(current.blob === file.blob, 'Acceptance policy is no longer current; a new decision is required');
|
|
33
|
+
const workflow = await sourceFile(api, policy.producer.workflow, tip.sha);
|
|
34
|
+
requireThat(workflow.blob === policy.producer.workflowBlob, 'Adopted producer workflow changed');
|
|
35
|
+
const installed = await api('actions/workflows/lighthouse-delivery-acceptance.yml');
|
|
36
|
+
requireThat(installed.state === 'active' && installed.path === policy.producer.workflow, 'Adopted producer is unavailable');
|
|
37
|
+
return { repo, policy, reference: { path: policyPath, revision: ref, blob: file.blob, sha256: file.sha256 } };
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
async function retainedSubject(api, item) {
|
|
41
|
+
const source = await sourceFile(api, item?.path, item?.revision);
|
|
42
|
+
if (item.sha256) requireThat(item.sha256 === source.sha256, 'Scope or criteria digest changed');
|
|
43
|
+
return { path: source.path, revision: source.revision, blob: source.blob, sha256: source.sha256 };
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export async function prepareAcceptance(api, repository, input) {
|
|
47
|
+
const { repo, reference } = await acceptancePolicy(api, repository, input.policyRevision);
|
|
48
|
+
requireThat(positive(input.issue) && positive(input.pullRequest), 'An exact issue and PR are required');
|
|
49
|
+
const issue = await api(`issues/${input.issue}`), pr = await api(`pulls/${input.pullRequest}`);
|
|
50
|
+
requireThat(!issue.pull_request && positive(issue.id) && positive(pr.id) && pr.base.repo.id === repo.id && pr.head.repo?.id === repo.id && revision(pr.head.sha), 'Candidate identity does not match the adopted repository');
|
|
51
|
+
const binding = { repository: { id: repo.id, fullName: repository }, workItem: { id: issue.id, number: issue.number, url: issue.html_url }, candidate: { kind: 'pull-request', id: pr.id, number: pr.number, head: pr.head.sha, url: pr.html_url }, scope: await retainedSubject(api, input.scope), criteria: await retainedSubject(api, input.criteria), policy: reference };
|
|
52
|
+
const decision = { schemaVersion: 1, route: 'repository-owner', binding, outcome: 'accepted', corrects: [], replacement: null, reason: 'Replace with the owner delivery decision reason.' };
|
|
53
|
+
return { schemaVersion: 1, binding, bindingDigest: acceptanceDigest(binding), comment: decisionComment(decision), effect: 'Prepared only; the repository owner must author a new explicit decision. No source decision or remote mutation was created.' };
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function decisionComment(decision) { return `${marker}\n\`\`\`json\n${JSON.stringify(decision, null, 2)}\n\`\`\``; }
|
|
57
|
+
export function parseAcceptanceDecision(body) {
|
|
58
|
+
requireThat(typeof body === 'string' && Buffer.byteLength(body) <= 65536 && body.startsWith(marker), 'Not a bounded delivery-decision source');
|
|
59
|
+
const match = body.match(/^<!-- lighthouse-delivery-decision:v1 -->\n```json\n([\s\S]+)\n```\s*$/);
|
|
60
|
+
requireThat(match, 'Malformed delivery-decision source');
|
|
61
|
+
const decision = parseJson(match[1]);
|
|
62
|
+
requireThat(decision.schemaVersion === 1 && decision.route === 'repository-owner' && ['accepted', 'rejected', 'revoked', 'superseded'].includes(decision.outcome), 'Unsupported delivery decision');
|
|
63
|
+
requireThat(Array.isArray(decision.corrects) && decision.corrects.length <= 32 && decision.corrects.every(id => /^github:[1-9][0-9]*:issue-comment:[1-9][0-9]*$/.test(id)) && new Set(decision.corrects).size === decision.corrects.length && typeof decision.reason === 'string' && decision.reason.trim().length > 0 && decision.reason.length <= 4096, 'Invalid correction references or decision reason');
|
|
64
|
+
requireThat(['accepted', 'rejected'].includes(decision.outcome) || decision.corrects.length > 0, 'Withdrawal requires explicit predecessor decisions');
|
|
65
|
+
requireThat(decision.outcome === 'superseded' ? /^github:[1-9][0-9]*:issue-comment:[1-9][0-9]*$/.test(decision.replacement) : decision.replacement === null, 'Invalid replacement decision');
|
|
66
|
+
return decision;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
async function authenticateSource(api, repository, commentId) {
|
|
70
|
+
requireThat(positive(commentId), 'Invalid source comment ID');
|
|
71
|
+
const comment = await api(`issues/comments/${commentId}`);
|
|
72
|
+
const decision = parseAcceptanceDecision(comment.body), binding = decision.binding;
|
|
73
|
+
const adopted = await acceptancePolicy(api, repository, binding?.policy?.revision);
|
|
74
|
+
const { repo } = adopted;
|
|
75
|
+
requireThat(canonical(binding.policy) === canonical(adopted.reference), 'Policy binding changed');
|
|
76
|
+
requireThat(comment.id === commentId && comment.user?.id === repo.owner.id && comment.user.type === 'User' && comment.created_at === comment.updated_at, 'Source must be an unedited explicit owner decision');
|
|
77
|
+
requireThat(binding.repository?.id === repo.id && binding.repository.fullName === repository && positive(binding.workItem?.number) && comment.issue_url === `https://api.github.com/repos/${repository}/issues/${binding.workItem.number}`, 'Source repository or work item mismatch');
|
|
78
|
+
const issue = await api(`issues/${binding.workItem.number}`), pr = await api(`pulls/${binding.candidate?.number}`);
|
|
79
|
+
requireThat(!issue.pull_request && issue.id === binding.workItem.id && issue.html_url === binding.workItem.url && binding.candidate.kind === 'pull-request' && pr.id === binding.candidate.id && pr.html_url === binding.candidate.url && pr.base.repo.id === repo.id && pr.head.repo?.id === repo.id && pr.head.sha === binding.candidate.head, 'Candidate or work item changed');
|
|
80
|
+
requireThat(canonical(await retainedSubject(api, binding.scope)) === canonical(binding.scope) && canonical(await retainedSubject(api, binding.criteria)) === canonical(binding.criteria), 'Retained scope or criteria mismatch');
|
|
81
|
+
return { ...adopted, decision, source: { id: comment.id, url: comment.html_url, createdAt: comment.created_at, updatedAt: comment.updated_at, body: comment.body, sha256: sha(comment.body), actor: { id: comment.user.id, login: comment.user.login } }, id: `github:${repo.id}:issue-comment:${comment.id}` };
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
async function authenticateProducer(api, adopted, producer, { producing = false } = {}) {
|
|
85
|
+
requireThat(producer?.kind === 'github-actions' && positive(producer.runId) && positive(producer.attempt), 'Eligible producer execution is required');
|
|
86
|
+
const run = await api(`actions/runs/${producer.runId}/attempts/${producer.attempt}`);
|
|
87
|
+
requireThat(run.id === producer.runId && run.run_attempt === producer.attempt && run.repository?.id === adopted.repo.id && run.event === 'workflow_dispatch' && run.actor?.id === adopted.repo.owner.id && run.triggering_actor?.id === adopted.repo.owner.id && run.path === adopted.policy.producer.workflow && run.head_sha === producer.revision && revision(run.head_sha), 'Producer execution is not the adopted owner-dispatched workflow');
|
|
88
|
+
requireThat(producing ? ['queued', 'in_progress'].includes(run.status) : run.status === 'completed' && run.conclusion === 'success', 'Producer execution is not usable');
|
|
89
|
+
const workflow = await sourceFile(api, run.path, run.head_sha);
|
|
90
|
+
requireThat(workflow.blob === adopted.policy.producer.workflowBlob && producer.workflowBlob === workflow.blob, 'Producer workflow content is not adopted');
|
|
91
|
+
return run;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export async function produceAcceptance(api, repository, commentId, execution) {
|
|
95
|
+
const authenticated = await authenticateSource(api, repository, commentId);
|
|
96
|
+
const workflow = await sourceFile(api, authenticated.policy.producer.workflow, execution.revision);
|
|
97
|
+
const producer = { kind: 'github-actions', runId: execution.runId, attempt: execution.attempt, revision: execution.revision, workflowBlob: workflow.blob, observedAt: new Date().toISOString() };
|
|
98
|
+
await authenticateProducer(api, authenticated, producer, { producing: true });
|
|
99
|
+
const receipt = { schemaVersion: 1, id: authenticated.id, route: 'repository-owner', decision: authenticated.decision, source: authenticated.source, producer };
|
|
100
|
+
validatePublishable({ 'receipt.json': JSON.stringify(receipt) });
|
|
101
|
+
return receipt;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
async function sourceHistory(api, issue) {
|
|
105
|
+
const comments = [];
|
|
106
|
+
for (let page = 1; page <= 10; page++) {
|
|
107
|
+
const batch = await api(`issues/${issue}/comments?per_page=100&page=${page}`);
|
|
108
|
+
requireThat(Array.isArray(batch), 'Source history unavailable'); comments.push(...batch);
|
|
109
|
+
if (batch.length < 100) return comments;
|
|
110
|
+
}
|
|
111
|
+
throw Error('Source history exceeds 1000-comment bound; completeness unavailable');
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
async function retainedHistory(api, repository, readArtifact) {
|
|
115
|
+
const receipts = [], seenRuns = new Set();
|
|
116
|
+
let expectedRuns;
|
|
117
|
+
for (let page = 1; page <= 10; page++) {
|
|
118
|
+
const result = await api(`actions/workflows/lighthouse-delivery-acceptance.yml/runs?event=workflow_dispatch&per_page=100&page=${page}`);
|
|
119
|
+
requireThat(Array.isArray(result.workflow_runs) && result.total_count <= 1000, 'Producer history exceeds bound or is incomplete');
|
|
120
|
+
expectedRuns ??= result.total_count;
|
|
121
|
+
requireThat(expectedRuns === result.total_count, 'Producer history changed during collection; retry verification');
|
|
122
|
+
for (const run of result.workflow_runs) {
|
|
123
|
+
requireThat(!seenRuns.has(run.id), 'Producer history pagination contains duplicates'); seenRuns.add(run.id);
|
|
124
|
+
const artifacts = await api(`actions/runs/${run.id}/artifacts?per_page=100`);
|
|
125
|
+
requireThat(Array.isArray(artifacts.artifacts) && artifacts.total_count === artifacts.artifacts.length && artifacts.total_count <= 100, 'Producer artifact history incomplete');
|
|
126
|
+
const retained = artifacts.artifacts.filter(a => /^lighthouse-delivery-acceptance-[1-9][0-9]*-[1-9][0-9]*$/.test(a.name));
|
|
127
|
+
requireThat((run.conclusion !== 'success' || retained.length > 0) && retained.every(a => !a.expired), 'Producer receipt expired or missing; historical corrections cannot be excluded');
|
|
128
|
+
for (const artifact of retained) receipts.push(await readArtifact(api, repository, run.id, artifact.name, 'receipt.json'));
|
|
129
|
+
requireThat(receipts.length <= 1000, 'Retained decision history exceeds bound');
|
|
130
|
+
}
|
|
131
|
+
if (result.workflow_runs.length < 100) { requireThat(seenRuns.size === expectedRuns, 'Producer history pagination incomplete'); return receipts; }
|
|
132
|
+
}
|
|
133
|
+
throw Error('Producer history exceeds pagination bound');
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
export async function verifyAcceptance(api, repository, { binding, receipts = [] }, { readArtifact = readActionsJson, now = () => new Date().toISOString() } = {}) {
|
|
137
|
+
const observedAt = now(), unavailable = reason => ({ schemaVersion: 1, status: 'unavailable', reason, recoveryOwner: 'repository-owner', observedAt, bindingDigest: acceptanceDigest(binding ?? null), historyCoverage: 'incomplete' });
|
|
138
|
+
try {
|
|
139
|
+
const adopted = await acceptancePolicy(api, repository, binding?.policy?.revision);
|
|
140
|
+
requireThat(binding.repository?.id === adopted.repo.id && binding.repository.fullName === repository && positive(binding.workItem?.number), 'Requested repository or work item mismatch');
|
|
141
|
+
const refreshed = await prepareAcceptance(api, repository, { policyRevision: binding.policy.revision, issue: binding.workItem.number, pullRequest: binding.candidate?.number, scope: binding.scope, criteria: binding.criteria });
|
|
142
|
+
requireThat(canonical(refreshed.binding) === canonical(binding), 'Requested candidate binding is stale or invalid');
|
|
143
|
+
requireThat(Array.isArray(receipts) && receipts.length <= 100, 'Receipt collection exceeds bound');
|
|
144
|
+
const retained = await retainedHistory(api, repository, readArtifact);
|
|
145
|
+
const history = await sourceHistory(api, binding.workItem.number);
|
|
146
|
+
const sources = [];
|
|
147
|
+
for (const comment of history.filter(c => c.user?.id === adopted.repo.owner.id && c.body?.startsWith(marker))) {
|
|
148
|
+
const decision = parseAcceptanceDecision(comment.body);
|
|
149
|
+
if (acceptanceDigest(decision.binding) === acceptanceDigest(binding)) sources.push(comment);
|
|
150
|
+
}
|
|
151
|
+
const relevant = retained.filter(r => acceptanceDigest(r.decision?.binding ?? null) === acceptanceDigest(binding));
|
|
152
|
+
requireThat(relevant.every(r => receipts.some(s => canonical(s) === canonical(r))), 'Required retained history omitted from consumer input');
|
|
153
|
+
const verified = new Map();
|
|
154
|
+
for (const receipt of receipts) {
|
|
155
|
+
requireThat(receipt.schemaVersion === 1 && receipt.route === 'repository-owner', 'Unsupported receipt version or route');
|
|
156
|
+
if (acceptanceDigest(receipt.decision?.binding) !== acceptanceDigest(binding)) continue;
|
|
157
|
+
validatePublishable({ 'receipt.json': JSON.stringify(receipt) });
|
|
158
|
+
const source = await authenticateSource(api, repository, receipt.source?.id);
|
|
159
|
+
requireThat(receipt.id === source.id && canonical(receipt.decision) === canonical(source.decision) && canonical(receipt.source) === canonical(source.source), 'Retained receipt and authenticated source differ');
|
|
160
|
+
await authenticateProducer(api, source, receipt.producer);
|
|
161
|
+
const artifact = await readArtifact(api, repository, receipt.producer.runId, `lighthouse-delivery-acceptance-${receipt.source.id}-${receipt.producer.attempt}`, 'receipt.json');
|
|
162
|
+
requireThat(canonical(artifact) === canonical(receipt), 'Receipt was not retained by the adopted producer execution');
|
|
163
|
+
if (verified.has(receipt.id)) requireThat(canonical(verified.get(receipt.id).decision) === canonical(receipt.decision) && canonical(verified.get(receipt.id).source) === canonical(receipt.source), 'Conflicting retry at one logical decision');
|
|
164
|
+
else verified.set(receipt.id, receipt);
|
|
165
|
+
}
|
|
166
|
+
requireThat(sources.length === verified.size && sources.every(c => verified.has(`github:${adopted.repo.id}:issue-comment:${c.id}`)), 'Decision history has missing producer receipts');
|
|
167
|
+
for (const receipt of verified.values()) if (receipt.decision.replacement) {
|
|
168
|
+
const match = receipt.decision.replacement.match(/^github:([1-9][0-9]*):issue-comment:([1-9][0-9]*)$/);
|
|
169
|
+
requireThat(Number(match[1]) === adopted.repo.id, 'Replacement belongs to another repository');
|
|
170
|
+
const replacement = await authenticateSource(api, repository, Number(match[2]));
|
|
171
|
+
requireThat(replacement.id !== receipt.id && replacement.decision.outcome === 'accepted', 'Supersession must name a separate owner acceptance source; replacement qualification remains independent');
|
|
172
|
+
}
|
|
173
|
+
const corrected = new Set();
|
|
174
|
+
for (const receipt of verified.values()) for (const id of receipt.decision.corrects) {
|
|
175
|
+
requireThat(id !== receipt.id && verified.has(id), 'Correction predecessor missing or self-referential'); corrected.add(id);
|
|
176
|
+
}
|
|
177
|
+
const visited = new Set(), visiting = new Set();
|
|
178
|
+
const visit = id => {
|
|
179
|
+
requireThat(!visiting.has(id), 'Cyclic correction history');
|
|
180
|
+
if (visited.has(id)) return;
|
|
181
|
+
visiting.add(id);
|
|
182
|
+
for (const prior of verified.get(id).decision.corrects) visit(prior);
|
|
183
|
+
visiting.delete(id); visited.add(id);
|
|
184
|
+
};
|
|
185
|
+
for (const id of verified.keys()) visit(id);
|
|
186
|
+
const active = [...verified.values()].filter(r => !corrected.has(r.id));
|
|
187
|
+
requireThat(active.length <= 1, 'Conflicting decisions require an explicit owner correction');
|
|
188
|
+
const current = active[0];
|
|
189
|
+
return { schemaVersion: 1, status: current?.decision.outcome ?? 'pending', decisionId: current?.id ?? null, reason: current ? 'Authenticated owner decision for this exact binding' : 'Adopted healthy route has no owner decision for this binding', observedAt, bindingDigest: acceptanceDigest(binding), historyCoverage: 'complete-at-observation', decisionIds: [...verified.keys()].sort(), sourceUrls: sources.map(s => s.html_url).sort(), limitations: ['Current only as of observation; artifact expiry, edited sources or inaccessible history make acceptance unavailable.', 'PR candidates only; artifact and delegated routes are unavailable.'] };
|
|
190
|
+
} catch (error) { return unavailable(error.message); }
|
|
191
|
+
}
|
|
@@ -7,7 +7,7 @@ import { createIssueControlManifest } from './issue-control-contract.mjs';
|
|
|
7
7
|
import { housekeepingFiles } from './housekeeping-assets.mjs';
|
|
8
8
|
|
|
9
9
|
const [target, revision, ...flags] = process.argv.slice(2);
|
|
10
|
-
if (!target || revision !== 'package' && !/^[a-f0-9]{40}$/.test(revision ?? '') || flags.some(x => !['--apply', '--replace-reviewed', '--with-propose', '--with-implement', '--with-completion', '--with-maintenance', '--with-product-change', '--with-unattended', '--with-epic', '--with-issue-control'].includes(x))) throw Error('Usage: install-workflows <repository> <immutable-lighthouse-commit|package> [--apply] [--replace-reviewed] [--with-propose] [--with-implement] [--with-completion] [--with-maintenance] [--with-product-change] [--with-unattended] [--with-epic] [--with-issue-control]');
|
|
10
|
+
if (!target || revision !== 'package' && !/^[a-f0-9]{40}$/.test(revision ?? '') || flags.some(x => !['--apply', '--replace-reviewed', '--with-propose', '--with-implement', '--with-completion', '--with-maintenance', '--with-product-change', '--with-unattended', '--with-epic', '--with-issue-control', '--with-delivery-acceptance'].includes(x))) throw Error('Usage: install-workflows <repository> <immutable-lighthouse-commit|package> [--apply] [--replace-reviewed] [--with-propose] [--with-implement] [--with-completion] [--with-maintenance] [--with-product-change] [--with-unattended] [--with-epic] [--with-issue-control] [--with-delivery-acceptance]');
|
|
11
11
|
const packageVersion = revision === 'package' ? JSON.parse(await readFile(new URL('../package.json', import.meta.url), 'utf8')).version : null;
|
|
12
12
|
const apply = flags.includes('--apply'), replace = flags.includes('--replace-reviewed');
|
|
13
13
|
const compilerCommand = process.env.LIGHTHOUSE_GH_AW_EXECUTABLE ?? 'gh';
|
|
@@ -29,6 +29,7 @@ if (flags.includes('--with-maintenance')) {
|
|
|
29
29
|
planned.push({ path, content });
|
|
30
30
|
console.log(`${apply ? 'Write' : 'Would write'} ${path}; configure the report index and explicitly activate maintenance separately.`);
|
|
31
31
|
}
|
|
32
|
+
if (flags.includes('--with-delivery-acceptance')) files.push('lighthouse-delivery-acceptance.yml');
|
|
32
33
|
if (unattended) files.push('lighthouse-sdlc-unattended.yml');
|
|
33
34
|
if (epic) files.push('lighthouse-sdlc-epic.yml');
|
|
34
35
|
for (const name of files) {
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { readFile, writeFile } from 'node:fs/promises';
|
|
2
|
+
import { createIssueApi } from './github-rest.mjs';
|
|
3
|
+
import { collectGithubMeasurements } from './measurement-github.mjs';
|
|
4
|
+
import { deriveMeasurements, metricDefinitions, stableJson } from './measurement.mjs';
|
|
5
|
+
|
|
6
|
+
export async function measurementCli(args, env = process.env) {
|
|
7
|
+
const operation = args[0], option = name => args[args.indexOf(name) + 1];
|
|
8
|
+
if (operation === 'collect') {
|
|
9
|
+
const repository = option('--repo');
|
|
10
|
+
if (!args.includes('--repo') || !args.includes('--start') || !args.includes('--end') || !args.includes('--output') || !env.GH_TOKEN) throw Error('collect requires --repo owner/repo --start UTC --end UTC --output frozen.json and read-only GH_TOKEN');
|
|
11
|
+
const bounds = Object.fromEntries([['--max-pages', 'maxPages'], ['--max-issues', 'maxIssues'], ['--max-prs', 'maxPullRequests'], ['--max-runs', 'maxRuns'], ['--max-requests', 'maxRequests']].filter(([flag]) => args.includes(flag)).map(([flag, key]) => [key, Number(option(flag))]));
|
|
12
|
+
const result = await collectGithubMeasurements(repository, { start: option('--start'), end: option('--end') }, { api: createIssueApi(repository, env), bounds, workflows: args.includes('--workflows') ? option('--workflows').split(',') : [] });
|
|
13
|
+
await writeFile(option('--output'), stableJson(result) + '\n', { flag: 'wx', mode: 0o600 });
|
|
14
|
+
process.stdout.write(JSON.stringify({ status: 'collected', records: result.records.length, gaps: result.collections.filter(c => c.status !== 'complete').length }) + '\n');
|
|
15
|
+
return result;
|
|
16
|
+
}
|
|
17
|
+
if (operation === 'render') {
|
|
18
|
+
if (!args.includes('--input') || !args.includes('--output')) throw Error('render requires --input frozen.json --output report.html');
|
|
19
|
+
const bytes = await readFile(option('--input'));
|
|
20
|
+
if (bytes.length > 4 * 1024 * 1024) throw Error('Frozen measurement input exceeds 4 MiB');
|
|
21
|
+
const { renderMeasurementReport } = await import('./measurement-report.mjs');
|
|
22
|
+
const bundle = JSON.parse(bytes), html = renderMeasurementReport(bundle);
|
|
23
|
+
await writeFile(option('--output'), html, { flag: 'wx', mode: 0o600 });
|
|
24
|
+
process.stdout.write(JSON.stringify({ status: 'rendered', inputSha256: deriveMeasurements(bundle).inputSha256 }) + '\n');
|
|
25
|
+
return html;
|
|
26
|
+
}
|
|
27
|
+
if (!['definitions', 'derive'].includes(operation) || operation === 'derive' && !args.includes('--input')) throw Error('Usage: lighthouse-sdlc measurements definitions | derive --input frozen.json [--output metrics.json] | collect --repo owner/repo --start UTC --end UTC --output frozen.json | render --input frozen.json --output report.html');
|
|
28
|
+
let result;
|
|
29
|
+
if (operation === 'definitions') result = { schemaVersion: 1, definitions: metricDefinitions };
|
|
30
|
+
else {
|
|
31
|
+
const bytes = await readFile(option('--input'));
|
|
32
|
+
if (bytes.length > 4 * 1024 * 1024) throw Error('Frozen measurement input exceeds 4 MiB');
|
|
33
|
+
result = deriveMeasurements(JSON.parse(bytes));
|
|
34
|
+
}
|
|
35
|
+
const text = stableJson(result) + '\n';
|
|
36
|
+
if (args.includes('--output')) await writeFile(option('--output'), text, { flag: 'wx', mode: 0o600 });
|
|
37
|
+
else process.stdout.write(text);
|
|
38
|
+
return result;
|
|
39
|
+
}
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
import { readFile } from 'node:fs/promises';
|
|
2
|
+
import { createActionsJsonReader } from './actions-artifact.mjs';
|
|
3
|
+
import { validateStageResult } from './contracts.mjs';
|
|
4
|
+
import { measurementRecord, measurementHash, deriveMeasurements } from './measurement.mjs';
|
|
5
|
+
|
|
6
|
+
const kinds = ['issue', 'pull-request', 'issue-pr-relation', 'workflow-attempt', 'workflow-job', 'stage-result', 'human-touch', 'human-wait', 'agent-step', 'usage', 'delegated-integration', 'revert', 'external'];
|
|
7
|
+
const positive = value => Number.isSafeInteger(value) && value > 0;
|
|
8
|
+
const fullSha = value => /^[a-f0-9]{40}$/.test(value ?? '');
|
|
9
|
+
|
|
10
|
+
export async function collectGithubMeasurements(repository, window, { api, readArtifact = createActionsJsonReader, now = () => new Date().toISOString(), bounds = {}, workflows = [] } = {}) {
|
|
11
|
+
bounds = { maxPages: 2, maxIssues: 20, maxPullRequests: 20, maxRuns: 20, maxAttempts: 3, maxRequests: 200, ...bounds };
|
|
12
|
+
if (!/^[\w.-]+\/[\w.-]+$/.test(repository) || !Number.isFinite(Date.parse(window?.start)) || !Number.isFinite(Date.parse(window?.end)) || Date.parse(window.start) >= Date.parse(window.end) || Object.values(bounds).some(n => !positive(n) || n > 1000) || !Array.isArray(workflows) || workflows.length > 8 || workflows.some(w => !/^[\w.-]+\.ya?ml$/.test(w))) throw Error('Invalid bounded repository/window collection request');
|
|
13
|
+
const resources = [], collections = Object.fromEntries(kinds.map(kind => [kind, { kind, status: 'complete', reasons: [] }])), records = [];
|
|
14
|
+
let requests = 0;
|
|
15
|
+
function gap(kind, reason, unavailable = false) {
|
|
16
|
+
const item = collections[kind];
|
|
17
|
+
if (item.status !== 'unavailable') item.status = unavailable ? 'unavailable' : 'incomplete';
|
|
18
|
+
if (!item.reasons.includes(reason)) item.reasons.push(reason);
|
|
19
|
+
}
|
|
20
|
+
const read = async path => {
|
|
21
|
+
if (++requests > bounds.maxRequests) throw Object.assign(Error('Request budget exhausted'), { code: 'REQUEST_BOUND' });
|
|
22
|
+
try { const result = await api(path, 'GET'); resources.push({ path, observedAt: now(), status: 'observed' }); return result; }
|
|
23
|
+
catch (error) { resources.push({ path, observedAt: now(), status: 'unavailable', httpStatus: Number.isInteger(error.status) ? error.status : null, reason: error.code === 'REQUEST_BOUND' ? 'request-bound' : 'source-read-failed' }); throw error; }
|
|
24
|
+
};
|
|
25
|
+
async function pages(path, kind, key, stop) {
|
|
26
|
+
const values = [], seen = new Set();
|
|
27
|
+
for (let page = 1; page <= bounds.maxPages; page++) {
|
|
28
|
+
const resource = `${path}${path.includes('?') ? '&' : '?'}per_page=100&page=${page}`;
|
|
29
|
+
let result;
|
|
30
|
+
try { result = await read(resource); } catch { gap(kind, `Unreadable ${resource}`); return values; }
|
|
31
|
+
const items = key ? result?.[key] : result;
|
|
32
|
+
if (!Array.isArray(items) || key && (!Number.isSafeInteger(result.total_count) || result.total_count < items.length)) { gap(kind, `Invalid inventory ${resource}`); return values; }
|
|
33
|
+
for (const item of items) {
|
|
34
|
+
const itemId = positive(item.id) ? `id:${item.id}` : kind === 'issue-pr-relation' && item.event === 'cross-referenced' && positive(item.source?.issue?.id) && item.created_at ? `relation:${item.source.issue.id}:${item.created_at}` : null;
|
|
35
|
+
if (!itemId && kind === 'issue-pr-relation' && item.event !== 'cross-referenced') continue;
|
|
36
|
+
if (!itemId || seen.has(itemId)) { gap(kind, `Missing or duplicate source identity in ${resource}`); continue; }
|
|
37
|
+
seen.add(itemId); values.push(item);
|
|
38
|
+
}
|
|
39
|
+
resources.at(-1).count = items.length;
|
|
40
|
+
if (items.length < 100 || stop?.(items)) return values;
|
|
41
|
+
if (page === bounds.maxPages) gap(kind, `Pagination bound reached at ${resource}`);
|
|
42
|
+
}
|
|
43
|
+
return values;
|
|
44
|
+
}
|
|
45
|
+
const startedAt = now();
|
|
46
|
+
if (Date.parse(window.end) > Date.parse(startedAt)) throw Error('Collection window must end no later than collection start');
|
|
47
|
+
const repo = await read('');
|
|
48
|
+
if (repo.full_name !== repository || !positive(repo.id)) throw Error('GitHub repository identity mismatch');
|
|
49
|
+
const identity = { id: repo.id, fullName: repository };
|
|
50
|
+
const source = (id, url, data, revision) => ({ id, url, observedAt: now(), revision: revision ?? `sha256:${measurementHash(data)}` });
|
|
51
|
+
const add = (kind, id, time, data, url, revision) => {
|
|
52
|
+
if (!Number.isFinite(Date.parse(time))) { gap(kind, `Missing event time for ${id}`); return null; }
|
|
53
|
+
const record = measurementRecord(identity, kind, id, time, data, source(id, url, data, revision)); records.push(record); return record;
|
|
54
|
+
};
|
|
55
|
+
const inside = time => Date.parse(time) >= Date.parse(window.start) && Date.parse(time) < Date.parse(window.end);
|
|
56
|
+
const issueInventory = await pages(`issues?state=all&since=${encodeURIComponent(window.start)}&sort=created&direction=desc`, 'issue', null, items => items.some(i => Date.parse(i.created_at) < Date.parse(window.start)));
|
|
57
|
+
const issues = issueInventory.filter(i => !i.pull_request && inside(i.created_at));
|
|
58
|
+
if (issues.length > bounds.maxIssues) gap('issue', 'Issue selection bound reached');
|
|
59
|
+
const prNumbers = new Set(), relations = [];
|
|
60
|
+
for (const issue of issues.slice(0, bounds.maxIssues)) {
|
|
61
|
+
add('issue', `issue:${issue.id}`, issue.created_at, { id: issue.id, number: issue.number, state: issue.state, createdAt: issue.created_at, closedAt: issue.closed_at }, issue.html_url);
|
|
62
|
+
const timeline = await pages(`issues/${issue.number}/timeline`, 'issue-pr-relation');
|
|
63
|
+
for (const event of timeline) {
|
|
64
|
+
if (event.event === 'cross-referenced' && event.source?.issue?.pull_request) {
|
|
65
|
+
const referenced = event.source.issue;
|
|
66
|
+
const match = referenced.pull_request.url?.match(new RegExp(`^https://api\\.github\\.com/repos/${repository.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}/pulls/([1-9][0-9]*)$`));
|
|
67
|
+
if (!match || !positive(referenced.id)) continue;
|
|
68
|
+
const relation = add('issue-pr-relation', positive(event.id) ? `timeline:${event.id}` : `timeline:issue:${issue.id}:pr:${referenced.id}:${event.created_at}`, event.created_at, { issueId: issue.id, prId: referenced.id, relation: 'github-cross-reference' }, positive(event.id) ? `${issue.html_url}#event-${event.id}` : issue.html_url);
|
|
69
|
+
if (relation) { relations.push(relation); prNumbers.add(Number(match[1])); }
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
const comments = await pages(`issues/${issue.number}/comments?since=${encodeURIComponent(window.start)}`, 'human-touch');
|
|
73
|
+
for (const comment of comments.filter(c => inside(c.created_at) && c.user?.type === 'User')) add('human-touch', `comment:${comment.id}`, comment.created_at, { actorType: 'User', actorId: comment.user.id, event: 'comment' }, comment.html_url);
|
|
74
|
+
}
|
|
75
|
+
const pullInventory = await pages('pulls?state=all&sort=created&direction=desc', 'pull-request', null, items => items.some(p => Date.parse(p.created_at) < Date.parse(window.start)));
|
|
76
|
+
for (const pr of pullInventory.filter(p => inside(p.created_at))) prNumbers.add(pr.number);
|
|
77
|
+
if (prNumbers.size > bounds.maxPullRequests) gap('pull-request', 'PR selection bound reached');
|
|
78
|
+
for (const number of [...prNumbers].sort((a, b) => b - a).slice(0, bounds.maxPullRequests)) {
|
|
79
|
+
let pr;
|
|
80
|
+
try { pr = await read(`pulls/${number}`); } catch { gap('pull-request', `PR ${number} unavailable`); continue; }
|
|
81
|
+
if (!positive(pr.id) || pr.base?.repo?.id !== repo.id || !fullSha(pr.head?.sha)) { gap('pull-request', `PR ${number} identity mismatch`); continue; }
|
|
82
|
+
const links = relations.filter(r => r.data.prId === pr.id);
|
|
83
|
+
add('pull-request', `pull-request:${pr.id}`, pr.created_at, { id: pr.id, number, head: pr.head.sha, createdAt: pr.created_at, merged: pr.merged === true, mergedAt: pr.merged_at, mergeCommitSha: pr.merge_commit_sha, linkedIssueIds: [...new Set(links.map(r => r.data.issueId))].sort(), linkProof: links.map(r => ({ issueId: r.data.issueId, sourceId: r.id, sha256: r.source.sha256 })) }, pr.html_url);
|
|
84
|
+
const reviews = await pages(`pulls/${number}/reviews`, 'human-touch');
|
|
85
|
+
for (const review of reviews.filter(r => inside(r.submitted_at) && r.user?.type === 'User' && r.state !== 'PENDING')) add('human-touch', `review:${review.id}`, review.submitted_at, { actorType: 'User', actorId: review.user.id, event: 'review', state: review.state }, review.html_url);
|
|
86
|
+
const comments = await pages(`issues/${number}/comments?since=${encodeURIComponent(window.start)}`, 'human-touch');
|
|
87
|
+
for (const comment of comments.filter(c => inside(c.created_at) && c.user?.type === 'User')) add('human-touch', `comment:${comment.id}`, comment.created_at, { actorType: 'User', actorId: comment.user.id, event: 'comment' }, comment.html_url);
|
|
88
|
+
}
|
|
89
|
+
const query = `created=${encodeURIComponent(`${window.start}..${window.end}`)}`;
|
|
90
|
+
const runs = new Map();
|
|
91
|
+
for (const workflow of workflows.length ? workflows : [null]) {
|
|
92
|
+
const list = await pages(`${workflow ? `actions/workflows/${workflow}/runs` : 'actions/runs'}?${query}`, 'workflow-attempt', 'workflow_runs');
|
|
93
|
+
for (const run of list.filter(r => inside(r.created_at))) runs.set(run.id, run);
|
|
94
|
+
}
|
|
95
|
+
if (runs.size > bounds.maxRuns) gap('workflow-attempt', 'Workflow run selection bound reached');
|
|
96
|
+
for (const selected of [...runs.values()].sort((a, b) => Date.parse(b.created_at) - Date.parse(a.created_at) || b.id - a.id).slice(0, bounds.maxRuns)) {
|
|
97
|
+
if (!positive(selected.run_attempt)) { gap('workflow-attempt', `Missing attempt identity for run ${selected.id}`); continue; }
|
|
98
|
+
if (selected.run_attempt > bounds.maxAttempts) gap('workflow-attempt', `Attempt bound reached for run ${selected.id}`);
|
|
99
|
+
let artifactInventory;
|
|
100
|
+
try { artifactInventory = await read(`actions/runs/${selected.id}/artifacts?per_page=100`); }
|
|
101
|
+
catch { artifactInventory = null; gap('stage-result', `Artifacts unavailable for run ${selected.id}`); gap('usage', `Artifacts unavailable for run ${selected.id}`); }
|
|
102
|
+
const artifacts = Array.isArray(artifactInventory?.artifacts) ? artifactInventory.artifacts : [];
|
|
103
|
+
if (artifactInventory && (!Array.isArray(artifactInventory.artifacts) || artifactInventory.total_count !== artifacts.length || artifacts.length > 100)) { gap('stage-result', `Artifact inventory incomplete for run ${selected.id}`); gap('usage', `Artifact inventory incomplete for run ${selected.id}`); }
|
|
104
|
+
for (let attempt = 1; attempt <= Math.min(selected.run_attempt, bounds.maxAttempts); attempt++) {
|
|
105
|
+
let run;
|
|
106
|
+
try { run = await read(`actions/runs/${selected.id}/attempts/${attempt}`); }
|
|
107
|
+
catch { gap('workflow-attempt', `Run ${selected.id} attempt ${attempt} unavailable`); continue; }
|
|
108
|
+
if (run.id !== selected.id || run.run_attempt !== attempt || run.repository?.id !== repo.id || !fullSha(run.head_sha)) { gap('workflow-attempt', `Run ${selected.id} attempt identity mismatch`); continue; }
|
|
109
|
+
add('workflow-attempt', `run:${run.id}:attempt:${attempt}`, run.status === 'completed' ? run.updated_at : run.created_at, { runId: run.id, attempt, workflow: run.path, status: run.status, conclusion: run.conclusion ?? 'pending', head: run.head_sha }, run.html_url, run.head_sha);
|
|
110
|
+
const jobs = await pages(`actions/runs/${run.id}/attempts/${attempt}/jobs`, 'agent-step', 'jobs');
|
|
111
|
+
const agentSteps = [];
|
|
112
|
+
for (const job of jobs) {
|
|
113
|
+
add('workflow-job', `job:${job.id}`, job.completed_at ?? job.started_at ?? run.created_at, { runId: run.id, attempt, jobId: job.id, name: job.name, status: job.status, conclusion: job.conclusion, publication: ['publish', 'Validate, publish and release'].includes(job.name) }, job.html_url, run.head_sha);
|
|
114
|
+
for (const step of (job.steps ?? []).filter(s => s.name === 'OpenCode progress and result' && s.conclusion !== 'skipped')) {
|
|
115
|
+
const id = `run:${run.id}:attempt:${attempt}:job:${job.id}:step:${step.number}`;
|
|
116
|
+
const record = add('agent-step', id, step.completed_at ?? step.started_at ?? run.created_at, { runId: run.id, attempt, jobId: job.id, stepNumber: step.number, stepName: step.name, startedAt: step.started_at, completedAt: step.completed_at, conclusion: step.conclusion }, job.html_url, run.head_sha);
|
|
117
|
+
if (record) agentSteps.push(record);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
const resultArtifacts = artifacts.filter(a => new RegExp(`^lighthouse-(?:(triage|refine|propose|implement|integrate|review|apply-review)-)?result-[1-9][0-9]*-${attempt}$`).test(a.name));
|
|
121
|
+
let runtime;
|
|
122
|
+
for (const artifact of resultArtifacts) {
|
|
123
|
+
if (artifact.expired) { gap('stage-result', `Expired artifact ${artifact.id}`); continue; }
|
|
124
|
+
try {
|
|
125
|
+
const reader = await readArtifact(read, repository, run.id, artifact.name), envelope = reader('envelope.json');
|
|
126
|
+
const result = envelope?.result;
|
|
127
|
+
if (validateStageResult(result).length) throw Error('Invalid source assessment');
|
|
128
|
+
runtime = reader('runtime.json', true);
|
|
129
|
+
add('stage-result', `artifact:${artifact.id}:stage-result`, run.updated_at, { runId: run.id, attempt, artifactId: artifact.id, stage: result.stage, status: result.status, blockingCause: result.status === 'blocked' && result.output?.handoff ? 'human' : 'unknown', pendingReviewCount: result.pendingReview.length, unavailableCheckCount: result.unavailableChecks.length, missingEvidenceCount: result.missingEvidence.length, nextAction: result.nextAction.slice(0, 1000), sourceAssessment: 'worker-declared; not acceptance' }, run.html_url, run.head_sha);
|
|
130
|
+
} catch { gap('stage-result', `Result artifact ${artifact.id} unavailable, incompatible or outside archive bounds`); }
|
|
131
|
+
}
|
|
132
|
+
if (!resultArtifacts.length && agentSteps.length) gap('stage-result', `No stage result artifact for run ${run.id} attempt ${attempt}`);
|
|
133
|
+
const telemetry = artifacts.filter(a => a.name === `lighthouse-telemetry-agent-${attempt}` && !a.expired);
|
|
134
|
+
let summary;
|
|
135
|
+
if (telemetry.length === 1 && agentSteps.length === 1) {
|
|
136
|
+
try {
|
|
137
|
+
const reader = await readArtifact(read, repository, run.id, telemetry[0].name);
|
|
138
|
+
summary = reader(`lighthouse-${run.id}-${attempt}/evidence/host/telemetry-usage.json`, true) ?? reader('telemetry-usage.json', true);
|
|
139
|
+
if (summary?.schemaVersion !== 1 || !['observed', 'incomplete', 'unavailable'].includes(summary.coverage)) summary = null;
|
|
140
|
+
} catch { gap('usage', `Usage artifact unavailable or outside archive bounds for run ${run.id} attempt ${attempt}`); }
|
|
141
|
+
}
|
|
142
|
+
for (const step of agentSteps) {
|
|
143
|
+
const data = { invocationId: step.id, runId: run.id, attempt, coverage: summary?.coverage ?? 'unavailable', usageSource: summary?.source ?? 'unavailable', authenticationRoute: 'unknown', identity: { requested: runtime?.modelExecution?.requested ?? null, resolved: runtime?.modelExecution?.resolved ?? null, providerReported: runtime?.modelExecution?.providerReported ?? null }, ...Object.fromEntries(['inputTokens', 'outputTokens', 'reasoningTokens', 'cacheReadTokens', 'cacheWriteTokens'].map(field => [field, summary?.tokens?.[field] ?? null])) };
|
|
144
|
+
add('usage', `usage:${step.id}`, step.time, data, run.html_url, run.head_sha);
|
|
145
|
+
if (!summary || summary.coverage === 'unavailable') gap('usage', `Missing or unassignable usage for ${step.id}`);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
collections.issue.scope = 'Issue creation cohort in [start,end), within selected bounds';
|
|
150
|
+
collections['pull-request'].scope = 'PR creation cohort plus explicitly related PRs, within selected bounds';
|
|
151
|
+
collections['issue-pr-relation'].scope = 'Retained cross-references on selected issue timelines';
|
|
152
|
+
collections['workflow-attempt'].scope = 'Selected workflows and runs created in [start,end); event completions must also fall in the window';
|
|
153
|
+
gap('workflow-attempt', 'Earlier-created runs that may complete within the window are outside this creation-cohort collector');
|
|
154
|
+
for (const kind of ['workflow-job', 'stage-result', 'agent-step', 'usage']) collections[kind].scope = 'Native observations from the selected run creation cohort';
|
|
155
|
+
for (const kind of ['human-wait', 'delegated-integration', 'revert', 'external']) gap(kind, 'No independently qualified source adapter selected by this collector; no replacement evidence is inferred', true);
|
|
156
|
+
for (const kind of ['human-touch', 'issue-pr-relation']) if (collections.issue.status !== 'complete' || collections['pull-request'].status !== 'complete') gap(kind, 'Issue/PR population or relation coverage is incomplete');
|
|
157
|
+
for (const kind of ['agent-step', 'workflow-job', 'stage-result', 'usage']) if (collections['workflow-attempt'].status !== 'complete') gap(kind, 'Run/attempt population coverage is incomplete');
|
|
158
|
+
gap('human-touch', 'Only selected issue/PR cohorts are scanned; interactions on other work items are not enumerated');
|
|
159
|
+
collections['human-touch'].scope = 'Selected issue/PR creation cohorts and explicitly linked PRs';
|
|
160
|
+
if (collections['agent-step'].status !== 'complete') gap('workflow-job', 'Native job inventory is incomplete');
|
|
161
|
+
const packageVersion = JSON.parse(await readFile(new URL('../package.json', import.meta.url), 'utf8')).version;
|
|
162
|
+
const bundle = { schemaVersion: 1, repository: identity, window, collector: { version: 1, packageVersion, implementationSha256: measurementHash(await readFile(new URL(import.meta.url), 'utf8')), startedAt, completedAt: now(), permissions: 'read-only GET requests; no repository mutation', bounds, workflows: workflows.length ? [...workflows].sort() : ['all-repository-workflows'], resources }, collections: Object.values(collections).map(c => ({ ...c, reason: c.reasons.join('; ') || null, records: records.filter(r => r.kind === c.kind).length })), records: records.sort((a, b) => `${a.kind}:${a.id}`.localeCompare(`${b.kind}:${b.id}`)) };
|
|
163
|
+
deriveMeasurements(bundle);
|
|
164
|
+
return bundle;
|
|
165
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
import { deriveMeasurements, metricDefinitions, stableJson } from './measurement.mjs';
|
|
3
|
+
|
|
4
|
+
const theme = readFileSync(new URL(import.meta.resolve('@juangcarmona/lighthouse-ui/tokens.css')), 'utf8');
|
|
5
|
+
const escape = value => String(value ?? '').replace(/[&<>"']/g, character => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[character]);
|
|
6
|
+
const number = value => typeof value === 'number' ? escape(value) : 'unavailable';
|
|
7
|
+
function link(source, repository) {
|
|
8
|
+
try {
|
|
9
|
+
const url = new URL(source.url);
|
|
10
|
+
if (url.protocol !== 'https:' || url.username || url.password || url.search || !(url.hostname === 'github.com' && url.pathname.startsWith(`/${repository}/`) || url.hostname === 'api.github.com' && url.pathname.startsWith(`/repos/${repository}/`))) throw Error();
|
|
11
|
+
return `<a href="${escape(url.href)}" rel="noreferrer">${escape(source.id)}</a>`;
|
|
12
|
+
} catch { return `${escape(source.id)} (source link unavailable)`; }
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function renderMeasurementReport(bundle) {
|
|
16
|
+
const report = deriveMeasurements(bundle);
|
|
17
|
+
const rows = report.metrics.map(metric => {
|
|
18
|
+
const definition = metricDefinitions.find(d => d.id === metric.id);
|
|
19
|
+
const counts = metric.counts ? `<p>${Object.entries(metric.counts).map(([key, value]) => `${escape(key)}: ${number(value)}`).join(' · ')}</p>` : '';
|
|
20
|
+
const fields = metric.fields ? `<table><caption>Token field coverage</caption><thead><tr><th scope="col">Field</th><th scope="col">Observed sum</th><th scope="col">Measured N / eligible M</th><th scope="col">Status</th></tr></thead><tbody>${Object.entries(metric.fields).map(([key, field]) => `<tr><th scope="row">${escape(key)}</th><td>${number(field.value)}</td><td>${field.measured} / ${field.eligible}</td><td>${escape(field.status)}</td></tr>`).join('')}</tbody></table>` : '';
|
|
21
|
+
const identities = metric.identities ? `<details><summary>Usage identity and authentication route observations</summary><ul>${metric.identities.map(identity => `<li><code>${escape(stableJson(identity))}</code></li>`).join('')}</ul></details>` : '';
|
|
22
|
+
const sources = [...metric.sources, ...(metric.relatedSources ?? [])];
|
|
23
|
+
const seen = new Set(), unique = sources.filter(source => { const key = `${source.kind}:${source.id}`; if (seen.has(key)) return false; seen.add(key); return true; });
|
|
24
|
+
return `<section id="${escape(metric.id)}"><h2>${escape(metric.id)}</h2><p><strong>${escape(metric.status)}</strong> · ${escape(definition.classification)} · ${escape(definition.unit)}</p><p>${escape(definition.useCase)}</p><p>Numerator: <strong>${number(metric.numerator)}</strong>. Denominator: <strong>${number(metric.denominator)}</strong>. Measured coverage: ${metric.coverage.measured} / ${metric.coverage.eligible}.${metric.censored !== undefined ? ` Censored: ${metric.censored}.` : ''}</p>${counts}${fields}${identities}<p>Formula: ${escape(definition.formula)}.</p><p>${escape(definition.rules)}</p>${metric.coverage.missingCollections.length ? `<p>Collection gaps: ${escape(metric.coverage.missingCollections.join(', '))}.</p>` : ''}${metric.coverage.conflictingIds.length ? `<p>Conflicting sources: ${escape(metric.coverage.conflictingIds.join(', '))}.</p>` : ''}<details><summary>Measured source references (${unique.length})</summary><ul>${unique.map(source => `<li>${link(source, bundle.repository.fullName)} · revision ${escape(source.revision)} · content ${escape(source.sha256)} · observed ${escape(source.observedAt)}</li>`).join('')}</ul></details></section>`;
|
|
25
|
+
}).join('\n');
|
|
26
|
+
const findings = bundle.records.filter(r => r.kind === 'stage-result' || r.kind === 'workflow-job' && (r.data.publication || r.data.conclusion === 'failure') || r.kind === 'usage' && r.data.coverage === 'unavailable');
|
|
27
|
+
const findingRows = findings.map(record => `<tr><td>${escape(record.kind)}</td><td>${escape(record.data.stage ?? record.data.name ?? 'Usage')}</td><td>${escape(record.data.status ?? record.data.conclusion ?? record.data.coverage)}</td><td>${escape(record.data.blockingCause ?? '')}</td><td>${escape(record.data.nextAction ?? (record.kind === 'usage' ? 'Retain a readable usage artifact for this exact invocation; missing usage stays unknown.' : 'Inspect the linked native observation before choosing a recovery action.'))}</td><td>${link({ id: record.id, url: record.source?.url }, bundle.repository.fullName)}</td></tr>`).join('');
|
|
28
|
+
return `<!doctype html>
|
|
29
|
+
<html lang="en" data-lh-theme="system"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'"><title>Lighthouse delivery observations — ${escape(bundle.repository.fullName)}</title><style>${theme}
|
|
30
|
+
body{font:var(--lh-text-base)/var(--lh-leading) var(--lh-font-sans);margin:var(--lh-space-8) auto;max-width:76rem;padding:0 var(--lh-space-4);color:var(--lh-text);background:var(--lh-canvas)}a{color:var(--lh-action);overflow-wrap:anywhere}a:focus,summary:focus{outline:4px solid var(--lh-focus);outline-offset:4px}p,li{overflow-wrap:anywhere}h1{line-height:1.2}h2{font-size:var(--lh-text-large);overflow-wrap:anywhere}section{border-top:1px solid var(--lh-border-strong);padding:var(--lh-space-4) 0}table{border-collapse:collapse;width:100%;margin:var(--lh-space-4) 0}th,td{text-align:left;vertical-align:top;border:1px solid var(--lh-border-strong);padding:var(--lh-space-3);overflow-wrap:anywhere}caption{font-weight:bold;text-align:left}code{font-family:var(--lh-font-mono);overflow-wrap:anywhere}nav ul{columns:2}nav a{display:inline-block;min-block-size:var(--lh-space-6)}nav li{padding-block:var(--lh-space-1)}details{margin:var(--lh-space-4) 0}.scroll{overflow:auto}small{font-size:var(--lh-text-small)}@media(max-width:650px){nav ul{columns:1}body{margin:var(--lh-space-4) auto}th,td{padding:var(--lh-space-2)}}</style></head><body>
|
|
31
|
+
<header><h1>Lighthouse delivery observations</h1><p>${escape(bundle.repository.fullName)} · numeric repository ID ${bundle.repository.id}</p><p>Window: ${escape(bundle.window.start)} to ${escape(bundle.window.end)} (end excluded).</p><p>${escape(report.trust)}</p><p>Collector version ${escape(bundle.collector?.version ?? 'offline input')} · package ${escape(bundle.collector?.packageVersion ?? 'unavailable')} · observation completed ${escape(bundle.collector?.completedAt ?? 'not retained')}.</p><p>Workflow selection: ${escape(bundle.collector?.workflows?.join(', ') ?? 'See frozen input')}. Each collection retains its own population and bounds.</p></header>
|
|
32
|
+
<nav aria-label="Measurements"><ul>${report.metrics.map(m => `<li><a href="#${escape(m.id)}">${escape(m.id)}</a></li>`).join('')}</ul></nav>
|
|
33
|
+
<main><section><h2>Collection coverage</h2><p>Missing observations provide no zero, acceptance, deployment or effort inference. Observed subtotals remain separate from complete populations.</p><ul>${bundle.collections.map(c => `<li><strong>${escape(c.kind)}: ${escape(c.status)}</strong> · ${escape(c.scope ?? '')} ${escape(c.reason ?? 'No collection gap recorded')}</li>`).join('')}</ul></section>
|
|
34
|
+
<section><h2>Operator findings</h2><p>Native publication outcomes, worker assessments and missing usage are separate observations. A green run can contain a blocked review. Source next actions are escaped text and cannot trigger work.</p><div class="scroll"><table><caption>Retained observations requiring interpretation</caption><thead><tr><th scope="col">Kind</th><th scope="col">Stage or job</th><th scope="col">Observed state</th><th scope="col">Blocking cause</th><th scope="col">Source next action</th><th scope="col">Source</th></tr></thead><tbody>${findingRows || '<tr><td colspan="6">No findings in the collected population; consult coverage before interpreting this absence.</td></tr>'}</tbody></table></div></section>
|
|
35
|
+
${rows}
|
|
36
|
+
</main><footer><p>Definition version ${report.definitionVersion}. Frozen input SHA-256: <code>${report.inputSha256}</code>.</p><p>Retain the frozen JSON and exact package version for offline reproduction. This static file makes no API calls, carries no credentials and grants no delivery action or authority.</p></footer></body></html>\n`;
|
|
37
|
+
}
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { validatePublishable } from './process-publication.mjs';
|
|
3
|
+
|
|
4
|
+
export const measurementVersion = 1;
|
|
5
|
+
export const stableJson = value => JSON.stringify(value, (_key, item) => item && typeof item === 'object' && !Array.isArray(item) ? Object.fromEntries(Object.keys(item).sort().map(key => [key, item[key]])) : item);
|
|
6
|
+
export const measurementHash = value => createHash('sha256').update(stableJson(value)).digest('hex');
|
|
7
|
+
const finite = value => Number.isSafeInteger(value) && value >= 0;
|
|
8
|
+
const instant = value => typeof value === 'string' && Number.isFinite(Date.parse(value));
|
|
9
|
+
const fullSha = value => /^[a-f0-9]{40}$/.test(value ?? '');
|
|
10
|
+
const identity = value => Number.isSafeInteger(value) && value > 0;
|
|
11
|
+
|
|
12
|
+
const entries = [
|
|
13
|
+
['evidence.completeness.v1', 'records', 'Review retained provenance coverage', 'all', 'valid source-bound records / enumerated records', 'measured', 'All enumerated records; a missing collection is a coverage gap, never an empty population.'],
|
|
14
|
+
['execution.stage-outcome.v1', 'stage results', 'Separate delivery assessments from Actions outcomes', 'stage-result', 'counts by explicit passed, failed, blocked and uncertain status / eligible stage results', 'measured', 'A blocked assessment never becomes passed from a green workflow.'],
|
|
15
|
+
['execution.attempt-outcome.v1', 'workflow attempts', 'Inspect technical retries independently', 'workflow-attempt', 'counts by native conclusion / enumerated workflow attempts', 'measured', 'Each run ID and attempt is distinct; skipped work is not an agent invocation.'],
|
|
16
|
+
['execution.blocking-reason.v1', 'blocked results', 'Distinguish human decisions from technical blockers', 'stage-result', 'counts by explicit human, technical or unknown cause / blocked results', 'measured', 'Only an explicit source classification establishes human blocking.'],
|
|
17
|
+
['delivery.issue-to-pr.v1', 'seconds', 'Observe candidate lead time', 'issue', 'sum of observed issue-to-first-linked-PR seconds / issues with observed linked PR', 'measured', 'Cohort: issues created in [start,end); unlinked issues are right-censored. PR relation must be retained explicitly.'],
|
|
18
|
+
['delivery.issue-to-integration.v1', 'seconds', 'Observe integration separately from candidate creation', 'issue', 'sum of observed issue-to-first-linked-merge seconds / issues with observed linked merge', 'measured', 'Cohort: issues created in [start,end); only explicit merged PR plus full merge SHA qualifies; missing integrations are right-censored.'],
|
|
19
|
+
['autonomy.human-touches.v1', 'events', 'Observe visible human interactions', 'human-touch', 'explicit User comment/review events / enumerated touch events', 'measured', 'Exclude bots and reactions; no per-person ranking or effort inference.'],
|
|
20
|
+
['autonomy.human-wait-time.v1', 'seconds', 'Observe explicit decision waiting', 'human-wait', 'sum of clipped explicit human-wait interval seconds / observed wait intervals', 'measured', 'Clip to the window; unresolved intervals are right-censored lower bounds; overlapping intervals remain separate work-item waits.'],
|
|
21
|
+
['autonomy.delegated-integration.v1', 'integrations', 'Observe integrations with authenticated delegation', 'delegated-integration', 'unique merge identities supported by a retained verifier assessment / eligible integration records', 'inferred', 'Requires exact head/merge binding, source proof references and the integration verifier; a boolean, bot actor or merge alone is insufficient.'],
|
|
22
|
+
['delivery.confirmed-reverts.v1', 'reverts', 'Observe explicitly evidenced reversals', 'revert', 'unique reversal identities with an explicit verified source relation / eligible revert records', 'inferred', 'Requires a declared source adapter and retained original/reversal revisions; titles and commit-message guesses are excluded.'],
|
|
23
|
+
['execution.agent-step-duration.v1', 'seconds', 'Observe the actual agent execution step', 'agent-step', 'sum of measured non-skipped agent step seconds / measured agent steps', 'measured', 'Exact run/attempt/job/step identity is required; workflow, queue and model-request time are excluded.'],
|
|
24
|
+
['model.token-usage.v1', 'tokens', 'Observe usage with per-field coverage', 'usage', 'sum of measured values per token field / eligible invocations, with measured N/M per field', 'measured', 'Keep requested/resolved/provider-reported identity and authentication route separate; missing fields stay unknown and reasoning is never added again to output.'],
|
|
25
|
+
['evidence.external-unknowns.v1', 'availability', 'Expose unsupported external conclusions', 'external', 'no fabricated numerator or denominator', 'measured', 'Provider confirmation, billing, deployment, incident rates, active human effort and accepted delivery need their own independently authenticated sources.'],
|
|
26
|
+
];
|
|
27
|
+
export const metricDefinitions = entries.map(([id, unit, useCase, kind, formula, classification, rules]) => ({ id, version: 1, unit, useCase, kind, formula, classification, rules, sourceRequirements: 'Numeric repository identity, stable source/event identity, retained content digest, exact revision and safe source URL; run/attempt lineage when applicable. Offline integrity is distinct from live source authentication.', window: 'UTC [start,end); event cohorts except issue lead-time cohorts and clipped wait intervals; no future or out-of-window completions.', deduplication: 'Same kind and logical ID with identical retained bytes is one event; changed bytes at one identity are conflicting and excluded. Retries remain separate attempts, never new accepted deliveries.', coverage: 'Numerator, denominator, measured count, eligible count, missing source collections, censored count and raw source references remain visible.', unavailableReason: 'No eligible measurement, required source/adapter unavailable, invalid binding, incomplete collection or contradictory source.', privacy: 'Repository scope; no transcripts, raw logs, credentials, personal scores or individual rankings.', aggregation: 'Totals and arithmetic mean over observed samples only; no imputation, scoring, price estimation or automatic policy change.' }));
|
|
28
|
+
|
|
29
|
+
export function measurementRecord(repository, kind, id, time, data, source) {
|
|
30
|
+
const digest = measurementHash({ kind, time, data });
|
|
31
|
+
return { kind, id, time, data, source: { ...source, repositoryId: repository.id, revision: source.revision && !source.revision.startsWith('sha256:') ? source.revision : `sha256:${digest}`, sha256: digest } };
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function validSource(record, repository) {
|
|
35
|
+
const source = record.source;
|
|
36
|
+
if (!source || source.repositoryId !== repository.id || typeof source.id !== 'string' || !source.id || !instant(source.observedAt) || source.sha256 !== measurementHash({ kind: record.kind, time: record.time, data: record.data }) || !(fullSha(source.revision) || /^sha256:[a-f0-9]{64}$/.test(source.revision ?? ''))) return false;
|
|
37
|
+
if (source.revision.startsWith('sha256:') && source.revision !== `sha256:${source.sha256}`) return false;
|
|
38
|
+
try {
|
|
39
|
+
const url = new URL(source.url);
|
|
40
|
+
return url.protocol === 'https:' && !url.username && !url.password && !url.search && (!url.hash || /^#(?:issuecomment|pullrequestreview|event)-[1-9][0-9]*$/.test(url.hash)) && (url.hostname === 'github.com' && url.pathname.startsWith(`/${repository.fullName}/`) || url.hostname === 'api.github.com' && url.pathname.startsWith(`/repos/${repository.fullName}/`));
|
|
41
|
+
} catch { return false; }
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function deriveMeasurements(bundle) {
|
|
45
|
+
if (bundle?.schemaVersion !== 1 || !identity(bundle.repository?.id) || !/^[\w.-]+\/[\w.-]+$/.test(bundle.repository.fullName) || !instant(bundle.window?.start) || !instant(bundle.window?.end) || Date.parse(bundle.window.start) >= Date.parse(bundle.window.end) || !Array.isArray(bundle.records) || bundle.records.length > 10000 || !Array.isArray(bundle.collections)) throw Error('Invalid bounded measurement bundle');
|
|
46
|
+
if (Buffer.byteLength(stableJson(bundle)) > 4 * 1024 * 1024) throw Error('Measurement bundle exceeds 4 MiB');
|
|
47
|
+
validatePublishable({ 'metadata.json': stableJson({ ...bundle, records: [] }) });
|
|
48
|
+
for (const record of bundle.records) validatePublishable({ 'record.json': stableJson(record) });
|
|
49
|
+
const logicalId = record => record.kind === 'workflow-attempt' && identity(record.data?.runId) && identity(record.data?.attempt) ? `${record.data.runId}:${record.data.attempt}` : record.kind === 'usage' && record.data?.invocationId ? record.data.invocationId : record.source?.id ?? record.id;
|
|
50
|
+
const recordKey = record => `${record.kind}:${logicalId(record)}`;
|
|
51
|
+
const signature = record => measurementHash({ kind: record.kind, time: record.time, data: record.data, repositoryId: record.source?.repositoryId, sha256: record.source?.sha256, revision: record.source?.revision });
|
|
52
|
+
const start = Date.parse(bundle.window.start), end = Date.parse(bundle.window.end), byId = new Map(), conflicts = new Set();
|
|
53
|
+
for (const record of bundle.records) {
|
|
54
|
+
if (typeof record.kind !== 'string' || typeof record.id !== 'string' || !record.id || !record.data || typeof record.data !== 'object') throw Error('Invalid measurement record');
|
|
55
|
+
const key = recordKey(record);
|
|
56
|
+
if (byId.has(key) && signature(byId.get(key)) !== signature(record)) conflicts.add(key);
|
|
57
|
+
else if (!byId.has(key) || stableJson(record) < stableJson(byId.get(key))) byId.set(key, record);
|
|
58
|
+
}
|
|
59
|
+
const all = [...byId.values()].sort((a, b) => `${a.kind}:${a.id}`.localeCompare(`${b.kind}:${b.id}`));
|
|
60
|
+
const inWindow = record => instant(record.time) && Date.parse(record.time) >= start && Date.parse(record.time) < end;
|
|
61
|
+
const within = all.filter(inWindow);
|
|
62
|
+
const usable = record => !conflicts.has(recordKey(record)) && validSource(record, bundle.repository);
|
|
63
|
+
const good = within.filter(usable);
|
|
64
|
+
const collection = kind => bundle.collections.filter(c => c.kind === kind);
|
|
65
|
+
const complete = kind => collection(kind).length === 1 && collection(kind)[0].status === 'complete';
|
|
66
|
+
const metrics = [];
|
|
67
|
+
function metric(id, kinds, eligible, measured, numerator, denominator, details = {}) {
|
|
68
|
+
const required = Array.isArray(kinds) ? kinds : [kinds];
|
|
69
|
+
const missingCollections = required.filter(kind => !complete(kind));
|
|
70
|
+
const relatedConflicts = eligible.filter(r => conflicts.has(recordKey(r))).map(r => r.id);
|
|
71
|
+
const coverage = { measured: measured.length, eligible: eligible.length, missingCollections, conflictingIds: relatedConflicts };
|
|
72
|
+
const status = relatedConflicts.length ? 'conflicting' : !measured.length && (eligible.length || missingCollections.length || numerator === null) ? 'unavailable' : measured.length < eligible.length || missingCollections.length ? 'incomplete' : 'measured';
|
|
73
|
+
metrics.push({ id, definitionVersion: 1, classification: metricDefinitions.find(d => d.id === id).classification, status, numerator, denominator, coverage, sources: measured.map(r => ({ id: r.id, kind: r.kind, ...r.source })).sort((a, b) => `${a.kind}:${a.id}`.localeCompare(`${b.kind}:${b.id}`)), ...details });
|
|
74
|
+
}
|
|
75
|
+
const sourceRecords = all.filter(usable);
|
|
76
|
+
metric('evidence.completeness.v1', [...new Set([...all.map(r => r.kind), ...bundle.collections.map(c => c.kind)])], all, sourceRecords, sourceRecords.length ? sourceRecords.length : null, all.length || null, { meaning: 'Structural retained-source coverage; does not authenticate producer or freshness.' });
|
|
77
|
+
for (const [id, kind, key, accepted] of [
|
|
78
|
+
['execution.stage-outcome.v1', 'stage-result', 'status', ['ready', 'passed', 'failed', 'blocked', 'uncertain']],
|
|
79
|
+
['execution.attempt-outcome.v1', 'workflow-attempt', 'conclusion', ['success', 'failure', 'cancelled', 'timed_out', 'skipped', 'neutral', 'action_required', 'stale', 'pending']],
|
|
80
|
+
]) {
|
|
81
|
+
const eligible = within.filter(r => r.kind === kind), measured = good.filter(r => r.kind === kind && accepted.includes(r.data[key]));
|
|
82
|
+
metric(id, kind, eligible, measured, measured.length || complete(kind) && !eligible.length ? measured.length : null, eligible.length, { counts: Object.fromEntries(accepted.map(status => [status, measured.length || complete(kind) ? measured.filter(r => r.data[key] === status).length : null])) });
|
|
83
|
+
}
|
|
84
|
+
const blocked = within.filter(r => r.kind === 'stage-result' && r.data.status === 'blocked'), validBlocked = blocked.filter(usable);
|
|
85
|
+
metric('execution.blocking-reason.v1', 'stage-result', blocked, validBlocked, validBlocked.length || complete('stage-result') ? validBlocked.length : null, blocked.length, { counts: Object.fromEntries(['human', 'technical', 'unknown'].map(cause => [cause, validBlocked.length || complete('stage-result') ? validBlocked.filter(r => (['human', 'technical'].includes(r.data.blockingCause) ? r.data.blockingCause : 'unknown') === cause).length : null])) });
|
|
86
|
+
const issues = within.filter(r => r.kind === 'issue');
|
|
87
|
+
for (const [id, field] of [['delivery.issue-to-pr.v1', 'createdAt'], ['delivery.issue-to-integration.v1', 'mergedAt']]) {
|
|
88
|
+
const samples = [], measured = [];
|
|
89
|
+
for (const issue of issues.filter(usable)) {
|
|
90
|
+
const candidates = all.filter(r => r.kind === 'pull-request' && usable(r) && r.data.linkedIssueIds?.includes(issue.data.id) && r.data.linkProof?.some(proof => proof.issueId === issue.data.id && all.some(relation => relation.kind === 'issue-pr-relation' && relation.id === proof.sourceId && usable(relation) && relation.source.sha256 === proof.sha256 && relation.data.issueId === issue.data.id && relation.data.prId === r.data.id)) && instant(r.data[field]) && Date.parse(r.data[field]) >= Date.parse(issue.time) && Date.parse(r.data[field]) < end && (field !== 'mergedAt' || r.data.merged === true && fullSha(r.data.mergeCommitSha)));
|
|
91
|
+
candidates.sort((a, b) => Date.parse(a.data[field]) - Date.parse(b.data[field]) || a.id.localeCompare(b.id));
|
|
92
|
+
if (candidates[0]) { measured.push(issue, candidates[0], ...all.filter(relation => relation.kind === 'issue-pr-relation' && relation.data.issueId === issue.data.id && relation.data.prId === candidates[0].data.id && usable(relation))); samples.push({ issueId: issue.id, pullRequestId: candidates[0].id, seconds: (Date.parse(candidates[0].data[field]) - Date.parse(issue.time)) / 1000 }); }
|
|
93
|
+
}
|
|
94
|
+
metric(id, ['issue', 'pull-request'], issues, measured.filter(r => r.kind === 'issue'), samples.length ? samples.reduce((sum, s) => sum + s.seconds, 0) : null, samples.length, { eligibleIssues: issues.length, censored: issues.length - samples.length, samples, relatedSources: measured.filter(r => r.kind !== 'issue').map(r => ({ id: r.id, ...r.source })), meanSeconds: samples.length ? samples.reduce((sum, s) => sum + s.seconds, 0) / samples.length : null });
|
|
95
|
+
}
|
|
96
|
+
const touches = within.filter(r => r.kind === 'human-touch' && r.data.actorType !== 'Bot'), human = touches.filter(r => usable(r) && r.data.actorType === 'User' && identity(r.data.actorId) && ['comment', 'review'].includes(r.data.event));
|
|
97
|
+
metric('autonomy.human-touches.v1', 'human-touch', touches, human, human.length || complete('human-touch') ? human.length : null, touches.length, { activeHumanSeconds: null });
|
|
98
|
+
const waits = all.filter(r => r.kind === 'human-wait' && instant(r.data.start) && Date.parse(r.data.start) < end && (!r.data.end || Date.parse(r.data.end) > start));
|
|
99
|
+
const intervals = waits.filter(r => usable(r) && r.data.cause === 'human' && (r.data.end === null || instant(r.data.end) && Date.parse(r.data.end) >= Date.parse(r.data.start)));
|
|
100
|
+
const samples = intervals.map(r => ({ id: r.id, seconds: (Math.min(end, r.data.end ? Date.parse(r.data.end) : end) - Math.max(start, Date.parse(r.data.start))) / 1000, censored: r.data.end === null || Date.parse(r.data.end) > end }));
|
|
101
|
+
metric('autonomy.human-wait-time.v1', 'human-wait', waits, intervals, samples.length ? samples.reduce((sum, s) => sum + s.seconds, 0) : null, intervals.length, { samples, censored: samples.filter(s => s.censored).length, activeHumanSeconds: null });
|
|
102
|
+
for (const [id, kind, adapter] of [['autonomy.delegated-integration.v1', 'delegated-integration', 'lighthouse.integration.v1'], ['delivery.confirmed-reverts.v1', 'revert', 'lighthouse.revert.v1']]) {
|
|
103
|
+
const eligible = within.filter(r => r.kind === kind);
|
|
104
|
+
const measured = eligible.filter(r => usable(r) && r.data.verification?.adapter === adapter && r.data.verification.status === 'verified-at-collection' && fullSha(r.data.head) && fullSha(r.data.merge) && r.data.verification.sourceIds?.length >= 2 && r.data.verification.bindingSha256 === measurementHash({ repositoryId: bundle.repository.id, head: r.data.head, merge: r.data.merge }) && r.data.verification.sourceIds.every(id => all.some(s => s.id === id && usable(s))) && (kind === 'delegated-integration' ? r.data.verification.sourceIds.some(id => all.some(s => s.id === id && s.kind === 'integration-authorization' && s.data.head === r.data.head && usable(s))) && r.data.verification.sourceIds.some(id => all.some(s => s.id === id && s.kind === 'integration-merge' && s.data.head === r.data.head && s.data.merge === r.data.merge && usable(s))) : r.data.verification.sourceIds.some(id => all.some(s => s.id === id && s.kind === 'reversal-source' && s.data.reverts === r.data.head && s.data.reversal === r.data.merge && usable(s)))));
|
|
105
|
+
const identities = new Set(measured.map(r => `${r.data.head}:${r.data.merge}`));
|
|
106
|
+
metric(id, kind, eligible, measured, identities.size || complete(kind) && !eligible.length ? identities.size : null, eligible.length, { limitation: 'Retained adapter assessment, not a fresh authentication. No title, actor, boolean or workflow-success inference.' });
|
|
107
|
+
}
|
|
108
|
+
const steps = within.filter(r => r.kind === 'agent-step' && r.data.conclusion !== 'skipped');
|
|
109
|
+
const measuredSteps = steps.filter(r => usable(r) && identity(r.data.runId) && identity(r.data.attempt) && identity(r.data.jobId) && Number.isSafeInteger(r.data.stepNumber) && r.data.stepNumber > 0 && r.data.stepName === 'OpenCode progress and result' && instant(r.data.startedAt) && instant(r.data.completedAt) && Date.parse(r.data.completedAt) >= Date.parse(r.data.startedAt));
|
|
110
|
+
const stepSeconds = measuredSteps.map(r => ({ id: r.id, seconds: (Date.parse(r.data.completedAt) - Date.parse(r.data.startedAt)) / 1000 }));
|
|
111
|
+
metric('execution.agent-step-duration.v1', 'agent-step', steps, measuredSteps, stepSeconds.length ? stepSeconds.reduce((s, x) => s + x.seconds, 0) : null, measuredSteps.length, { samples: stepSeconds, meaning: 'Native agent wrapper step wall time; not model-request or CPU time.' });
|
|
112
|
+
const usage = within.filter(r => r.kind === 'usage'), fields = ['inputTokens', 'outputTokens', 'reasoningTokens', 'cacheReadTokens', 'cacheWriteTokens'];
|
|
113
|
+
const usableUsage = usage.filter(r => usable(r) && typeof r.data.invocationId === 'string' && r.data.invocationId && r.data.usageSource && r.data.authenticationRoute && r.data.identity && ['observed', 'incomplete', 'unavailable'].includes(r.data.coverage));
|
|
114
|
+
const fieldCoverage = Object.fromEntries(fields.map(field => {
|
|
115
|
+
const measured = usableUsage.filter(r => r.data.coverage !== 'unavailable' && finite(r.data[field]));
|
|
116
|
+
const total = measured.reduce((sum, r) => sum + r.data[field], 0), representable = Number.isSafeInteger(total);
|
|
117
|
+
return [field, { value: measured.length && representable ? total : null, measured: measured.length, eligible: usage.length, status: measured.length && representable ? measured.length === usage.length && complete('usage') && measured.every(r => r.data.coverage === 'observed') ? 'measured' : 'incomplete' : 'unavailable' }];
|
|
118
|
+
}));
|
|
119
|
+
metric('model.token-usage.v1', 'usage', usage, usableUsage.filter(r => fields.some(field => finite(r.data[field])) && r.data.coverage !== 'unavailable'), null, usage.length, { fields: fieldCoverage, identities: usableUsage.map(r => ({ id: r.id, ...r.data.identity, authenticationRoute: r.data.authenticationRoute, usageSource: r.data.usageSource })), actualBilledCost: null, billableOutputTokens: null });
|
|
120
|
+
const usageMetric = metrics.at(-1);
|
|
121
|
+
if (usageMetric.status === 'measured' && Object.values(fieldCoverage).some(field => field.status !== 'measured')) usageMetric.status = 'incomplete';
|
|
122
|
+
metric('evidence.external-unknowns.v1', 'external', [], [], null, null, { providerConfirmation: null, actualBilledCost: null, deployment: null, incidents: null, activeHumanEffort: null, acceptedDelivery: null, reason: 'The first report does not contain independently authenticated sources for these conclusions.' });
|
|
123
|
+
return { schemaVersion: 1, definitionVersion: 1, inputSha256: measurementHash(bundle), repository: bundle.repository, window: bundle.window, trust: 'Reproducible projection of retained observations; offline integrity does not establish live authenticity or freshness.', metrics, limitations: bundle.collections.filter(c => c.status !== 'complete').map(c => ({ kind: c.kind, status: c.status, reason: c.reason ?? 'Source incomplete' })).sort((a, b) => a.kind.localeCompare(b.kind)), conflictingRecordIds: [...conflicts].sort() };
|
|
124
|
+
}
|
package/src/sdlc.mjs
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
import { measurementCli } from './measurement-cli.mjs';
|
|
3
|
+
import { acceptanceCli } from './delivery-acceptance-cli.mjs';
|
|
2
4
|
import { practiceCli } from './practice-cli.mjs';
|
|
3
5
|
import { access, mkdir, readFile, writeFile } from 'node:fs/promises';
|
|
4
6
|
import { constants } from 'node:fs';
|
|
@@ -395,11 +397,15 @@ async function runGithubLabels(args) {
|
|
|
395
397
|
}
|
|
396
398
|
|
|
397
399
|
const command = process.argv[2] ?? 'verify';
|
|
398
|
-
if (!['practices', 'telemetry', 'contract', 'verify', 'aliases', 'triage', 'state', 'stage-result', 'browser-e2e', 'evidence', 'control-plane', 'memory', 'launch', 'decompose', 'stacked', 'route', 'github-triage', 'github-decompose', 'reconcile-labels', 'github-labels'].includes(command)) {
|
|
399
|
-
console.error('Usage: lighthouse-sdlc <practices|telemetry|contract|verify|aliases|triage|state|stage-result|browser-e2e|evidence|control-plane|memory|launch|decompose|stacked|route|github-triage|github-decompose|reconcile-labels|github-labels>');
|
|
400
|
+
if (!['measurements', 'delivery-acceptance', 'practices', 'telemetry', 'contract', 'verify', 'aliases', 'triage', 'state', 'stage-result', 'browser-e2e', 'evidence', 'control-plane', 'memory', 'launch', 'decompose', 'stacked', 'route', 'github-triage', 'github-decompose', 'reconcile-labels', 'github-labels'].includes(command)) {
|
|
401
|
+
console.error('Usage: lighthouse-sdlc <measurements|delivery-acceptance|practices|telemetry|contract|verify|aliases|triage|state|stage-result|browser-e2e|evidence|control-plane|memory|launch|decompose|stacked|route|github-triage|github-decompose|reconcile-labels|github-labels>');
|
|
400
402
|
process.exit(2);
|
|
401
403
|
}
|
|
402
|
-
if (command === '
|
|
404
|
+
if (command === 'measurements') {
|
|
405
|
+
await measurementCli(process.argv.slice(3));
|
|
406
|
+
} else if (command === 'delivery-acceptance') {
|
|
407
|
+
await acceptanceCli(process.argv.slice(3));
|
|
408
|
+
} else if (command === 'practices') {
|
|
403
409
|
console.log(JSON.stringify(await practiceCli(process.argv.slice(3)), null, 2));
|
|
404
410
|
} else if (command === 'telemetry') {
|
|
405
411
|
await telemetryCli(process.argv.slice(3));
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
name: Lighthouse delivery acceptance
|
|
2
|
+
on:
|
|
3
|
+
workflow_dispatch:
|
|
4
|
+
inputs:
|
|
5
|
+
decision_comment:
|
|
6
|
+
description: Numeric ID of the owner's unedited delivery-decision issue comment
|
|
7
|
+
type: string
|
|
8
|
+
required: true
|
|
9
|
+
permissions: {}
|
|
10
|
+
jobs:
|
|
11
|
+
record:
|
|
12
|
+
if: github.actor == github.repository_owner && github.triggering_actor == github.repository_owner
|
|
13
|
+
runs-on: ubuntu-24.04
|
|
14
|
+
permissions:
|
|
15
|
+
contents: read
|
|
16
|
+
issues: read
|
|
17
|
+
pull-requests: read
|
|
18
|
+
actions: read
|
|
19
|
+
steps:
|
|
20
|
+
- uses: actions/checkout@v5
|
|
21
|
+
with:
|
|
22
|
+
repository: juangcarmona/lighthouse
|
|
23
|
+
ref: __LIGHTHOUSE_REF__
|
|
24
|
+
persist-credentials: false
|
|
25
|
+
- uses: actions/setup-node@v5
|
|
26
|
+
with:
|
|
27
|
+
node-version: 24
|
|
28
|
+
- name: Authenticate and retain the explicit owner decision
|
|
29
|
+
env:
|
|
30
|
+
GH_TOKEN: ${{ github.token }}
|
|
31
|
+
LIGHTHOUSE_DECISION_COMMENT: ${{ inputs.decision_comment }}
|
|
32
|
+
run: node src/packages/sdlc/src/sdlc.mjs delivery-acceptance produce --output receipt.json
|
|
33
|
+
- uses: actions/upload-artifact@v7
|
|
34
|
+
with:
|
|
35
|
+
name: lighthouse-delivery-acceptance-${{ inputs.decision_comment }}-${{ github.run_attempt }}
|
|
36
|
+
path: receipt.json
|
|
37
|
+
if-no-files-found: error
|
|
38
|
+
retention-days: 90
|