@juangcarmona/lighthouse-sdlc 0.24.5 → 0.25.1

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 CHANGED
@@ -188,3 +188,7 @@ Lighthouse-authored material in this package is licensed under [Apache-2.0](LICE
188
188
  ## Runner telemetry
189
189
 
190
190
  The [telemetry contract](telemetry.md) covers collection from first startup, native OpenCode activity, resource observations, hosted workflow artifacts, per-stream replay and optional OTLP export. Independent applications and collectors own presentation. Existing installations adopt the runner wrapper and refreshed workflow projection through their documented update routes.
191
+
192
+ ## Engineering practice evidence
193
+
194
+ The [practice evidence contract](practice-evidence.md) defines versioned source observations and common cumulative levels. Measurement integrity, native execution, hosting enforcement and current certification remain separate checks.
@@ -0,0 +1,9 @@
1
+ # Practice evidence
2
+
3
+ Use `lighthouse-sdlc practices catalog` to read common definitions. Use `validate --input <file>` for structural checks and an unauthenticated report; offline declarations remain unavailable for certification. Use `github --input <file>` to read and verify an exact native test execution with authenticated `gh` access.
4
+
5
+ The native request contains `context` (numeric repository identity, ref, commit, scope/module inventory and shared profile), `runId`, `attempt`, `jobId`, `workflow`, `stepName` and `command`. The adapter requires a unique direct test command in the pinned workflow and a matching completed native job/step. It extracts one reconciled Node TAP or spec summary from that step's logs and reads effective branch rules without changing them. Missing logs or mismatched identity fail collection. Unknown enforcement remains a certification gap.
6
+
7
+ The producer's committed workflow and test command are the execution authority. This adapter does not inspect arbitrary scanners or turn arbitrary output into test evidence. Restrict an assessment's scope to the tests actually declared by that command. Exact measurements can establish a practice result while other practices or enforcement remain missing. Read the [full contract](../practice-evidence.md) before interpreting a level.
8
+
9
+ Use `history --input <file>` to aggregate existing assessment receipts under an explicit period and optional per-group sampling expectations. Historical output remains separate from current certification.
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"],
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"],
14
14
  "routes": ["supervised", "plan-only", "unattended", "hotfix", "stacked"],
15
15
  "metaCommands": ["ff", "hotfix", "decompose", "stacked"],
16
16
  "gates": ["triaged", "ready", "planned", "done"],
package/issue-control.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # Issue-control SDK
2
2
 
3
- The `./issue-control` export supplies `createIssueControl`, `parseIssueComment`, `parseIssueIntent` and `validateIssueIntent`. The [intent schema](schemas/issue-control-intent.schema.json) describes version 1; runtime validation also checks canonical JSON and UTF-8 byte limits. This implementation is awaiting packed-consumer and actual-user native qualification. Source availability does not establish a published or adopted release.
3
+ The `./issue-control` export supplies `createIssueControl`, `parseIssueComment`, `parseIssueIntent` and `validateIssueIntent`. The [intent schema](schemas/issue-control-intent.schema.json) describes version 1; runtime validation also checks canonical JSON and UTF-8 byte limits. The original contract was published in SDLC 0.22.0 after source-owned owner-user qualification. Current release, consumer adoption and connected App-user outcomes require their own revision-bound receipts; see [issue #119](https://github.com/juangcarmona/lighthouse/issues/119).
4
4
 
5
5
  ## Adoption
6
6
 
@@ -34,6 +34,8 @@ const reconciled = await control.reconcile(prepared);
34
34
 
35
35
  `prepare` returns either a prepared object with `version`, `intent`, `key`, `payloadDigest` and `effect`, or an explicit unavailable/rejected state. Call `submit` only for a prepared object. `observe` and `prepare` perform reads only. They report source eligibility separately from execution readiness and can become stale while a request queues; source admission rechecks current authority.
36
36
 
37
+ `observe` includes a `prerequisites` object on each Refine/Propose assessment: `installedContract`, `writeAuthority`, `repositoryPolicy`, `sourceReservations` and `stageEvidence`. Each reports `availability` and an optional reason. A check skipped after an earlier unmet prerequisite stays unavailable with `earlier-prerequisite-not-met`. Valid direct owner entry reports `owner-direct-entry`; it does not claim triage evidence. These observations add no reservation or execution authority.
38
+
37
39
  The transport receives `{scope, repository?, path, method, body?, optional?, apiVersion?}`. Account scope uses `GET user`; repository paths are relative to the explicitly bound repository. Use the actual connected user's credentials, honor the requested API version, return parsed provider JSON, and map optional 404 to `null`. HTTP failures expose a numeric `status`; uncertain network failures retain uncertainty. No credentials, default transport, environment token lookup or ambient network access is supplied by this module. Comments are posted directly as that user. A bot or installation token cannot substitute for the acting account.
38
40
 
39
41
  `readAuthority({api, repository, actor, metadata})` must return verified `actorId`, `repositoryId`, and boolean `commentWrite`/`dispatchWrite` capabilities for the actual credentials. Missing or mismatched evidence denies writes. The current contract supports the personal repository owner; other identities are explicitly unsupported. Reading repository variables may require additional token permission; a denial makes policy unavailable, rather than assuming automation is enabled.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@juangcarmona/lighthouse-sdlc",
3
- "version": "0.24.5",
3
+ "version": "0.25.1",
4
4
  "type": "module",
5
5
  "description": "Provider-neutral SDLC skills, commands and route contracts for Lighthouse adopters",
6
6
  "repository": {
@@ -47,7 +47,8 @@
47
47
  "LICENSE",
48
48
  "NOTICE",
49
49
  "telemetry.md",
50
- "issue-control.md"
50
+ "issue-control.md",
51
+ "practice-evidence.md"
51
52
  ],
52
53
  "bin": {
53
54
  "lighthouse-sdlc": "./src/sdlc.mjs"
@@ -102,7 +103,12 @@
102
103
  "./telemetry-opencode": "./src/telemetry-opencode.mjs",
103
104
  "./schemas/telemetry-event.schema.json": "./schemas/telemetry-event.schema.json",
104
105
  "./issue-control": "./src/issue-control.mjs",
105
- "./schemas/issue-control-intent.schema.json": "./schemas/issue-control-intent.schema.json"
106
+ "./schemas/issue-control-intent.schema.json": "./schemas/issue-control-intent.schema.json",
107
+ "./practice-catalog": "./src/practice-catalog.mjs",
108
+ "./practice-observation": "./src/practice-observation.mjs",
109
+ "./practice-evaluator": "./src/practice-evaluator.mjs",
110
+ "./practice-github": "./src/practice-github.mjs",
111
+ "./practice-history": "./src/practice-history.mjs"
106
112
  },
107
113
  "license": "Apache-2.0"
108
114
  }
@@ -0,0 +1,51 @@
1
+ # Engineering practice evidence
2
+
3
+ The package-owned catalog defines common cumulative L0–L3 criteria. Import `@juangcarmona/lighthouse-sdlc/practice-catalog` and `@juangcarmona/lighthouse-sdlc/practice-observation` for the definitions and observation validator.
4
+
5
+ An observation binds measurements, production module inventory, collection counts, exclusions and applicability to a SHA-256 digest. It identifies the numeric repository, exact commit, workflow/run/attempt/job, producer version, time and HTTPS source. Validation checks structure and integrity; it does not authenticate a producer or certify a practice. A source resolver must independently verify execution and configured CI/merge enforcement before current certification.
6
+
7
+ L1 requires actual passing security assessments and tests. L2 adds per-module coverage of 80% lines and 70% branches, executed Gherkin specifications, an SBOM and an explicit passing license policy. L3 adds method complexity of at most 15 cyclomatic and 30 CRAP, plus applicable DAST. A library or CLI without an HTTP application surface may justify DAST non-applicability through the shared profile. Missing tools or permission are gaps. Current evidence must match the assessed commit and definition and be no older than 14 days.
8
+
9
+ Mutation, hygiene, performance and restoration remain complementary. Mutation's covered-code target of 80% is informational; neither absence nor failure blocks a level. Historical aggregates cannot certify current code or authorize receipt deletion. No reporting API installs scanners, changes repository policy or activates gates.
10
+
11
+ ## Evaluate current evidence
12
+
13
+ Import `evaluatePractices` from `@juangcarmona/lighthouse-sdlc/practice-evaluator`. Supply `context`, `observations`, an evaluation time and a trusted `resolveSource` callback. The callback must independently retrieve the execution report and return its exact `observationDigest`, `verified: true` and observed enforcement (`status`, `ci`, `merge`, HTTPS `sources`). It must never return verification merely because an input file says it passed. Unresolved authority is `unavailable`.
14
+
15
+ The GitHub adapter `collectGithubTests` supplies that resolver from authenticated read-only API and log collection. The CLI uses it through `lighthouse-sdlc practices github --input source-request.json`; see the [command guide](commands/practices.md). The committed workflow and command remain the producing repository's authority. The initial adapter supports direct Node test or npm test commands with a single Node TAP or spec summary; other report formats require a producer-owned adapter. It preserves skipped tests as incomplete execution and checks required-check integration identity. Rules with bypass actors do not establish universal mandatory enforcement.
16
+
17
+ A `validate --input observations.json` report can inspect local observations but cannot authenticate them. It consequently cannot certify their practices. The evaluator exposes measurement state and enforcement gaps separately: `met` with an unverified gate is not a certified mandatory control. L0 requires an independently verified L1 failure or below-standard measurement. Missing evidence alone remains `unverified`.
18
+
19
+ ## Historical periods
20
+
21
+ Use `lighthouse-sdlc practices history --input history-request.json` or `aggregatePracticeHistory` from the `practice-history` export. Supply assessment receipts and a half-open `period` (`start`, `end`). Optional `expectations` identify an exact context, catalog/level versions and expected `samples` for each compatible group. Without an expected cadence, sampling coverage remains explicitly unknown. Missing periods are visible even when no assessment was collected.
22
+
23
+ The report separates incompatible contexts and definitions, deduplicates exact source runs and retries, rejects contradictions and retains level distributions, observation coverage, gaps, numeric measurement ranges/first/last values and source references. Levels are never averaged. Reports are historical summaries, cannot be passed into current evaluation as observations and authorize no deletion of receipts. The caller retains authority for the original assessment receipts and their retention.
24
+
25
+ ## Native request example
26
+
27
+ Replace every source identifier below with values from the same completed run. `stepName` must match the native step and its unique direct command in the committed workflow. The declared scope covers the tests actually executed by that command.
28
+
29
+ ```json
30
+ {
31
+ "context": {
32
+ "repository": { "id": 123, "fullName": "owner/repository" },
33
+ "ref": "refs/heads/main",
34
+ "commit": "0123456789abcdef0123456789abcdef01234567",
35
+ "scope": { "id": "node-tests", "modules": ["application"] },
36
+ "profile": "web-application"
37
+ },
38
+ "runId": 456,
39
+ "attempt": 1,
40
+ "jobId": 789,
41
+ "workflow": ".github/workflows/ci.yml",
42
+ "stepName": "Run npm test",
43
+ "command": "npm test"
44
+ }
45
+ ```
46
+
47
+ ```sh
48
+ lighthouse-sdlc practices github --input source-request.json > assessment.json
49
+ ```
50
+
51
+ For library consumers, `collectGithubTests(request)` returns `observations`, its native `authority` receipt and a source resolver. Pass those observations and resolver to `evaluatePractices` with the same context. Keep the report and native source URLs together. The report can show `tests: met` while the overall level remains `unverified` because security or enforcement evidence is missing.
@@ -82,7 +82,9 @@ export async function collectIssueControlFacts({ api, repository, number, actor,
82
82
  if (supported) try { reservation = await reservations(read, repository, metadata.owner.login, issue, comments, capability, readArtifact); }
83
83
  catch { reservation = { availability: 'unavailable', reason: 'reservation-evidence-unavailable', active: [] }; }
84
84
  const actions = { comment: supported ? writeAllowed('commentWrite') ?? { eligible: true, availability: 'available' } : refusal('installed-contract-unsupported', 'unsupported') };
85
+ const stageEvidence = {};
85
86
  for (const stage of ['refine', 'propose']) {
87
+ stageEvidence[stage] = { availability: 'unavailable', reason: 'earlier-prerequisite-not-met' };
86
88
  if (!supported || !capability.stages.includes(stage)) { actions[stage] = refusal('stage-contract-unsupported', 'unsupported'); continue; }
87
89
  if (writeAllowed('dispatchWrite')) { actions[stage] = writeAllowed('dispatchWrite'); continue; }
88
90
  if (!policyKnown) { actions[stage] = unavailable('policy-unavailable'); continue; }
@@ -93,12 +95,32 @@ export async function collectIssueControlFacts({ api, repository, number, actor,
93
95
  if (reservation.availability !== 'available') { actions[stage] = unavailable(reservation.reason); continue; }
94
96
  if (reservation.active.length) { actions[stage] = refusal('authenticated-source-reservation'); continue; }
95
97
  try {
98
+ let triage;
96
99
  if (stage === 'refine' || issue.user.login !== metadata.owner.login)
97
- await collectTriageAdmission({ api: read, repository, owner: metadata.owner.login, issue, comments, sourceRevision, readArtifact });
100
+ triage = await collectTriageAdmission({ api: read, repository, owner: metadata.owner.login, issue, comments, sourceRevision, readArtifact });
98
101
  if (stage === 'propose') await collectProposalAdmission({ api: read, repository, owner: metadata.owner.login, issue, comments, sourceRevision, taskDigest: inputDigest, readArtifact });
102
+ stageEvidence[stage] = { availability: 'available', reason: stage === 'propose' ? 'validated-refinement'
103
+ : triage ? 'validated-triage' : 'owner-direct-entry' };
99
104
  actions[stage] = { eligible: true, availability: 'available' };
100
- } catch (error) { actions[stage] = error instanceof IssueAdmissionRefusal ? { ...refusal(error.reason, error.availability), message: error.message }
101
- : unavailable(stage === 'refine' ? 'triage-not-verified' : 'proposal-prerequisites-not-verified'); }
105
+ } catch (error) {
106
+ actions[stage] = error instanceof IssueAdmissionRefusal ? { ...refusal(error.reason, error.availability), message: error.message }
107
+ : unavailable(stage === 'refine' ? 'triage-not-verified' : 'proposal-prerequisites-not-verified');
108
+ stageEvidence[stage] = { availability: actions[stage].availability, reason: actions[stage].reason };
109
+ }
110
+ }
111
+ for (const stage of ['refine', 'propose']) {
112
+ const authorityRefusal = writeAllowed('dispatchWrite');
113
+ actions[stage].prerequisites = {
114
+ installedContract: supported && capability.stages.includes(stage) ? { availability: 'available' }
115
+ : { availability: 'unsupported', reason: 'stage-contract-unsupported' },
116
+ writeAuthority: authorityRefusal ? { availability: authorityRefusal.availability, reason: authorityRefusal.reason } : { availability: 'available' },
117
+ repositoryPolicy: !policyKnown ? { availability: 'unavailable', reason: 'policy-unavailable' }
118
+ : !policy.automationEnabled ? { availability: 'denied', reason: 'automation-disabled' }
119
+ : policy.epicEnabled ? { availability: 'unsupported', reason: 'epic-admission-contract-unsupported' } : { availability: 'available' },
120
+ sourceReservations: reservation.availability !== 'available' ? { availability: reservation.availability, reason: reservation.reason }
121
+ : reservation.active.length ? { availability: 'denied', reason: 'authenticated-source-reservation' } : { availability: 'available' },
122
+ stageEvidence: stageEvidence[stage]
123
+ };
102
124
  }
103
125
  let question = { availability: 'none' };
104
126
  const pending = pendingStage(comments);
@@ -0,0 +1,29 @@
1
+ const version = '1.0.0';
2
+ const criteria = { secrets: { confirmedSecrets: 0 }, vulnerabilities: { critical: 0, high: 0 }, sast: { blocking: 0 }, tests: { allDeclaredExecuteAndPass: true }, coverage: { lines: 80, branches: 70, perModule: true }, specifications: { format: 'gherkin', allDeclaredExecuteAndPass: true }, sbom: { identifiedDocument: true }, licenses: { versionedPolicy: true, violations: 0 }, complexity: { cyclomatic: 15, crap: 30, perMethod: true }, dast: { critical: 0, high: 0 }, mutation: { coveredScore: 80, informational: true } };
3
+ const practices = [
4
+ ['secrets', 1, ['confirmedSecrets'], 'Zero confirmed secrets'],
5
+ ['vulnerabilities', 1, ['critical', 'high'], 'Zero unresolved critical or high findings'],
6
+ ['sast', 1, ['blocking'], 'Zero blocking findings'],
7
+ ['tests', 1, ['declared', 'executed', 'passed', 'failed'], 'All applicable declared tests execute and pass'],
8
+ ['coverage', 2, ['modules'], 'Every production module: lines >= 80%, branches >= 70%'],
9
+ ['specifications', 2, ['format', 'declared', 'executed', 'passed', 'failed'], 'Applicable Gherkin specifications execute and pass'],
10
+ ['sbom', 2, ['format', 'documentDigest', 'components'], 'An identified machine-readable SBOM covers the assessed scope'],
11
+ ['licenses', 2, ['policy', 'assessed', 'violations'], 'An explicit versioned license policy passes'],
12
+ ['complexity', 3, ['modules', 'methods'], 'Every applicable production method: cyclomatic <= 15, CRAP <= 30'],
13
+ ['dast', 3, ['critical', 'high'], 'Zero unresolved critical or high findings on the HTTP application surface'],
14
+ ['mutation', null, ['coveredScore', 'fullScore', 'killed', 'survived', 'timedOut', 'uncovered', 'modules'], 'Covered-code target 80%; informational and nonblocking'],
15
+ ['hygiene', null, ['checks'], 'Complementary observations; no common level threshold'],
16
+ ['performance', null, ['measurements'], 'Complementary measurements; no common level threshold'],
17
+ ['restoration', null, ['exercises'], 'Complementary executed restoration evidence; no common level threshold'],
18
+ ].map(([id, level, measurements, quality]) => ({ id, definitionVersion: version, level, measurements, quality, criteria: criteria[id] ?? {},
19
+ evidence: 'Exact execution report with measured scope, exclusions, producer and source attempt',
20
+ enforcement: level === null ? 'report-only' : 'blocking-ci-and-merge',
21
+ applicability: id === 'dast' ? 'HTTP application surface; a library or CLI without that surface may justify not-applicable' : 'Applicable to the assessed production scope',
22
+ }));
23
+ function freeze(value) { if (value && typeof value === 'object') { Object.values(value).forEach(freeze); Object.freeze(value); } return value; }
24
+ export const practiceCatalog = freeze({ schemaVersion: 1, version, levelVersion: version, maximumAgeDays: 14, emptyBranchSet: 'Not applicable only when the measured branch total is exactly zero',
25
+ profiles: { library: { httpSurface: false }, cli: { httpSurface: false }, 'http-service': { httpSurface: true }, 'web-application': { httpSurface: true } },
26
+ levelRules: { L0: 'A verified failing or below-standard L1 assessment; absence never qualifies', L1: 'All applicable basic security and test practices with mandatory enforcement', L2: 'L1 plus coverage, specifications, SBOM and licenses', L3: 'L2 plus complexity and applicable DAST' },
27
+ levels: { L0: [], L1: practices.filter(p => p.level === 1).map(p => p.id), L2: practices.filter(p => p.level && p.level <= 2).map(p => p.id), L3: practices.filter(p => p.level).map(p => p.id) }, practices,
28
+ });
29
+ export const practiceStates = freeze(['met', 'below-standard', 'failing', 'missing', 'partial', 'stale', 'unavailable', 'not-applicable']);
@@ -0,0 +1,21 @@
1
+ import { aggregatePracticeHistory } from './practice-history.mjs';
2
+ import { readFileSync, statSync } from 'node:fs';
3
+ import { practiceCatalog } from './practice-catalog.mjs';
4
+ import { evaluatePractices } from './practice-evaluator.mjs';
5
+ import { collectGithubTests } from './practice-github.mjs';
6
+
7
+ const usage = 'Usage: lighthouse-sdlc practices catalog | validate --input <file> | history --input <file> | github --input <source-request.json>';
8
+ export async function practiceCli(args) {
9
+ const [command, ...flags] = args;
10
+ if (!['catalog', 'validate', 'history', 'github'].includes(command)) throw Error(usage);
11
+ if (command === 'catalog') { if (flags.length) throw Error(usage); return practiceCatalog; }
12
+ if (flags.length !== 2 || flags[0] !== '--input' || !flags[1]) throw Error(usage);
13
+ if (statSync(flags[1]).size > 16 * 1024 * 1024) throw Error('Practice input exceeds 16 MiB');
14
+ const input = JSON.parse(readFileSync(flags[1], 'utf8'));
15
+ if (command === 'history') return aggregatePracticeHistory(input);
16
+ if (command === 'validate') return evaluatePractices({ context: input.context, observations: input.observations, now: input.now });
17
+ if (Object.keys(input).some(k => !['context', 'runId', 'attempt', 'jobId', 'workflow', 'stepName', 'command'].includes(k))) throw Error('Unknown native source request field');
18
+ const collected = await collectGithubTests(input);
19
+ const report = await evaluatePractices({ context: input.context, observations: collected.observations, resolveSource: collected.resolveSource });
20
+ return { ...report, authority: collected.authority };
21
+ }
@@ -0,0 +1,110 @@
1
+ import { practiceCatalog, practiceStates } from './practice-catalog.mjs';
2
+ import { canonical, practiceDigest, record, requirePracticeObservation, sourceIdentity, sourceUrl, validatePracticeContext } from './practice-observation.mjs';
3
+
4
+ const count = n => Number.isSafeInteger(n) && n >= 0;
5
+ const number = n => typeof n === 'number' && Number.isFinite(n) && n >= 0;
6
+ const percent = n => number(n) && n <= 100;
7
+ const nonempty = s => typeof s === 'string' && s.length > 0;
8
+ const digest = s => /^sha256:[a-f0-9]{64}$/.test(s ?? '');
9
+ const outcome = (state, ...gaps) => ({ state, gaps });
10
+ const complete = array => Array.isArray(array) && array.length > 0 && array.every(record);
11
+ function execution(m) {
12
+ if (!['declared', 'executed', 'passed', 'failed'].every(k => count(m[k])) || m.executed !== m.passed + m.failed || m.executed > m.declared) return outcome('partial', 'incomplete or inconsistent executed-test counts');
13
+ if (m.failed > 0) return outcome('failing', 'executed tests failed');
14
+ if (m.declared === 0 || m.executed !== m.declared) return outcome('partial', 'applicable declared tests did not all execute');
15
+ return outcome('met');
16
+ }
17
+ function measuredQuality(p, o) {
18
+ const m = o.measurements;
19
+ if (p.measurements.some(k => !Object.hasOwn(m, k))) return outcome('partial', 'required measurements are missing');
20
+ if (['secrets', 'vulnerabilities', 'sast', 'dast'].includes(p.id)) {
21
+ if (!record(m.scanner) || !['name', 'version', 'ruleVersion'].every(k => nonempty(m.scanner[k]))) return outcome('partial', 'scanner and rule versions are missing');
22
+ if (!p.measurements.every(k => count(m[k]))) return outcome('partial', 'security finding counts are incomplete');
23
+ return p.measurements.some(k => m[k] > 0) ? outcome('below-standard', p.quality) : outcome('met');
24
+ }
25
+ if (p.id === 'tests' || p.id === 'specifications') {
26
+ if (p.id === 'specifications' && m.format !== 'gherkin') return outcome('partial', 'executed Gherkin evidence is required');
27
+ return execution(m);
28
+ }
29
+ if (p.id === 'coverage') {
30
+ if (!complete(m.modules) || new Set(m.modules.map(v => v.id)).size !== m.modules.length || m.modules.length !== o.scope.modules.length || o.scope.modules.some(id => !m.modules.some(v => v.id === id))) return outcome('partial', 'coverage does not identify every production module');
31
+ if (m.modules.some(v => !percent(v.lines) || (!percent(v.branches) && !(v.branches === null && v.branchesTotal === 0)) )) return outcome('partial', 'module coverage measurements are incomplete');
32
+ return m.modules.some(v => v.lines < p.criteria.lines || v.branches !== null && v.branches < p.criteria.branches) ? outcome('below-standard', p.quality) : outcome('met');
33
+ }
34
+ if (p.id === 'sbom') return ['SPDX', 'CycloneDX'].includes(m.format) && digest(m.documentDigest) && count(m.components) ? outcome('met') : outcome('partial', 'complete identified SBOM required');
35
+ if (p.id === 'licenses') {
36
+ if (!record(m.policy) || !nonempty(m.policy.id) || !nonempty(m.policy.version) || !digest(m.policy.digest) || !count(m.assessed) || !count(m.violations)) return outcome('partial', 'explicit versioned license policy and assessed components required');
37
+ return m.violations > 0 ? outcome('below-standard', 'license policy violations') : outcome('met');
38
+ }
39
+ if (p.id === 'complexity') {
40
+ if (!Array.isArray(m.methods) || !complete(m.modules) || new Set(m.modules.map(v => v.id)).size !== m.modules.length || m.modules.length !== o.scope.modules.length || o.scope.modules.some(id => !m.modules.some(v => v.id === id && count(v.declaredMethods) && v.declaredMethods === m.methods.filter(method => method.module === id).length)) || m.methods.some(v => !record(v) || !nonempty(v.id) || !o.scope.modules.includes(v.module) || !number(v.cyclomatic) || !number(v.crap)) || new Set(m.methods.map(v => canonical([v.module, v.id]))).size !== m.methods.length) return outcome('partial', 'complete module/method complexity inventory required');
41
+ return m.methods.some(v => v.cyclomatic > p.criteria.cyclomatic || v.crap > p.criteria.crap) ? outcome('below-standard', p.quality) : outcome('met');
42
+ }
43
+ if (p.id === 'mutation') {
44
+ if (!percent(m.coveredScore) || !percent(m.fullScore) || !['killed', 'survived', 'timedOut', 'uncovered'].every(k => count(m[k])) || !complete(m.modules)) return outcome('partial', 'mutation scores, outcomes and module detail required');
45
+ return m.coveredScore < p.criteria.coveredScore ? outcome('below-standard', 'informational covered-code target: 80%') : outcome('met');
46
+ }
47
+ return Array.isArray(m[p.measurements[0]]) && m[p.measurements[0]].length > 0 ? outcome('met') : outcome('partial', 'complementary execution detail is missing');
48
+ }
49
+
50
+ export function selectPracticeObservations(observations) {
51
+ if (!Array.isArray(observations) || observations.length > 10000) throw Error('Supply at most 10000 practice observations');
52
+ const byAttempt = new Map(), latest = new Map();
53
+ for (const value of observations) {
54
+ requirePracticeObservation(value);
55
+ const key = sourceIdentity(value), existing = byAttempt.get(key);
56
+ if (existing && canonical(existing) !== canonical(value)) throw Error('Contradictory observations for the same source attempt');
57
+ byAttempt.set(key, value);
58
+ }
59
+ for (const value of byAttempt.values()) {
60
+ const key = sourceIdentity(value, { attempt: false }), existing = latest.get(key);
61
+ if (!existing || value.source.attempt > existing.source.attempt) latest.set(key, value);
62
+ }
63
+ return [...latest.values()].sort((a, b) => canonical([a.practice, a.source.observedAt, a.source.runId]).localeCompare(canonical([b.practice, b.source.observedAt, b.source.runId])));
64
+ }
65
+
66
+ export async function evaluatePractices({ context, observations = [], resolveSource, now = new Date().toISOString() }) {
67
+ const errors = validatePracticeContext(context);
68
+ if (errors.length) throw Error('Invalid practice context: ' + errors.join('; '));
69
+ if (!Number.isFinite(Date.parse(now))) throw Error('An explicit valid evaluation time is required');
70
+ const selected = selectPracticeObservations(observations), reports = [];
71
+ for (const practice of practiceCatalog.practices) {
72
+ const matching = selected.filter(o => o.practice === practice.id && o.repository.id === context.repository.id && o.repository.fullName === context.repository.fullName && o.commit === context.commit && o.ref === context.ref && canonical(o.scope) === canonical(context.scope));
73
+ const o = matching.sort((a, b) => Date.parse(b.source.observedAt) - Date.parse(a.source.observedAt) || b.source.runId - a.source.runId)[0];
74
+ let result, verifiedEnforcement = null;
75
+ const enforcementGaps = [];
76
+ if (!o) result = outcome('missing', 'no exact repository/revision/scope observation');
77
+ else if (o.catalogVersion !== practiceCatalog.version || o.definitionVersion !== practice.definitionVersion) result = outcome('unavailable', 'incompatible practice definition');
78
+ else if (o.applicability.profile !== context.profile) result = outcome('unavailable', 'incompatible applicability profile');
79
+ else if (Date.parse(o.source.observedAt) > Date.parse(now) || Date.parse(now) - Date.parse(o.source.observedAt) > practiceCatalog.maximumAgeDays * 86400000) result = outcome('stale', 'evidence is future-dated or exceeds 14 days');
80
+ else {
81
+ let proof;
82
+ try { proof = await resolveSource?.(structuredClone(o)); } catch { /* Authority failure remains an explicit evidence gap. */ }
83
+ if (!record(proof) || proof.observationDigest !== practiceDigest(o) || proof.verified !== true) result = outcome('unavailable', 'execution source could not be independently verified');
84
+ else {
85
+ verifiedEnforcement = structuredClone(proof.enforcement ?? null);
86
+ if (o.source.result === 'unavailable') result = outcome('unavailable', 'source result is unavailable');
87
+ else if (o.source.result !== 'success') result = outcome('failing', 'source execution failed or was cancelled');
88
+ else if (o.applicability.status === 'not-applicable') {
89
+ result = practice.id === 'dast' && practiceCatalog.profiles[context.profile].httpSurface === false ? outcome('not-applicable') : outcome('partial', 'shared profile does not justify this exemption');
90
+ } else if (o.collection.collected < o.collection.expected || o.collection.exclusions.some(e => context.scope.modules.includes(e.scope))) result = outcome('partial', 'collection or applicable production scope is incomplete');
91
+ else result = measuredQuality(practice, o);
92
+ if (practice.level !== null && result.state !== 'not-applicable') {
93
+ if (o.mode !== 'blocking') enforcementGaps.push('observation is report-only');
94
+ if (proof.enforcement?.status !== 'verified' || proof.enforcement.ci !== true || proof.enforcement.merge !== true || !Array.isArray(proof.enforcement.sources) || !proof.enforcement.sources.length || proof.enforcement.sources.some(url => !sourceUrl(url))) enforcementGaps.push('configured CI and merge enforcement is missing or unavailable');
95
+ }
96
+ }
97
+ }
98
+ reports.push({ practice: practice.id, definitionVersion: practice.definitionVersion, requiredFrom: practice.level, ...result, enforcement: verifiedEnforcement, enforcementGaps, certified: ['met', 'not-applicable'].includes(result.state) && enforcementGaps.length === 0,
99
+ observation: o ?? null });
100
+ }
101
+ const licenses = reports.find(p => p.practice === 'licenses'), sbom = reports.find(p => p.practice === 'sbom');
102
+ if (licenses.state === 'met' && sbom.state === 'met' && licenses.observation.measurements.assessed !== sbom.observation.measurements.components) Object.assign(licenses, { state: 'partial', certified: false, gaps: ['license assessment does not cover every SBOM component'] });
103
+ const levels = Object.fromEntries(['L1', 'L2', 'L3'].map(level => {
104
+ const gaps = reports.filter(p => practiceCatalog.levels[level].includes(p.practice) && !p.certified).map(p => ({ practice: p.practice, state: p.state, reasons: [...p.gaps, ...p.enforcementGaps] }));
105
+ return [level, { demonstrated: gaps.length === 0, gaps }];
106
+ }));
107
+ const negativeL1 = reports.some(p => practiceCatalog.levels.L1.includes(p.practice) && ['failing', 'below-standard'].includes(p.state));
108
+ const level = ['L3', 'L2', 'L1'].find(l => levels[l].demonstrated) ?? (negativeL1 ? 'L0' : 'unverified');
109
+ return { schemaVersion: 1, kind: 'current-practice-assessment', catalogVersion: practiceCatalog.version, levelVersion: practiceCatalog.levelVersion, assessedAt: new Date(now).toISOString(), context: structuredClone(context), level, levels, practices: reports, states: practiceStates };
110
+ }
@@ -0,0 +1,96 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { githubRequest } from './github-profile.mjs';
3
+ import { practiceCatalog } from './practice-catalog.mjs';
4
+ import { observationPayload, practiceDigest, validatePracticeContext } from './practice-observation.mjs';
5
+
6
+ export function githubPracticeLog(path) {
7
+ return new Promise((resolve, reject) => execFile('gh', ['api', '--hostname', 'github.com', path], { timeout: 30000, maxBuffer: 16 * 1024 * 1024 }, (error, stdout) => error ? reject(Error('Native test logs unavailable; check Actions read permission and retention')) : resolve(stdout)));
8
+ }
9
+
10
+ export function measurementsFromTap(log) {
11
+ if (typeof log !== 'string' || log.length > 16 * 1024 * 1024) throw Error('Bounded TAP execution output required');
12
+ const read = name => {
13
+ const values = [...log.matchAll(new RegExp('(?:^|\\n)(?:\\d{4}-[^ ]+ )?(?:#|ℹ) ' + name + ' (\\d+)\\s*(?=\\n|$)', 'g'))];
14
+ if (values.length !== 1) throw Error('TAP must contain one unambiguous ' + name + ' summary');
15
+ const value = Number(values[0][1]); if (!Number.isSafeInteger(value)) throw Error('Invalid TAP count'); return value;
16
+ };
17
+ const total = read('tests'), passed = read('pass'), failed = read('fail'), skipped = read('skipped'), todo = read('todo'), cancelled = read('cancelled');
18
+ if (total < 1 || passed + failed + skipped + todo + cancelled !== total) throw Error('TAP summary does not reconcile');
19
+ return { declared: total, executed: passed + failed, passed, failed, skipped, todo, cancelled };
20
+ }
21
+
22
+ async function mergeEnforcement(repository, branch, check, appId, request) {
23
+ const base = `repos/${repository}`, sources = [];
24
+ let known = false, required = false;
25
+ try {
26
+ const protection = await request(`${base}/branches/${encodeURIComponent(branch)}/protection`);
27
+ known = true; sources.push(`https://api.github.com/${base}/branches/${encodeURIComponent(branch)}/protection`);
28
+ required = protection.enforce_admins?.enabled === true && protection.required_status_checks?.checks?.some(c => c.context === check && c.app_id === appId) === true;
29
+ } catch { /* Effective rules may provide the mandatory check instead. */ }
30
+ try {
31
+ const rules = await request(`${base}/rules/branches/${encodeURIComponent(branch)}?per_page=100`);
32
+ if (!Array.isArray(rules) || rules.length >= 100) throw Error('Incomplete effective rule inventory');
33
+ known = true;
34
+ for (const rule of rules.filter(r => r.type === 'required_status_checks' && r.parameters?.required_status_checks?.some(c => c.context === check && c.integration_id === appId))) {
35
+ const endpoint = rule.ruleset_source_type === 'Repository' ? `repos/${rule.ruleset_source}/rulesets/${rule.ruleset_id}` : rule.ruleset_source_type === 'Organization' ? `orgs/${rule.ruleset_source}/rulesets/${rule.ruleset_id}` : null;
36
+ if (!endpoint) continue;
37
+ const policy = await request(endpoint); sources.push(`https://api.github.com/${endpoint}`);
38
+ if (policy.enforcement === 'active' && Array.isArray(policy.bypass_actors) && policy.bypass_actors.length === 0) required = true;
39
+ }
40
+ } catch { if (!required) known = false; }
41
+ return { status: known ? 'verified' : 'unavailable', merge: required, sources };
42
+ }
43
+
44
+ export function commandBlocksTestFailure(command, scripts = {}, visiting = new Set()) {
45
+ if (/^node --test(?: [\w./* -]+)?$/.test(command)) return true;
46
+ const match = /^npm (?:test|(run) ([\w:-]+))$/.exec(command);
47
+ if (!match) return false;
48
+ const name = match[1] ? match[2] : 'test';
49
+ if (visiting.has(name) || typeof scripts[name] !== 'string' || /[|;`$\n\r]/.test(scripts[name])) return false;
50
+ const next = new Set(visiting); next.add(name);
51
+ return scripts[name].split('&&').some(part => commandBlocksTestFailure(part.trim(), scripts, next));
52
+ }
53
+
54
+ export async function collectGithubTests({ context, runId, attempt, jobId, workflow, stepName, command }, { request = githubRequest, readLog = githubPracticeLog } = {}) {
55
+ const errors = validatePracticeContext(context);
56
+ if (errors.length) throw Error(errors.join('; '));
57
+ if (![runId, attempt, jobId].every(n => Number.isSafeInteger(n) && n > 0) || !/^\.github\/workflows\/[\w.-]+\.ya?ml$/.test(workflow) || typeof stepName !== 'string' || !stepName.length || typeof command !== 'string' || !/^(?:node --test [\w./* -]+|npm (?:test|run [\w:-]+))$/.test(command)) throw Error('Exact run/attempt/job, workflow, test step and supported test command are required');
58
+ const base = `repos/${context.repository.fullName}`;
59
+ const [repo, run, job, contents] = await Promise.all([
60
+ request(base), request(`${base}/actions/runs/${runId}/attempts/${attempt}`), request(`${base}/actions/jobs/${jobId}`), request(`${base}/contents/${workflow}?ref=${context.commit}`),
61
+ ]);
62
+ if (repo.id !== context.repository.id || repo.full_name !== context.repository.fullName || run.repository?.id !== repo.id || run.head_repository?.id !== repo.id || run.head_sha !== context.commit || run.head_branch !== context.ref.replace(/^refs\/heads\//, '') || run.path !== workflow || run.run_attempt !== attempt || run.status !== 'completed' || job.run_id !== runId || job.run_attempt !== attempt || job.head_sha !== context.commit || job.status !== 'completed' || !job.check_run_url?.startsWith(`https://api.github.com/${base}/check-runs/`)) throw Error('Native run/job/repository/revision/attempt binding failed');
63
+ const check = await request(job.check_run_url.slice('https://api.github.com/'.length));
64
+ if (check.head_sha !== context.commit || check.app?.slug !== 'github-actions' || !Number.isSafeInteger(check.app.id)) throw Error('Native check is not GitHub Actions at the assessed commit');
65
+ if (contents.encoding !== 'base64' || typeof contents.content !== 'string' || contents.size > 1048576) throw Error('Pinned workflow source unavailable');
66
+ const workflowSource = Buffer.from(contents.content, 'base64').toString('utf8');
67
+ const commandLines = workflowSource.split('\n').filter(line => line.trim() === 'run: ' + command || line.trim() === '- run: ' + command);
68
+ const lines = workflowSource.split('\n'), commandIndex = lines.indexOf(commandLines[0]);
69
+ const namedStep = commandIndex > 0 && lines[commandIndex - 1].trim() === '- name: ' + stepName;
70
+ const unnamedStep = commandLines[0]?.trim() === '- run: ' + command && stepName === 'Run ' + command;
71
+ if (commandLines.length !== 1 || !(namedStep || unnamedStep)) throw Error('The expected test command is not unique in the pinned workflow');
72
+ const steps = job.steps.filter(s => s.name === stepName);
73
+ if (steps.length !== 1 || steps[0].status !== 'completed' || !steps[0].started_at || !steps[0].completed_at) throw Error('Native executed test step is unavailable or ambiguous');
74
+ const step = steps[0], log = await readLog(`${base}/actions/jobs/${jobId}/logs`);
75
+ const stepLog = log.split('\n').filter(line => { const time = Date.parse(line.split(' ')[0]); return Number.isFinite(time) && time >= Date.parse(step.started_at) && time <= Date.parse(step.completed_at) + 999; }).join('\n');
76
+ const measurements = measurementsFromTap(stepLog);
77
+ let scripts = {};
78
+ if (command.startsWith('npm ')) {
79
+ try {
80
+ const manifest = await request(`${base}/contents/package.json?ref=${context.commit}`);
81
+ if (manifest.encoding === 'base64' && manifest.size < 1048576) scripts = JSON.parse(Buffer.from(manifest.content, 'base64').toString('utf8')).scripts ?? {};
82
+ } catch { /* Unknown script propagation cannot establish blocking CI. */ }
83
+ }
84
+ const ci = !/continue-on-error\s*:|shell\s*:/.test(workflowSource) && commandBlocksTestFailure(command, scripts);
85
+ const enforcement = { ...await mergeEnforcement(repo.full_name, context.ref.replace(/^refs\/heads\//, ''), job.name, check.app.id, request), ci };
86
+ const url = `https://github.com/${repo.full_name}/actions/runs/${runId}/attempts/${attempt}#job-${jobId}`;
87
+ const observation = { schemaVersion: 1, catalogVersion: practiceCatalog.version, definitionVersion: practiceCatalog.version, practice: 'tests',
88
+ repository: context.repository, ref: context.ref, commit: context.commit, scope: context.scope, mode: ci ? 'blocking' : 'report-only',
89
+ applicability: { status: 'applicable', profile: context.profile, reason: `Declared tests in native step: ${stepName}`, source: `https://github.com/${repo.full_name}/blob/${context.commit}/${workflow}` },
90
+ collection: { expected: 1, collected: 1, exclusions: [] }, measurements,
91
+ source: { workflow, runId, attempt, jobId, url, result: step.conclusion === 'success' ? 'success' : step.conclusion === 'cancelled' ? 'cancelled' : 'failure', observedAt: step.completed_at, producer: { name: 'github-actions-tap', version: '1.0.0' }, reportDigest: '' } };
92
+ observation.source.reportDigest = practiceDigest(observationPayload(observation));
93
+ const observationDigest = practiceDigest(observation);
94
+ return { observations: [observation], authority: { workflowDigest: practiceDigest(workflowSource), logDigest: practiceDigest(stepLog), enforcement },
95
+ resolveSource: candidate => practiceDigest(candidate) === observationDigest ? { verified: true, observationDigest, enforcement } : undefined };
96
+ }
@@ -0,0 +1,124 @@
1
+ import { practiceCatalog, practiceStates } from './practice-catalog.mjs';
2
+ import { canonical, practiceDigest, record, requirePracticeObservation, validatePracticeContext } from './practice-observation.mjs';
3
+
4
+ const levels = ['unverified', 'L0', 'L1', 'L2', 'L3'];
5
+ const validTime = value => typeof value === 'string' && Number.isFinite(Date.parse(value));
6
+ const sharedContext = ({ commit, ...context }) => context;
7
+ const groupKey = value => canonical([sharedContext(value.context), value.catalogVersion, value.levelVersion]);
8
+ function validateAssessment(report) {
9
+ if (!record(report) || report.schemaVersion !== 1 || report.kind !== 'current-practice-assessment' || !validTime(report.assessedAt) || !levels.includes(report.level) || typeof report.catalogVersion !== 'string' || !report.catalogVersion || typeof report.levelVersion !== 'string' || !report.levelVersion || validatePracticeContext(report.context).length || !Array.isArray(report.practices) || report.practices.length !== practiceCatalog.practices.length) throw Error('Valid current-assessment receipts are required as historical input');
10
+ const ids = new Set();
11
+ for (const p of report.practices) {
12
+ if (!record(p) || !practiceCatalog.practices.some(v => v.id === p.practice) || ids.has(p.practice) || !practiceStates.includes(p.state) || typeof p.certified !== 'boolean' || !Array.isArray(p.gaps) || !Array.isArray(p.enforcementGaps)) throw Error('Invalid or duplicate historical practice receipt');
13
+ ids.add(p.practice);
14
+ if (p.certified && (!['met', 'not-applicable'].includes(p.state) || p.gaps.length || p.enforcementGaps.length)) throw Error('Contradictory historical certification state');
15
+ if (p.observation) {
16
+ const o = requirePracticeObservation(p.observation);
17
+ if (o.practice !== p.practice || o.repository.id !== report.context.repository.id || o.commit !== report.context.commit || o.ref !== report.context.ref || o.repository.fullName !== report.context.repository.fullName || canonical(o.scope) !== canonical(report.context.scope)) throw Error('Historical observation is outside its assessment scope');
18
+ }
19
+ }
20
+ if (report.catalogVersion === practiceCatalog.version && report.levelVersion === practiceCatalog.levelVersion) {
21
+ const highest = ['L3', 'L2', 'L1'].find(level => practiceCatalog.levels[level].every(id => report.practices.find(p => p.practice === id).certified));
22
+ const negative = report.practices.some(p => practiceCatalog.levels.L1.includes(p.practice) && ['failing', 'below-standard'].includes(p.state));
23
+ if (report.level !== (highest ?? (negative ? 'L0' : 'unverified'))) throw Error('Contradictory historical level');
24
+ }
25
+ }
26
+ function sourceEntries(report) {
27
+ return report.practices.filter(p => p.observation).map(p => p.observation).map(o => ({
28
+ key: canonical([o.source.workflow, o.source.runId]), attempt: o.source.attempt, observedAt: o.source.observedAt, url: o.source.url,
29
+ })).sort((a, b) => a.key.localeCompare(b.key));
30
+ }
31
+ function compareReceipts(left, right) {
32
+ const a = sourceEntries(left), b = sourceEntries(right);
33
+ let newer = false, older = false;
34
+ if (a.length !== b.length) throw Error('Contradictory historical source coverage');
35
+ for (let i = 0; i < a.length; i++) {
36
+ const delta = a[i].attempt - b[i].attempt;
37
+ if (delta > 0) newer = true; if (delta < 0) older = true;
38
+ }
39
+ if (newer && older) throw Error('Incomparable retry vectors cannot replace a historical receipt');
40
+ if (newer) return 1; if (older) return -1;
41
+ if (practiceDigest(left) === practiceDigest(right)) return 0;
42
+ const leftContent = { ...left, assessedAt: null }, rightContent = { ...right, assessedAt: null };
43
+ if (canonical(leftContent) !== canonical(rightContent)) throw Error('Contradictory historical receipts for the same source attempts');
44
+ return Date.parse(left.assessedAt) - Date.parse(right.assessedAt);
45
+ }
46
+ function numericMeasurements(value, path = '', result = {}) {
47
+ if (typeof value === 'number' && Number.isFinite(value)) result[path] = value;
48
+ else if (Array.isArray(value)) {
49
+ for (const item of value) {
50
+ if (record(item) && typeof item.id === 'string') numericMeasurements(item, path + '[' + item.id + ']', result);
51
+ }
52
+ } else if (record(value)) for (const key of Object.keys(value).sort()) numericMeasurements(value[key], path ? path + '.' + key : key, result);
53
+ return result;
54
+ }
55
+
56
+ export function aggregatePracticeHistory({ assessments, period, expectations = [] }) {
57
+ if (!Array.isArray(assessments) || assessments.length > 10000 || !record(period) || !validTime(period.start) || !validTime(period.end) || Date.parse(period.start) >= Date.parse(period.end) || !Array.isArray(expectations) || expectations.length > 10000) throw Error('History needs a bounded receipt list and a valid half-open period');
58
+ const groups = new Map(), sourceRevisions = new Map();
59
+ const get = value => {
60
+ const key = groupKey(value);
61
+ if (!groups.has(key)) groups.set(key, { context: structuredClone(sharedContext(value.context)), catalogVersion: value.catalogVersion, levelVersion: value.levelVersion, expectedSamples: null, receipts: new Map(), receivedSources: new Map() });
62
+ return groups.get(key);
63
+ };
64
+ for (const expected of expectations) {
65
+ if (!record(expected) || validatePracticeContext(expected.context).length || typeof expected.catalogVersion !== 'string' || !expected.catalogVersion || typeof expected.levelVersion !== 'string' || !expected.levelVersion || !Number.isSafeInteger(expected.samples) || expected.samples < 0) throw Error('History expectations need exact compatible context, versions and a nonnegative sample count');
66
+ const group = get(expected);
67
+ if (group.expectedSamples !== null) throw Error('Duplicate history expectation');
68
+ group.expectedSamples = expected.samples;
69
+ }
70
+ for (const report of assessments) {
71
+ validateAssessment(report);
72
+ for (const p of report.practices.filter(p => p.observation)) {
73
+ const o = p.observation, source = canonical([o.repository.id, o.source.workflow, o.source.runId]), revision = canonical([o.commit, o.ref]);
74
+ if (sourceRevisions.has(source) && sourceRevisions.get(source) !== revision) throw Error('Contradictory source run revision');
75
+ sourceRevisions.set(source, revision);
76
+ }
77
+ if (Date.parse(report.assessedAt) < Date.parse(period.start) || Date.parse(report.assessedAt) >= Date.parse(period.end)) throw Error('Historical receipt is outside the requested period');
78
+ const group = get(report), sources = sourceEntries(report);
79
+ for (const p of report.practices.filter(p => p.observation)) {
80
+ const o = p.observation;
81
+ group.receivedSources.set(o.source.url, { url: o.source.url, attempt: o.source.attempt, result: o.source.result });
82
+ }
83
+ const identity = canonical([report.context.commit, sources.length ? [...new Set(sources.map(s => s.key))] : report.assessedAt]);
84
+ const previous = group.receipts.get(identity);
85
+ if (!previous || compareReceipts(report, previous) > 0) group.receipts.set(identity, structuredClone(report));
86
+ }
87
+ const summaries = [...groups.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([, group]) => {
88
+ const receipts = [...group.receipts.values()].sort((a, b) => Date.parse(a.assessedAt) - Date.parse(b.assessedAt) || practiceDigest(a).localeCompare(practiceDigest(b)));
89
+ if (group.expectedSamples !== null && group.expectedSamples < receipts.length) throw Error('Observed samples exceed the declared sampling coverage');
90
+ const distribution = Object.fromEntries(levels.map(l => [l, 0])), states = Object.fromEntries(practiceStates.map(s => [s, 0]));
91
+ const trends = {}, gaps = {}, definitions = {}, references = new Set();
92
+ let incompatibleObservations = 0;
93
+ let observedPractices = 0;
94
+ for (const report of receipts) {
95
+ distribution[report.level]++;
96
+ for (const p of report.practices) {
97
+ states[p.state]++;
98
+ if (p.observation) {
99
+ observedPractices++;
100
+ references.add(p.observation.source.url);
101
+ const definition = p.observation.catalogVersion + '/' + p.observation.definitionVersion;
102
+ definitions[p.practice + '@' + definition] = (definitions[p.practice + '@' + definition] ?? 0) + 1;
103
+ const compatible = p.observation.catalogVersion === group.catalogVersion && p.observation.definitionVersion === p.definitionVersion;
104
+ if (!compatible) incompatibleObservations++;
105
+ const measurements = compatible ? numericMeasurements(p.observation.measurements) : {};
106
+ for (const [path, value] of Object.entries(measurements)) {
107
+ const key = p.practice + '.' + path;
108
+ if (!trends[key]) trends[key] = { count: 0, min: value, max: value, first: value, last: value, firstAt: p.observation.source.observedAt, lastAt: p.observation.source.observedAt, firstSource: p.observation.source.url, lastSource: p.observation.source.url };
109
+ const trend = trends[key]; trend.count++; trend.min = Math.min(trend.min, value); trend.max = Math.max(trend.max, value);
110
+ if (Date.parse(p.observation.source.observedAt) < Date.parse(trend.firstAt)) Object.assign(trend, { first: value, firstAt: p.observation.source.observedAt, firstSource: p.observation.source.url });
111
+ if (Date.parse(p.observation.source.observedAt) >= Date.parse(trend.lastAt)) Object.assign(trend, { last: value, lastAt: p.observation.source.observedAt, lastSource: p.observation.source.url });
112
+ }
113
+ }
114
+ for (const reason of [...p.gaps, ...p.enforcementGaps]) { const key = p.practice + ': ' + reason; gaps[key] = (gaps[key] ?? 0) + 1; }
115
+ }
116
+ }
117
+ return { context: group.context, catalogVersion: group.catalogVersion, levelVersion: group.levelVersion,
118
+ coverage: { expectedSamples: group.expectedSamples, observedSamples: receipts.length, missingSamples: group.expectedSamples === null ? null : group.expectedSamples - receipts.length, unknownSamplingCoverage: group.expectedSamples === null,
119
+ expectedPracticeSlots: receipts.length * practiceCatalog.practices.length, observedPractices, missingPractices: states.missing, unknownPractices: states.partial + states.stale + states.unavailable },
120
+ observedDefinitions: definitions, incompatibleObservations, levelDistribution: distribution, practiceStates: states, gaps, measurementTrends: trends, sources: [...references].sort(), supersededSources: [...group.receivedSources.values()].filter(source => !references.has(source.url)).sort((a, b) => a.url.localeCompare(b.url)) };
121
+ });
122
+ return { schemaVersion: 1, kind: 'historical-practice-summary', currentCertification: false, period: { start: new Date(period.start).toISOString(), end: new Date(period.end).toISOString() }, groups: summaries,
123
+ retention: 'Source receipts remain subject to existing retention obligations; this summary authorizes no deletion' };
124
+ }
@@ -0,0 +1,56 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { practiceCatalog } from './practice-catalog.mjs';
3
+
4
+ export const record = value => value !== null && typeof value === 'object' && !Array.isArray(value);
5
+ export const canonical = value => JSON.stringify(Array.isArray(value) ? value.map(v => JSON.parse(canonical(v))) : record(value) ? Object.fromEntries(Object.keys(value).sort().map(k => [k, JSON.parse(canonical(value[k]))])) : value);
6
+ export const practiceDigest = value => 'sha256:' + createHash('sha256').update(canonical(value)).digest('hex');
7
+ const text = value => typeof value === 'string' && value.length > 0 && value.length <= 2048;
8
+ const positive = value => Number.isSafeInteger(value) && value > 0;
9
+ export const exactCommit = value => typeof value === 'string' && /^[a-f0-9]{40}$/.test(value);
10
+ export const sourceUrl = value => { try { return new URL(value).protocol === 'https:'; } catch { return false; } };
11
+ const date = value => typeof value === 'string' && /^\d{4}-\d\d-\d\dT/.test(value) && Number.isFinite(Date.parse(value));
12
+ const only = (value, keys) => record(value) && Object.keys(value).every(k => keys.includes(k));
13
+
14
+ export function validatePracticeContext(context) {
15
+ const errors = [];
16
+ if (!only(context, ['repository', 'ref', 'commit', 'scope', 'profile'])) return ['context must contain only repository, ref, commit, scope and profile'];
17
+ if (!only(context.repository, ['id', 'fullName']) || !positive(context.repository.id) || !/^[\w.-]+\/[\w.-]+$/.test(context.repository.fullName)) errors.push('repository needs a positive numeric id and owner/name');
18
+ if (!text(context.ref) || !exactCommit(context.commit)) errors.push('ref and exact 40-character commit are required');
19
+ if (!only(context.scope, ['id', 'modules']) || !text(context.scope.id) || !Array.isArray(context.scope.modules) || !context.scope.modules.length || context.scope.modules.some(m => !text(m)) || new Set(context.scope.modules).size !== context.scope.modules.length) errors.push('scope needs an id and unique production module inventory');
20
+ if (!Object.hasOwn(practiceCatalog.profiles, context.profile)) errors.push('unknown shared applicability profile');
21
+ return errors;
22
+ }
23
+
24
+ export function observationPayload(observation) {
25
+ return { practice: observation.practice, definitionVersion: observation.definitionVersion, catalogVersion: observation.catalogVersion,
26
+ repository: observation.repository, ref: observation.ref, commit: observation.commit, scope: observation.scope,
27
+ mode: observation.mode, applicability: observation.applicability, collection: observation.collection, measurements: observation.measurements };
28
+ }
29
+
30
+ export function validatePracticeObservation(observation) {
31
+ const errors = [];
32
+ if (!only(observation, ['schemaVersion', 'catalogVersion', 'definitionVersion', 'practice', 'repository', 'ref', 'commit', 'scope', 'mode', 'applicability', 'collection', 'measurements', 'source'])) return ['observation contains unsupported fields or is not an object'];
33
+ if (observation.schemaVersion !== 1) errors.push('unsupported observation schema version');
34
+ if (!text(observation.catalogVersion) || !text(observation.definitionVersion) || !practiceCatalog.practices.some(p => p.id === observation.practice)) errors.push('practice and explicit definition versions are required');
35
+ errors.push(...validatePracticeContext({ repository: observation.repository, ref: observation.ref, commit: observation.commit, scope: observation.scope, profile: observation.applicability?.profile }));
36
+ if (!['blocking', 'report-only'].includes(observation.mode)) errors.push('mode must be blocking or report-only');
37
+ const applicability = observation.applicability;
38
+ if (!only(applicability, ['status', 'profile', 'reason', 'source']) || !['applicable', 'not-applicable'].includes(applicability.status) || !text(applicability.reason) || !sourceUrl(applicability.source)) errors.push('applicability needs status, shared profile, reason and source');
39
+ const collection = observation.collection;
40
+ if (!only(collection, ['expected', 'collected', 'exclusions']) || !Number.isSafeInteger(collection.expected) || collection.expected < 1 || !Number.isSafeInteger(collection.collected) || collection.collected < 0 || collection.collected > collection.expected || !Array.isArray(collection.exclusions) || collection.exclusions.some(e => !only(e, ['scope', 'reason', 'source']) || !text(e.scope) || !text(e.reason) || !sourceUrl(e.source)) || new Set(collection.exclusions.map(e => e.scope)).size !== collection.exclusions.length) errors.push('collection needs bounded counts and unique justified exclusions');
41
+ if (!record(observation.measurements)) errors.push('measurements must be an object, including when empty');
42
+ const source = observation.source;
43
+ if (!only(source, ['workflow', 'runId', 'attempt', 'jobId', 'url', 'result', 'observedAt', 'producer', 'reportDigest']) || !text(source.workflow) || !positive(source.runId) || !positive(source.attempt) || !positive(source.jobId) || !sourceUrl(source.url) || !['success', 'failure', 'cancelled', 'unavailable'].includes(source.result) || !date(source.observedAt) || !only(source.producer, ['name', 'version']) || !text(source.producer.name) || !text(source.producer.version) || !/^sha256:[a-f0-9]{64}$/.test(source.reportDigest)) errors.push('source needs exact workflow/run/attempt/job, time, URL, result, producer version and report digest');
44
+ if (errors.length === 0 && source.reportDigest !== practiceDigest(observationPayload(observation))) errors.push('report digest does not bind the measured observation payload');
45
+ return errors;
46
+ }
47
+
48
+ export function requirePracticeObservation(observation) {
49
+ const errors = validatePracticeObservation(observation);
50
+ if (errors.length) throw new Error('Invalid practice observation: ' + errors.join('; '));
51
+ return observation;
52
+ }
53
+
54
+ export function sourceIdentity(observation, { attempt = true } = {}) {
55
+ return canonical([observation.repository.id, observation.practice, observation.source.workflow, observation.source.runId, ...(attempt ? [observation.source.attempt] : []), observation.scope]);
56
+ }
package/src/sdlc.mjs CHANGED
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env node
2
+ import { practiceCli } from './practice-cli.mjs';
2
3
  import { access, mkdir, readFile, writeFile } from 'node:fs/promises';
3
4
  import { constants } from 'node:fs';
4
5
  import { dirname, resolve } from 'node:path';
@@ -394,11 +395,13 @@ async function runGithubLabels(args) {
394
395
  }
395
396
 
396
397
  const command = process.argv[2] ?? 'verify';
397
- if (!['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)) {
398
- console.error('Usage: lighthouse-sdlc <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>');
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>');
399
400
  process.exit(2);
400
401
  }
401
- if (command === 'telemetry') {
402
+ if (command === 'practices') {
403
+ console.log(JSON.stringify(await practiceCli(process.argv.slice(3)), null, 2));
404
+ } else if (command === 'telemetry') {
402
405
  await telemetryCli(process.argv.slice(3));
403
406
  } else if (command === 'contract') {
404
407
  console.log(await readFile(contractPath, 'utf8'));