@juangcarmona/lighthouse-sdlc 0.30.1 → 0.30.3

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
@@ -4,6 +4,8 @@ For optional worker command presentation, see [compact output and complete diagn
4
4
 
5
5
  For original intent, source decisions and affected instruction evidence, see [change continuity](change-continuity.md). New implementation admissions require that assessment; unresolved guidance conflicts need their named owner before completion.
6
6
 
7
+ In an instruction review, `sources` lists guidance files in the authenticated candidate repository inventory. Required installed guides, workflow prompts and skills must still be inspected; cite their exact reference and pinned package version or revision in `reason` or a relevant candidate source's `evidence`. A tracked `LIGHTHOUSE.md` can supply the candidate pointer to an ignored installed guide. The [instruction-review example](change-continuity.md) shows that representation; an ignored `node_modules` file or `/harness` path remains outside the candidate source list.
8
+
7
9
  Final reviews use [verified process guard dispositions](process-guards.md) to separate demonstrated guards, unqualified proposals and reasoned no-guard outcomes, retaining their evidence and maintenance owner.
8
10
 
9
11
  Use GitHub labels to request work. The router authenticates the owner, dispatches one worker and publishes its result. Installed policy can continue delivery automatically; questions, `future`, human reservations and required approvals stop it.
@@ -49,8 +51,12 @@ These actions require installed workers, enabled automation and the repository o
49
51
  | Required CI passes for a complete implementation candidate | Current PR head and adopted checks | Mark the PR ready and project `pr-ready`; wait for merge authorization. | [PR state](src/pr-state-actions.mjs) |
50
52
  | Approve the implementation PR | Completion installed; owner approval for current head and passing required checks | `integrate` assesses and performs the authorized merge. After successful post-merge CI, `review` records the retrospective and closes the issue if passed. | [Completion](completion.md) |
51
53
 
54
+ When `future` pauses a manual implementation request, the router publishes a blocked handoff on the issue without dispatching a worker or publishing a candidate. Reobserving that request does not duplicate the handoff. Remove `future` when ready: an existing `implement` label remains the explicit continuation request; without it, request implementation again. Other authorization and publication failures still fail the execution.
55
+
52
56
  For direct implementation, the host scaffolds OpenSpec metadata before the agent starts. The agent preserves those fields and declares `skip_specs: true` only for a plan without specification changes. Before independent checks, the host materializes the final metadata while preserving existing provider bytes and completed implementation tasks.
53
57
 
58
+ Before implementation invokes a model, the host checks explicit required verification files against the admitted source. An absent file requires an exact correction reason and authorized write scope for its creation. Repositories declaring Lighthouse or ProductShape adoption also need explicit, provider-valid PDaC v1alpha2 configuration and a valid accepted model. Prerequisite failures retain the source-bound preflight diagnostic, start no agent and cannot receive an automatic technical retry. Repair the adopter policy or product prerequisite, then request implementation again. Historical SDLC-only consumers without an adoption declaration remain unconfigured for this product check. The full candidate verification and independent checks still run after implementation; preflight grants no product approval or migration authority.
59
+
54
60
  When the admitted source already contains one completed, issue-bound archived implementation plan, the host validates its provider metadata, planning artifacts and task completion without recreating an active change. Incomplete evidence, multiple matching archives, active/archive conflicts or candidate rewrites stop requalification with a repair reason. The archive is planning evidence, not a completion receipt: independent checks, required review, forge checks and the original correction/deadline limits still apply. Adopters need the released SDLC correction and an updated workflow source/package-mode installation before retrying a real candidate; a source fix alone does not establish installed adoption.
55
61
 
56
62
  The generated independent plan check runs from the read-only harness against the materialized candidate. It strictly validates the selected archive under its original active identity only in a disposable provider workspace, leaving the candidate unchanged. Without an applicable archive it retains strict active-plan validation; missing plans fail rather than skipping the check.
@@ -213,7 +219,7 @@ Lighthouse-authored material in this package is licensed under [Apache-2.0](LICE
213
219
 
214
220
  ## Runner telemetry
215
221
 
216
- 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.
222
+ The [telemetry contract](telemetry.md) covers collection from first startup, native OpenCode activity, opt-in Claude Code usage metrics, 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.
217
223
 
218
224
  ## Engineering practice evidence
219
225
 
@@ -4,7 +4,27 @@ Before proposing or continuing a change, use `context.continuity` to locate the
4
4
 
5
5
  The host rechecks the original title, body and owner-answer identities, contents and revisions before continuation/publication. A changed task digest requires fresh refinement under the named owner. Preserve the old record and the new decision; a worker cannot reinterpret the old grant to cover changed intent. Conflicting product, architecture or instruction authority requires a blocked result naming both sources and the responsible owner.
6
6
 
7
- At implementation completion, when `request.instructionReview` is `1`, return `output.instructionReview` using `contract.instructionReview`. Inspect the guidance reached by the changed behavior: applicable `AGENTS.md`, its pointers, selected skills, workflow prompts and affected package or architecture guidance. Record each inspected repository path, owning project/tool, disposition and concrete supporting evidence. Use `reviewed` with source findings, or `not-applicable` with a bounded reason and no sources. A source can be `current`, `corrected` or an intentional `host-specific` projection. Distinct host commands or paths are legitimate when they preserve the canonical policy; explain the owning contract instead of normalizing every host.
7
+ At implementation completion, when `request.instructionReview` is `1`, return `output.instructionReview` using `contract.instructionReview`. Inspect the guidance reached by the changed behavior: applicable `AGENTS.md`, its pointers, selected skills, workflow prompts and affected package or architecture guidance. For guidance files in the authenticated candidate repository inventory, record the repository path, owning project/tool, disposition and concrete supporting evidence in `sources`. Use `reviewed` with source findings, or `not-applicable` with a bounded reason and no sources. A source can be `current`, `corrected` or an intentional `host-specific` projection. Distinct host commands or paths are legitimate when they preserve the canonical policy; explain the owning contract instead of normalizing every host.
8
+
9
+ Required installed package guides, workflow prompts and skills must still be inspected when they are outside that inventory. Record their exact inspected reference and pinned package version or revision in `reason` or a relevant candidate source's `evidence`. For example, a tracked `LIGHTHOUSE.md` may point to `node_modules/@juangcarmona/lighthouse-sdlc/README.md`: put `LIGHTHOUSE.md` in `sources` and the inspected package guide and version in its supporting evidence. Ignored dependency files and `/harness` paths do not become candidate sources because they exist or were read. Preserve their owning tool and inspection requirements; do not copy them into the repository to satisfy this report.
10
+
11
+ This example assumes a fixture pinned to SDLC 0.30.1. Use the actual candidate pointer and the exact installed version or revision you inspected in your own report:
12
+
13
+ ```json
14
+ {
15
+ "schemaVersion": 1,
16
+ "status": "reviewed",
17
+ "reason": "Reviewed delivery guidance reached through the tracked project pointer.",
18
+ "sources": [
19
+ {
20
+ "path": "LIGHTHOUSE.md",
21
+ "owner": "Lighthouse",
22
+ "status": "current",
23
+ "evidence": "Read LIGHTHOUSE.md and its required node_modules/@juangcarmona/lighthouse-sdlc/README.md guide from the fixture's pinned @juangcarmona/lighthouse-sdlc@0.30.1 installation; compared the applicable delivery instructions with the candidate."
24
+ }
25
+ ]
26
+ }
27
+ ```
8
28
 
9
29
  Report `stale`, `conflict` or `missing` sources as `blocked` with the decision owner and next action. A passed completion cannot retain those findings or refer to a source absent from the candidate. These checks validate the report and its paths; semantic consistency still requires the worker's inspection and independent review. Syntax validation alone does not prove that prose agrees with implementation.
10
30
 
package/epic-delivery.md CHANGED
@@ -26,6 +26,8 @@ The owner-driven workflow provides `reconcile`, `refine-child`, `register-pr`, `
26
26
 
27
27
  Readiness uses the [adopter-owned GitHub App](github-actions.md#eligible-ci-for-bot-delivery) to create an immutable verification branch pointing to the exact head/base integration commit, then observes its native push CI and waits for enforced checks. The candidate must preserve the trusted CI workflow. The journal records intent before branch creation; an unconfirmed request is reconciled by observation, never blindly resent. `workflow_dispatch` checks cannot satisfy PR rules. Acknowledgement alone cannot make a PR ready. Each child merge still requires the owner's current-head review, and final aggregate acceptance preserves the parent's separate decision.
28
28
 
29
+ Publication can repeat a GitHub `422` tree-creation refusal that names a newly uploaded blob only after reading back that exact object's bytes and rechecking owner authority and the epic base. It preserves the original tree request and allows at most three attempts. Unknown responses, other refusals, unavailable or conflicting blobs and changed authority stop publication without a ref write.
30
+
29
31
  For native epic children, implementation policy `reviewRequired` is enforced at epic acceptance. A verified implementation can pass its own stage and register its PR for review; that result grants no merge authority. Missing implementation evidence, failed independent checks and model-reported blockers still prevent a passing result. Ordinary implementation routes retain their policy review stop.
30
32
 
31
33
  `recover-publication` is an explicit owner action for a failed correction that wrote its exact independently checked tree but lost its final publication receipt. Supply the child, original run, PR, head and current epic base. The host verifies retained dispatch, content, cleanup, intent and dependencies before recording the old reservation as failed; it never repeats execution or writes a Git ref, PR or merge. Review feedback can then request fresh verification on the same PR. A reviewed workflow branch may run this recovery without changing the epic's frozen default branch.
@@ -40,6 +42,8 @@ The credentialed host must supply `withLease(parentKey, work)` with a serialized
40
42
 
41
43
  The adapter records intent before creation, records returned native IDs before linking, attaches children with the native sub-issues endpoint and records native blocked-by relationships. It never edits the parent's body or lifecycle. Retries verify exact metadata, receipt identity and native relationships. Duplicate, copied or changed correlations block. A lost create response stops at uncertainty rather than reposting; the host must establish a verified resource receipt before resuming. Confirmed link writes can reconcile on retry. Cancelled receipts cannot be recreated. Partial failures retain already-created children and stop downstream creation.
42
44
 
45
+ Candidate discovery lists issues updated since the parent's creation, with a one-second overlap for timestamp precision. This includes new orphan creations and older issues updated to copy a marker, across authors and plan revisions, without scanning unchanged history from before the parent existed. A missing parent timestamp or more than five full pages of relevant updates stops reconciliation; a partial inventory never establishes that a child is absent.
46
+
43
47
  The native host supplies those callbacks through an owner-triggered workflow and retained Actions artifacts. Do not invoke the adapter without a durable journal and lease, and do not describe fixture tests as full delivery. See the tracked [implementation tasks](../../../openspec/changes/issue-146-proposal/tasks.md).
44
48
 
45
49
  ## An approved product prerequisite before implementation
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@juangcarmona/lighthouse-sdlc",
3
- "version": "0.30.1",
3
+ "version": "0.30.3",
4
4
  "type": "module",
5
5
  "description": "Provider-neutral SDLC skills, commands and route contracts for Lighthouse adopters",
6
6
  "repository": {
@@ -123,6 +123,6 @@
123
123
  },
124
124
  "license": "Apache-2.0",
125
125
  "dependencies": {
126
- "@juangcarmona/lighthouse-ui": "0.2.1"
126
+ "@juangcarmona/lighthouse-ui": "0.2.2"
127
127
  }
128
128
  }
@@ -424,6 +424,24 @@
424
424
  },
425
425
  "queueDurationMs": {
426
426
  "$ref": "#/$defs/metadataValue"
427
+ },
428
+ "skill": {
429
+ "$ref": "#/$defs/metadataValue"
430
+ },
431
+ "agent": {
432
+ "$ref": "#/$defs/metadataValue"
433
+ },
434
+ "querySource": {
435
+ "$ref": "#/$defs/metadataValue"
436
+ },
437
+ "tokenType": {
438
+ "$ref": "#/$defs/metadataValue"
439
+ },
440
+ "costUsd": {
441
+ "$ref": "#/$defs/metadataValue"
442
+ },
443
+ "costSource": {
444
+ "$ref": "#/$defs/metadataValue"
427
445
  }
428
446
  }
429
447
  }
@@ -16,8 +16,8 @@ export function assertRetainedIntent(request, issue, answers) {
16
16
  }
17
17
 
18
18
  export const instructionReviewContract = {
19
- schemaVersion: 1, status: 'reviewed | not-applicable | blocked', reason: 'Scope and evidence for this assessment',
20
- sources: [{ path: 'repository-relative guidance path', owner: 'project or owning provider', status: 'current | corrected | host-specific | stale | conflict | missing', evidence: 'Exact source, implementation or owning-tool check supporting this finding' }],
19
+ schemaVersion: 1, status: 'reviewed | not-applicable | blocked', reason: 'Scope and findings. Inspect required installed guides, workflow prompts and skills; record inspected references outside the candidate with their pinned package version or revision here or in source evidence.',
20
+ sources: [{ path: 'Guidance file in the authenticated candidate inventory, such as AGENTS.md or LIGHTHOUSE.md; ignored node_modules dependencies and /harness paths are outside this inventory', owner: 'project or owning provider', status: 'current | corrected | host-specific | stale | conflict | missing', evidence: 'Concrete source, implementation or owning-tool evidence; include exact inspected installed-guide, prompt or skill references and their pinned package version or revision when outside the candidate' }],
21
21
  };
22
22
 
23
23
  export function validateInstructionReview(value, files) {
@@ -292,9 +292,14 @@ export async function readyEpicPullRequest({ api, repository, owner, parent, chi
292
292
  }
293
293
 
294
294
  export async function findEpicCandidates(api, correlation) {
295
+ const parent = await api(`issues/${correlation.parent}`);
296
+ const created = Date.parse(parent?.created_at ?? '');
297
+ if (parent?.number !== correlation.parent || parent.pull_request || !Number.isFinite(created)) throw Error('Epic parent creation time unavailable');
298
+ // Children cannot predate their parent; updated copies must remain visible across authors and plans.
299
+ const since = encodeURIComponent(new Date(Math.floor(created / 1000) * 1000 - 1000).toISOString().replace('.000Z', 'Z'));
295
300
  const candidates = [];
296
301
  for (let page = 1; page <= 5; page++) {
297
- const issues = await api(`issues?state=all&per_page=100&page=${page}`);
302
+ const issues = await api(`issues?state=all&since=${since}&per_page=100&page=${page}`);
298
303
  if (!Array.isArray(issues)) throw Error('Epic issue inventory unavailable');
299
304
  for (const issue of issues) {
300
305
  const marker = readEpicMarker(issue.body);
@@ -6,7 +6,7 @@ The OpenCode adapter cleans each admitted attempt, not each issue. Its host engi
6
6
 
7
7
  | Resource | Owner and disposal boundary | Retained or excluded state |
8
8
  | --- | --- | --- |
9
- | `RUNNER_TEMP/lighthouse-engine-<owner digest>` | Adapter allocation, recorded before worker access with parent and root device/inode identity; removed only after runtime absence and successful local retention | A replaced root, unknown owner, incomplete allocation or failed collection is preserved and blocks admission |
9
+ | `<engine lock>.resources/workspaces/lighthouse-engine-<owner digest>` | Adapter allocation, recorded before worker access with parent and root device/inode identity; removed only after runtime absence and successful local retention | A replaced root, unknown owner, incomplete allocation or failed collection is preserved and blocks admission |
10
10
  | Snapshot `source`, validation `candidate`, workspace `node_modules` and `.cache` | Children of that exact disposable workspace; disposed with the workspace | The original checkout, manual checkouts, modified source outside the snapshot and other runs are never inferred owned |
11
11
  | Container `/tmp`, npm command scratch and private cache tmpfs | Existing command/container lifecycle; unchanged by this correction | Inherited host caches, provider paths, NuGet state and caller-selected paths outside the workspace are not swept |
12
12
  | Containers, anonymous volumes and private networks | Existing durable Docker ownership and inventory checks; container removal includes anonymous volumes | Named authentication/data volumes and foreign resources remain preserved; no host-wide prune |
@@ -20,7 +20,7 @@ The OpenCode adapter cleans each admitted attempt, not each issue. Its host engi
20
20
 
21
21
  After taking the host slot, a new adapter first runs the existing stopped-owner Docker recovery. It then recovers journaled workspaces only when the original process is confirmed stopped and that owner's runtime receipt is clean. Active or unknown process identities stop admission. Journals from older releases without a workspace record remain Docker-only; directory names do not retroactively establish ownership.
22
22
 
23
- Before disposal, the adapter collects candidate edits through its existing bounded source and scope validation and collects worker evidence under the existing 200-file/64-MiB limit. It seals and synchronizes the recovery bundle before recording retention, then removes the workspace and checks absence. A failed or unsafe collection leaves the workspace intact. An interrupted removal can retry from the sealed bundle without requiring the partially removed source tree to be readable. A changed retained bundle blocks removal.
23
+ Before disposal, the adapter collects candidate edits through its existing bounded source and scope validation and collects worker evidence under the existing 200-file/64-MiB limit. It seals and synchronizes the recovery bundle before recording retention, then removes the workspace and checks absence. A failed or unsafe collection leaves the workspace intact beside the durable ownership journals, outside the runner temporary directory. Runner job cleanup cannot remove the recovery checkpoint or uncollected candidate. Existing journaled paths remain subject to their original device/inode and ownership checks. An interrupted removal can retry from the sealed bundle without requiring the partially removed source tree to be readable. A changed retained bundle blocks removal.
24
24
 
25
25
  Local retention has no automatic age-based eviction. Admission stops at 32 bundles, 512 MiB of content or 8,192 filesystem entries, reserving the minimum three entries for another bundle and its two receipt files. An operator must first reconcile publication and candidate recovery, archive needed local diagnostics, and explicitly release only the matching stopped attempt's bundle and delivery outputs. A completed journal can be archived with that bundle only after confirming its workspace and runtime resources absent. Do not release a bundle still referenced by an incomplete workspace cleanup. Do not infer local deletion authority from a successful remote artifact upload. Unknown or unsafe state requires reconciliation, not additional allocation.
26
26
 
@@ -53,7 +53,10 @@ function openOwner(path, record, run) {
53
53
  const prefix = `lighthouse-${record.key.slice(0, 24)}`;
54
54
  return {
55
55
  prefix,
56
- allocateWorkspace(parent) { return allocateWorkspace(record, parent, () => persist(path, record), dirname(path)); },
56
+ allocateWorkspace(parent = join(dirname(path), 'workspaces')) {
57
+ mkdirSync(parent, { recursive: true, mode: 0o700 });
58
+ return allocateWorkspace(record, parent, () => persist(path, record), dirname(path));
59
+ },
57
60
  checkpointWorkspace(baseline, tracked, policy) { return checkpointWorkspace(record, baseline, tracked, policy, () => persist(path, record)); },
58
61
  cleanupWorkspace(options) { return disposeWorkspace(record, () => persist(path, record), dirname(path), options); },
59
62
  prepare(args) {
@@ -2,6 +2,15 @@ import { setTimeout as pause } from 'node:timers/promises';
2
2
 
3
3
  export const repositoryApiUrl = (repository, path = '') => `https://api.github.com/repos/${repository}${path ? `/${path}` : ''}`;
4
4
 
5
+ function rateLimitMetadata(response) {
6
+ const result = {};
7
+ for (const [field, header] of [['limit', 'x-ratelimit-limit'], ['remaining', 'x-ratelimit-remaining'], ['reset', 'x-ratelimit-reset'], ['retryAfterSeconds', 'retry-after']]) {
8
+ const value = response.headers?.get(header);
9
+ if (typeof value === 'string' && /^\d{1,16}$/.test(value) && Number.isSafeInteger(Number(value))) result[field] = Number(value);
10
+ }
11
+ return result;
12
+ }
13
+
5
14
  async function denialMessage(response, token) {
6
15
  let reader;
7
16
  try {
@@ -58,8 +67,15 @@ export function createIssueApi(repo, env, fetchRequest = fetch, { now = Date.now
58
67
  if (optional && r.status === 404) return null;
59
68
  if (!r.ok) {
60
69
  const error = Object.assign(Error(`GitHub ${method} ${path}: ${r.status}`), { status: r.status });
61
- const message = await denialMessage(r, env.GH_TOKEN);
62
- if (message) error.message += `: ${message}`;
70
+ const rateLimit = r.status === 403 ? rateLimitMetadata(r) : {};
71
+ if (Object.keys(rateLimit).length) {
72
+ error.rateLimit = rateLimit;
73
+ error.message += ` [rate-limit ${Object.entries(rateLimit).map(([key, value]) => `${key}=${value}`).join(' ')}]`;
74
+ try { void r.body?.cancel().catch(() => {}); } catch {}
75
+ } else {
76
+ const message = await denialMessage(r, env.GH_TOKEN);
77
+ if (message) error.message += `: ${message}`;
78
+ }
63
79
  throw error;
64
80
  }
65
81
  if (/^actions\/jobs\/[1-9][0-9]*\/logs$/.test(path)) {
@@ -267,7 +267,27 @@ async function writeImplementationPullRequest(api, { snapshot, changes, body, ru
267
267
  }
268
268
  if (synchronization) entries.push(...synchronization.files.map(({ path, sha, mode }) => ({ path, sha, mode, type: 'blob' })));
269
269
  if (verificationRefresh && (commit.sha !== snapshot.sourceRevision || !/^[a-f0-9]{40}$/.test(commit.tree?.sha ?? ''))) throw Error('Checked verification tree changed');
270
- const tree = verificationRefresh ? commit.tree : await api('git/trees', 'POST', { base_tree: commit.tree.sha, tree: entries });
270
+ let tree = commit.tree;
271
+ if (!verificationRefresh) {
272
+ const treeBody = { base_tree: commit.tree.sha, tree: entries };
273
+ for (let attempt = 0; attempt < 3; attempt++) {
274
+ try { tree = await api('git/trees', 'POST', treeBody); break; }
275
+ catch (error) {
276
+ // Repeat only a refused write whose newly created blob is now readable.
277
+ const rejected = /^GitHub POST git\/trees: 422: tree\.sha ([a-f0-9]{40}) is not a valid blob$/.exec(error.message ?? '');
278
+ const file = rejected && changes[entries.findIndex(entry => entry.sha === rejected[1])];
279
+ if (attempt === 2 || error.status !== 422 || !file || file.content === null) throw error;
280
+ const bytes = Buffer.from(file.content, 'base64');
281
+ const expected = createHash('sha1').update(`blob ${bytes.length}\0`).update(bytes).digest('hex');
282
+ if (rejected[1] !== expected) throw error;
283
+ const observed = await api(`git/blobs/${expected}`, 'GET', undefined, true);
284
+ if (observed?.sha !== expected || observed.encoding !== 'base64' || observed.size !== bytes.length || typeof observed.content !== 'string' || !Buffer.from(observed.content, 'base64').equals(bytes)) throw error;
285
+ await setTimeout(250 * 2 ** attempt);
286
+ await beforeWrite();
287
+ await checkEpicBase();
288
+ }
289
+ }
290
+ }
271
291
  if (synchronization && tree.sha !== checkedTree) throw Error('Synchronized publication differs from the independently checked tree');
272
292
  const message = verificationRefresh ? `chore: refresh verification for issue #${snapshot.issue}\n\nLighthouse-CI-Base: ${snapshot.baseRevision}` : `feat: implement issue #${snapshot.issue}`;
273
293
  const commitBody = { message, tree: tree.sha, parents: synchronization ? [snapshot.sourceRevision, snapshot.baseRevision] : [snapshot.sourceRevision] };
@@ -448,7 +448,12 @@ async function main(command) {
448
448
  if (issue.labels.some(x => ['future', 'needs-info', 'waiting-review'].includes(x.name))) { await output('send', 'false'); await summary('⏸️ Implementation paused by the current issue decision. No worker dispatched.'); return; }
449
449
  checkHandoff(prior, result, issue, answers, route.productResume?.head ?? revision, route.predecessor.runId);
450
450
  }
451
- if (stage === 'implement' && issue.labels.some(x => x.name === 'future')) throw Error('Implementation paused by future label');
451
+ if (stage === 'implement' && issue.labels.some(x => x.name === 'future')) {
452
+ await publishRoutingHandoff(api, issueNumber, `${repo}:future:${env.GITHUB_RUN_ID}`, renderHandoff({ status: 'blocked', stage, happened: 'Implementation paused by future label. This attempt dispatched no worker and published no candidate.', action: 'Owner: remove the future label when ready, then request implement again unless an implement label is already pending.', next: 'Removing future resumes only a pending implement label; otherwise a new explicit request is required. This notice does not authorize merge.', details: `[Routing execution](https://github.com/${repo}/actions/runs/${env.GITHUB_RUN_ID})` }));
453
+ await output('send', 'false');
454
+ await summary('Implementation paused by future label. No worker dispatched. Follow the issue handoff to resume.');
455
+ return;
456
+ }
452
457
  const eventRunId = epicTriage || epicRefinement ? String(event.inputs.epic_run) : after ? String(after.completionRecovery?.maintenance ?? after.workflow_run.id) : undefined;
453
458
  const feedback = implementationReview ?? proposalReview;
454
459
  const worker = route.worker ?? feedbackWorker(feedback);
@@ -23,7 +23,7 @@ import { commandProgress } from './command-progress.mjs';
23
23
  import { codegraphSelection, startCodegraph, stopCodegraph } from './codegraph-runtime.mjs';
24
24
  import { createExecutionOwner, recoverExecutionOwners, recoverExecutionWorkspaces, ownedDockerArgs, runOwnedDocker } from './execution-cleanup.mjs';
25
25
  import { harnessIdentity } from './harness-identity.mjs';
26
- import { verificationIntegrity } from './verification-integrity.mjs';
26
+ import { verificationIntegrity, verificationPreflight, sourceDigest } from './verification-integrity.mjs';
27
27
  import { implementationPlanMetadata, prepareImplementationPlanMetadata } from './implementation-plan.mjs';
28
28
  import { acquireEngineSlot, engineSlotWaitSeconds } from './engine-slot.mjs';
29
29
  export { acquireEngineSlot } from './engine-slot.mjs';
@@ -93,10 +93,8 @@ export async function installProductEvidence(input, source, expectedBaseline) {
93
93
  }
94
94
  }
95
95
 
96
- export async function preparePlanningProductEvidence(source, runDir, { core, install = promisify(execFile), signal } = {}) {
96
+ async function prepareProductProvider(runDir, { core, install = promisify(execFile), signal } = {}) {
97
97
  signal?.throwIfAborted();
98
- try { await lstat(join(source, '.product/config.yaml')); }
99
- catch (error) { if (error.code === 'ENOENT') return null; throw error; }
100
98
  if (!core) {
101
99
  const prefix = join(runDir, 'product-provider'), home = join(prefix, 'home');
102
100
  await mkdir(home, { recursive: true });
@@ -109,13 +107,41 @@ export async function preparePlanningProductEvidence(source, runDir, { core, ins
109
107
  });
110
108
  } catch (error) {
111
109
  if (error.name === 'AbortError') throw error;
112
- throw Error('ProductShape planning provider setup failed: ' + redactLog(String(error.stderr || error.message)).slice(0, 3000));
110
+ throw Error('ProductShape provider setup failed: ' + redactLog(String(error.stderr || error.message)).slice(0, 3000));
113
111
  }
114
112
  core = await loadProductCore({ entry: createRequire(join(prefix, 'package.json')).resolve('@prodshape/core') });
115
113
  await mkdir(join(runDir, 'evidence/host'), { recursive: true });
116
114
  await copyFile(join(prefix, 'package-lock.json'), join(runDir, 'evidence/host/product-provider-lock.json'));
117
115
  }
118
116
  signal?.throwIfAborted();
117
+ return core;
118
+ }
119
+
120
+ export async function prepareImplementationPrerequisites(source, baseline, runDir, request, options = {}) {
121
+ options.signal?.throwIfAborted();
122
+ const receipt = { sourceRevision: request.sourceRevision, sourceDigest: sourceDigest(baseline), verification: verificationPreflight(baseline, request.implementation.policy, request.issue), product: { status: 'unconfigured' } };
123
+ // Historical SDLC-only consumers have no declared product adoption.
124
+ if (!baseline.has('lighthouse.json') && ![...baseline.keys()].some(path => path.startsWith('.product/'))) return receipt;
125
+ if (!baseline.has('.product/config.yaml')) throw Error('Explicit .product/config.yaml is required before model execution. Initialize a new model through ProductShape, or restore the existing declaration; then validate PDaC v1alpha2 and request implementation again.');
126
+ const core = await prepareProductProvider(runDir, options);
127
+ const repository = await core.openRepository(source);
128
+ options.signal?.throwIfAborted();
129
+ if (repository.configDiagnostics.length || repository.config.version !== 'v1alpha2') {
130
+ throw Error(`ProductShape configuration does not satisfy required PDaC v1alpha2 before model execution (observed ${repository.config.version}). Review the installed Lighthouse upgrades/pdac-v1alpha2.md migration guide, migrate through ProductShape and validate before requesting implementation again.`);
131
+ }
132
+ const baselineResult = await core.validateBaseline(repository);
133
+ options.signal?.throwIfAborted();
134
+ const blocking = baselineResult.diagnostics.filter(item => item.severity === 'error' || repository.config.validation['warnings-as-errors']);
135
+ if (blocking.length) throw Error(`ProductShape baseline has ${blocking.length} blocking diagnostic(s) before model execution. Run prodshape --serialization-version v1alpha2 validate and repair the accepted model through its owning provider before requesting implementation again.`);
136
+ receipt.product = { status: 'passed', provider: '@prodshape/core', version: core.version, serializationVersion: repository.config.version };
137
+ return receipt;
138
+ }
139
+
140
+ export async function preparePlanningProductEvidence(source, runDir, { core, install, signal } = {}) {
141
+ signal?.throwIfAborted();
142
+ try { await lstat(join(source, '.product/config.yaml')); }
143
+ catch (error) { if (error.code === 'ENOENT') return null; throw error; }
144
+ core = await prepareProductProvider(runDir, { core, install, signal });
119
145
  const baselineDigest = await productModelDigest(source), reports = join(runDir, 'evidence/host/product-context');
120
146
  const path = join(runDir, 'context.json'), context = JSON.parse(await readFile(path, 'utf8'));
121
147
  const scopeText = context.issue ? productEvidenceScopeText({ issue: context.issue, continuation: context.continuation }) : undefined;
@@ -200,15 +226,14 @@ async function main() {
200
226
  const ensureOwner = () => config.resourceOwner ??= createExecutionOwner(ownershipDirectory, { repository: request.repository ?? env.GITHUB_REPOSITORY, runId: request.runId, workflowRunId: String(env.GITHUB_RUN_ID), attempt: Number(env.GITHUB_RUN_ATTEMPT) });
201
227
  await recoverExecutionWorkspaces(ownershipDirectory, { restoreOwnership: root => { ensureOwner(); restoreWorkspaceOwnership(root, config); } });
202
228
  ensureOwner();
203
- dir = await config.resourceOwner.allocateWorkspace(env.RUNNER_TEMP);
229
+ dir = await config.resourceOwner.allocateWorkspace();
204
230
  source = join(dir, 'source'); output = join(dir, 'output');
205
231
  await mkdir(source); await mkdir(output); await chmod(output, 0o777);
206
232
  name = `${config.resourceOwner.prefix}-engine`;
207
233
  await recordPhase('running');
208
234
  runtime = await startEnvironment({ selected, image: config.image, commands: implementing ? [['git'], ['sh'], ...(request.implementation.policy.checks ?? [])] : [], name: `${name}-agent`, uid: config.uid, run: args => runOwnedDocker(config, args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], timeout: 30000 }) });
209
- await recordPhase('passed');
210
235
  if (cancelled || !checkController()) throw Error('Execution cancelled before agent startup');
211
- console.log('Engine slot acquired; starting isolated OpenCode');
236
+ console.log('Engine slot acquired; preparing isolated source');
212
237
  await snapshotSource(env.GITHUB_WORKSPACE, source);
213
238
  if (!implementing) await config.resourceOwner.checkpointWorkspace(null, null, undefined);
214
239
  if (request.worker === 'product-change') {
@@ -227,6 +252,8 @@ async function main() {
227
252
  await rm(source, { recursive: true, force: true }); await mkdir(source);
228
253
  await materializeCandidate(baseline, [], source);
229
254
  }
255
+ try { runtimeReceipt.prerequisites = await prepareImplementationPrerequisites(source, baseline, runDir, request, { signal: preparation.signal }); }
256
+ catch (error) { if (!cancelled && error.name !== 'AbortError') error.code = 'adopter-prerequisite'; throw error; }
230
257
  if (request.seedDigest) {
231
258
  const seed = validateChanges(JSON.parse(await readFile(join(runDir, 'seed.json'), 'utf8')), request.implementation.policy);
232
259
  if (changesDigest(seed) !== request.seedDigest) throw Error('Seed artifact identity mismatch');
@@ -247,6 +274,7 @@ async function main() {
247
274
  }
248
275
  await prepareImplementationWorkspace(source, config, request.issue, repository);
249
276
  }
277
+ await recordPhase('passed');
250
278
  await config.resourceOwner.checkpointWorkspace(baseline, trackedSource, request.implementation?.policy);
251
279
  const context = join(dir, 'context.json');
252
280
  await copyFile(join(runDir, 'context.json'), context); await chmod(context, 0o644);
@@ -459,7 +487,7 @@ async function main() {
459
487
  progress?.poll();
460
488
  runtimeReceipt.lastCommand = progress?.last ?? null;
461
489
  error.phase = phase;
462
- runtimeReceipt.failure = { phase, message: redactLog(error.message).slice(0, 3000) };
490
+ runtimeReceipt.failure = { phase, message: redactLog(error.message).slice(0, 3000), ...(error.code === 'adopter-prerequisite' ? { code: error.code } : {}) };
463
491
  console.error(progressText('Failure', runtimeReceipt.failure.message));
464
492
  await recordPhase('failed');
465
493
  if (implementing && baseline) {
@@ -0,0 +1,157 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { createServer } from 'node:http';
3
+ import { spawn } from 'node:child_process';
4
+ import { createTelemetry, readTelemetry, telemetryContext, telemetryDirectory } from './telemetry.mjs';
5
+
6
+ const hash = value => createHash('sha256').update(value).digest('hex');
7
+ const valueOf = item => item?.stringValue ?? item?.intValue ?? item?.doubleValue ?? item?.boolValue ?? null;
8
+ const numberOf = point => {
9
+ const value = point?.asDouble ?? point?.asInt;
10
+ if (typeof value === 'number' && Number.isFinite(value) && value >= 0) return value;
11
+ if (typeof value === 'string' && /^\d+(?:\.\d+)?$/.test(value) && Number.isFinite(Number(value))) return Number(value);
12
+ return null;
13
+ };
14
+ const timestamp = input => {
15
+ try { const value = BigInt(input); const milliseconds = Number(value / 1000000n); return Number.isSafeInteger(milliseconds) && milliseconds >= 0 && milliseconds < 8640000000000000 ? milliseconds : null; }
16
+ catch { return null; }
17
+ };
18
+ const fields = values => Object.fromEntries(Object.entries(values).filter(([, value]) => value !== null && value !== undefined));
19
+
20
+ function attributesOf(items = []) {
21
+ return Object.fromEntries(items.filter(item => typeof item?.key === 'string').map(item => [item.key, valueOf(item.value)]));
22
+ }
23
+
24
+ function metricIdentity(name, point, attributes) {
25
+ return hash(JSON.stringify([name, point.startTimeUnixNano ?? null, point.timeUnixNano ?? null, attributes, point.asDouble ?? point.asInt ?? null]));
26
+ }
27
+
28
+ function mapMetric(metric, point, resource, telemetry, seen) {
29
+ const attribute = attributesOf(point.attributes);
30
+ const model = typeof attribute.model === 'string' ? attribute.model : null;
31
+ const skill = typeof attribute['skill.name'] === 'string' && attribute['skill.name'] !== 'custom_skill' && attribute['skill.name'] !== 'custom' ? attribute['skill.name'] : null;
32
+ const agent = typeof attribute['agent.name'] === 'string' && attribute['agent.name'] !== 'custom' ? attribute['agent.name'] : null;
33
+ const querySource = typeof attribute.query_source === 'string' ? attribute.query_source : null;
34
+ const repoName = typeof resource['vcs.repository.name'] === 'string' ? resource['vcs.repository.name'] : null;
35
+ const ownerName = typeof resource['vcs.owner.name'] === 'string' ? resource['vcs.owner.name'] : null;
36
+ const repository = repoName && ownerName ? `${ownerName}/${repoName}` : null;
37
+ const identity = typeof attribute['session.id'] === 'string' ? `claude-${hash(attribute['session.id']).slice(0, 24)}` : null;
38
+ const time = timestamp(point.timeUnixNano);
39
+ const sourceId = metricIdentity(metric.name, point, { model, skill, agent, querySource, type: attribute.type ?? null, session: identity, repository });
40
+ if (seen.has(sourceId)) return { accepted: true, emitted: false };
41
+ if (seen.size >= 20000) {
42
+ seen.delete(seen.values().next().value);
43
+ telemetry.emit('collection.gap', { reasonCode: 'claude-dedup-window-rotated' });
44
+ }
45
+ if (repository || identity) telemetry.bind({ repository: repository ?? undefined, sessionId: identity ?? undefined });
46
+
47
+ const common = { model, provider: 'anthropic', modelSource: 'runtime-reported', skill, agent, querySource };
48
+ if (metric.name === 'claude_code.token.usage') {
49
+ if (metric.unit !== 'tokens') { telemetry.emit('collection.gap', { reasonCode: 'claude-token-unit-unsupported' }); return { accepted: true, emitted: false }; }
50
+ const tokenType = attribute.type;
51
+ const count = numberOf(point);
52
+ const tokenField = { input: 'inputTokens', output: 'outputTokens', cacheRead: 'cacheReadTokens', cacheCreation: 'cacheWriteTokens' }[tokenType];
53
+ if (!tokenField || count === null) { telemetry.emit('collection.gap', { reasonCode: 'claude-token-datapoint-unsupported' }); return { accepted: true, emitted: false }; }
54
+ const event = telemetry.emit('claude.usage.observed', fields({ ...common, tokenType, [tokenField]: count }), { kind: 'claude-code', id: sourceId, time });
55
+ if (!event) return { accepted: false, emitted: false };
56
+ seen.add(sourceId);
57
+ return { accepted: true, emitted: true };
58
+ }
59
+ if (metric.name === 'claude_code.cost.usage') {
60
+ if (metric.unit !== 'USD') { telemetry.emit('collection.gap', { reasonCode: 'claude-cost-unit-unsupported' }); return { accepted: true, emitted: false }; }
61
+ const costUsd = numberOf(point);
62
+ if (costUsd === null) { telemetry.emit('collection.gap', { reasonCode: 'claude-cost-datapoint-unsupported' }); return { accepted: true, emitted: false }; }
63
+ const event = telemetry.emit('claude.cost.observed', { ...fields(common), costUsd, costSource: 'claude-estimated' }, { kind: 'claude-code', id: sourceId, time });
64
+ if (!event) return { accepted: false, emitted: false };
65
+ seen.add(sourceId);
66
+ return { accepted: true, emitted: true };
67
+ }
68
+ return { accepted: true, emitted: false };
69
+ }
70
+
71
+ export function collectClaudeMetrics(payload, { telemetry, seen = new Set() } = {}) {
72
+ if (!payload || !Array.isArray(payload.resourceMetrics) || !telemetry) throw Error('Invalid Claude OTLP metrics payload');
73
+ let emitted = 0, rejected = 0;
74
+ for (const resourceMetric of payload.resourceMetrics) {
75
+ const resource = attributesOf(resourceMetric.resource?.attributes);
76
+ for (const scope of resourceMetric.scopeMetrics ?? []) for (const metric of scope.metrics ?? []) {
77
+ const points = metric.sum?.dataPoints ?? [];
78
+ for (const point of points) {
79
+ const result = mapMetric(metric, point, resource, telemetry, seen);
80
+ if (!result.accepted) rejected++;
81
+ if (result.emitted) emitted++;
82
+ }
83
+ }
84
+ }
85
+ return { emitted, rejected };
86
+ }
87
+
88
+ export function claudeUsageSummary(events) {
89
+ const records = events.filter(event => event.source?.kind === 'claude-code' && ['claude.usage.observed', 'claude.cost.observed'].includes(event.type));
90
+ const unique = [...new Map(records.map(event => [event.source.id ?? event.id, event])).values()];
91
+ const tokenTotals = { input: 0, output: 0, cacheRead: 0, cacheCreation: 0 };
92
+ const tokenSeen = new Set(), costSamples = [];
93
+ const byModel = {}, bySkill = {};
94
+ for (const event of unique) {
95
+ const { model, skill, tokenType, costUsd } = event.attributes;
96
+ if (event.type === 'claude.usage.observed') {
97
+ const key = { input: 'inputTokens', output: 'outputTokens', cacheRead: 'cacheReadTokens', cacheCreation: 'cacheWriteTokens' }[tokenType];
98
+ const amount = key ? event.attributes[key] : null;
99
+ if (typeof amount === 'number') {
100
+ tokenTotals[tokenType] += amount; tokenSeen.add(tokenType);
101
+ const modelKey = model ?? 'unknown'; byModel[modelKey] ??= { tokens: {} }; byModel[modelKey].tokens[tokenType] = (byModel[modelKey].tokens[tokenType] ?? 0) + amount;
102
+ if (skill) { bySkill[skill] ??= {}; bySkill[skill][tokenType] = (bySkill[skill][tokenType] ?? 0) + amount; }
103
+ }
104
+ } else if (typeof costUsd === 'number') {
105
+ const modelKey = model ?? 'unknown'; byModel[modelKey] ??= { tokens: {} }; byModel[modelKey].estimatedCostUsd = (byModel[modelKey].estimatedCostUsd ?? 0) + costUsd;
106
+ if (skill) bySkill[skill] = { ...bySkill[skill], estimatedCostUsd: (bySkill[skill]?.estimatedCostUsd ?? 0) + costUsd };
107
+ costSamples.push({ model: modelKey, skill, costUsd });
108
+ }
109
+ }
110
+ const totalCost = costSamples.reduce((sum, sample) => sum + sample.costUsd, 0);
111
+ const incomplete = events.some(event => event.type === 'collection.gap' && /^claude-/.test(event.attributes?.reasonCode ?? ''));
112
+ return {
113
+ source: 'claude-code-native-otlp-metrics', coverage: !unique.length ? 'unavailable' : incomplete ? 'incomplete' : 'observed',
114
+ tokens: Object.fromEntries(Object.entries(tokenTotals).map(([key, amount]) => [key, tokenSeen.has(key) ? amount : null])),
115
+ estimatedCostUsd: costSamples.length ? totalCost : null, billedCostUsd: null,
116
+ costCoverage: costSamples.length ? 'source-reported-estimate' : 'unavailable', byModel, bySkill,
117
+ };
118
+ }
119
+
120
+ export function createClaudeMetricsReceiver({ telemetry, seen = new Set(), maxBodyBytes = 1048576 } = {}) {
121
+ const server = createServer((request, response) => {
122
+ if (request.method !== 'POST' || request.url !== '/v1/metrics') { response.writeHead(404).end(); return; }
123
+ const chunks = []; let bytes = 0, overflow = false;
124
+ request.on('data', chunk => { bytes += chunk.length; if (bytes > maxBodyBytes) overflow = true; else chunks.push(chunk); });
125
+ request.on('end', () => {
126
+ if (overflow) { response.writeHead(413).end(); return; }
127
+ try {
128
+ const payload = JSON.parse(Buffer.concat(chunks).toString('utf8'));
129
+ const result = collectClaudeMetrics(payload, { telemetry, seen });
130
+ if (result.rejected) { response.writeHead(503).end(); return; }
131
+ response.writeHead(200, { 'content-type': 'application/json' }).end('{}');
132
+ } catch { response.writeHead(400).end(); }
133
+ });
134
+ });
135
+ return server;
136
+ }
137
+
138
+ export async function runClaudeTelemetry(command, { env = process.env, directory = telemetryDirectory(env) } = {}) {
139
+ if (!command.length) throw Error('A Claude Code command is required');
140
+ const telemetry = createTelemetry({ directory, component: 'claude-code', context: telemetryContext(env, { stage: env.LIGHTHOUSE_CLAUDE_STAGE, issue: env.LIGHTHOUSE_CLAUDE_ISSUE, runId: env.LIGHTHOUSE_CLAUDE_RUN_ID }), env });
141
+ const seen = new Set(readTelemetry(directory).filter(event => event.source?.kind === 'claude-code' && event.source.id).slice(-20000).map(event => event.source.id));
142
+ const server = createClaudeMetricsReceiver({ telemetry, seen });
143
+ await new Promise((resolve, reject) => { server.once('error', reject); server.listen(0, '127.0.0.1', resolve); });
144
+ const { port } = server.address();
145
+ const childEnv = { ...env,
146
+ CLAUDE_CODE_ENABLE_TELEMETRY: '1', OTEL_METRICS_EXPORTER: 'otlp', OTEL_LOGS_EXPORTER: 'none', OTEL_TRACES_EXPORTER: 'none',
147
+ OTEL_EXPORTER_OTLP_METRICS_PROTOCOL: 'http/json', OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE: 'delta',
148
+ OTEL_EXPORTER_OTLP_METRICS_ENDPOINT: `http://127.0.0.1:${port}/v1/metrics`, OTEL_METRICS_INCLUDE_SESSION_ID: env.LIGHTHOUSE_CLAUDE_INCLUDE_SESSION_ID === 'true' ? 'true' : 'false',
149
+ OTEL_METRICS_INCLUDE_ACCOUNT_UUID: 'false', OTEL_METRICS_INCLUDE_REPOSITORY: env.LIGHTHOUSE_CLAUDE_INCLUDE_REPOSITORY === 'true' ? 'true' : 'false',
150
+ OTEL_LOG_TOOL_DETAILS: '1', OTEL_LOG_USER_PROMPTS: '0', OTEL_LOG_ASSISTANT_RESPONSES: '0', OTEL_LOG_TOOL_CONTENT: '0', OTEL_LOG_RAW_API_BODIES: '0',
151
+ };
152
+ delete childEnv.OTEL_EXPORTER_OTLP_HEADERS; delete childEnv.OTEL_EXPORTER_OTLP_METRICS_HEADERS; delete childEnv.OTEL_EXPORTER_OTLP_ENDPOINT;
153
+ const child = spawn(command[0], command.slice(1), { env: childEnv, stdio: 'inherit' });
154
+ const result = await new Promise(resolve => { child.once('error', () => resolve(127)); child.once('close', code => resolve(code ?? 1)); });
155
+ await new Promise(resolve => server.close(resolve)); telemetry.close(result === 0 ? 'completed' : 'failed');
156
+ return result;
157
+ }
@@ -3,6 +3,7 @@ import { setTimeout as pause } from 'node:timers/promises';
3
3
  import { createTelemetry, readTelemetry, telemetryDirectory, telemetryHealth, telemetrySettings, exportTelemetry } from './telemetry.mjs';
4
4
  import { usageSummary } from './telemetry-opencode.mjs';
5
5
  import { installTelemetry } from './telemetry-runner.mjs';
6
+ import { claudeUsageSummary, runClaudeTelemetry } from './telemetry-claude.mjs';
6
7
 
7
8
  export async function telemetryCli(args, env = process.env) {
8
9
  const [command] = args, option = name => { const i = args.indexOf(name); return i >= 0 ? args[i + 1] : undefined; };
@@ -22,11 +23,18 @@ export async function telemetryCli(args, env = process.env) {
22
23
  if (!args.includes('--follow')) break;
23
24
  await pause(250);
24
25
  } while (true);
25
- } else if (command === 'usage') print(usageSummary(readTelemetry(directory).filter(e => !option('--run') || e.correlation.runId === option('--run')), { health: telemetryHealth(directory) }));
26
+ } else if (command === 'usage') {
27
+ const events = readTelemetry(directory).filter(e => !option('--run') || e.correlation.runId === option('--run'));
28
+ print({ ...usageSummary(events, { health: telemetryHealth(directory) }), claudeCode: claudeUsageSummary(events) });
29
+ } else if (command === 'claude' && args[1] === 'run') {
30
+ const separator = args.indexOf('--');
31
+ if (separator < 0) throw Error('Use telemetry claude run -- <claude command> [arguments]');
32
+ process.exitCode = await runClaudeTelemetry(args.slice(separator + 1), { env, directory });
33
+ }
26
34
  else if (command === 'export') {
27
35
  const endpoint = option('--endpoint') ?? env.LIGHTHOUSE_TELEMETRY_OTLP_ENDPOINT ?? telemetrySettings(directory)?.otlpEndpoint;
28
36
  if (!endpoint) throw Error('Configure an explicit OTLP HTTP JSON /v1/logs endpoint');
29
37
  const headers = env.LIGHTHOUSE_TELEMETRY_OTLP_HEADERS ? JSON.parse(env.LIGHTHOUSE_TELEMETRY_OTLP_HEADERS) : {};
30
38
  do { print(await exportTelemetry(directory, { endpoint, headers })); if (!args.includes('--follow')) break; await pause(2000); } while (true);
31
- } else throw Error('Usage: lighthouse-sdlc telemetry <install|status|read|usage|export> [--directory <operator-state>] [--stream <id> --after <sequence> --follow]');
39
+ } else throw Error('Usage: lighthouse-sdlc telemetry <install|status|read|usage|export|claude run -- <command>> [--directory <operator-state>] [--stream <id> --after <sequence> --follow]');
32
40
  }
@@ -6,6 +6,11 @@ export function tokenMetadata(tokens) {
6
6
  return { inputTokens: tokens?.input ?? null, outputTokens: tokens?.output ?? null, reasoningTokens: tokens?.reasoning ?? null, cacheReadTokens: tokens?.cache?.read ?? null, cacheWriteTokens: tokens?.cache?.write ?? null };
7
7
  }
8
8
 
9
+ function modelIdentity(model) {
10
+ const id = model?.id ?? model?.modelID;
11
+ return typeof id === 'string' ? id : null;
12
+ }
13
+
9
14
  export function openCodeObserver(emit) {
10
15
  const tools = new Map(), steps = new Map(), seen = new Set();
11
16
  return event => {
@@ -23,10 +28,10 @@ export function openCodeObserver(emit) {
23
28
  send(event.type, { tool: tool?.name, callId: data.id, messageId: data.assistantMessageID, status: event.type.endsWith('success') ? 'completed' : 'failed', durationMs: tool ? time - tool.started : null }); tools.delete(data.id);
24
29
  } else if (event.type === 'session.step.started') {
25
30
  steps.set(data.assistantMessageID, { started: data.started ?? time, model: data.model });
26
- send(event.type, { model: data.model?.modelID, provider: data.model?.providerID, messageId: data.assistantMessageID, modelSource: 'runtime-reported', status: 'running' });
31
+ send(event.type, { model: modelIdentity(data.model), provider: data.model?.providerID, messageId: data.assistantMessageID, modelSource: 'runtime-reported', status: 'running' });
27
32
  } else if (['session.step.ended', 'session.step.failed'].includes(event.type)) {
28
33
  const step = steps.get(data.assistantMessageID);
29
- send(event.type, { ...tokenMetadata(data.tokens), messageId: data.assistantMessageID, model: step?.model?.modelID, provider: step?.model?.providerID, durationMs: step ? time - step.started : null, finishReason: data.finish, status: event.type.endsWith('ended') ? 'completed' : 'failed' }); steps.delete(data.assistantMessageID);
34
+ send(event.type, { ...tokenMetadata(data.tokens), messageId: data.assistantMessageID, model: modelIdentity(step?.model), provider: step?.model?.providerID, durationMs: step ? time - step.started : null, finishReason: data.finish, status: event.type.endsWith('ended') ? 'completed' : 'failed' }); steps.delete(data.assistantMessageID);
30
35
  } else if (event.type === 'session.step.streamed') {
31
36
  const step = steps.get(data.assistantMessageID);
32
37
  send(event.type, { messageId: data.assistantMessageID, durationMs: step ? time - step.started : null });
package/src/telemetry.mjs CHANGED
@@ -12,7 +12,7 @@ const version = JSON.parse(readFileSync(new URL('../package.json', import.meta.u
12
12
  const hash = value => createHash('sha256').update(value).digest('hex');
13
13
  const identifier = value => typeof value === 'string' && /^[\w./:@#-]{1,256}$/.test(value) && !/(?:Bearer|sk-|ghp_|github_pat_|eyJ)/i.test(value) ? value : null;
14
14
  const numeric = value => typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : null;
15
- const attributes = new Set(['phase', 'status', 'reasonCode', 'reasonDigest', 'eventName', 'action', 'label', 'actorClass', 'authorization', 'decision', 'tool', 'callId', 'messageId', 'model', 'provider', 'modelSource', 'finishReason', 'requestKind', 'adapter', 'capability', 'image', 'signal', 'exitCode', 'durationMs', 'queueDurationMs', 'inputTokens', 'outputTokens', 'reasoningTokens', 'cacheReadTokens', 'cacheWriteTokens', 'stepStarts', 'stepFinishes', 'toolCalls', 'sourceEvents', 'omittedEvents', 'cpuUsageUsec', 'memoryBytes', 'memoryPeakBytes', 'pids', 'pidsPeak', 'pidsDenied', 'oomKills', 'readBytes', 'writeBytes', 'networkRxBytes', 'networkTxBytes', 'cpuLimit', 'memoryLimitBytes', 'pidsLimit', 'httpStatus', 'attempt', 'delayMs', 'streamConnected']);
15
+ const attributes = new Set(['phase', 'status', 'reasonCode', 'reasonDigest', 'eventName', 'action', 'label', 'actorClass', 'authorization', 'decision', 'tool', 'callId', 'messageId', 'model', 'provider', 'modelSource', 'finishReason', 'requestKind', 'adapter', 'capability', 'image', 'signal', 'exitCode', 'durationMs', 'queueDurationMs', 'inputTokens', 'outputTokens', 'reasoningTokens', 'cacheReadTokens', 'cacheWriteTokens', 'stepStarts', 'stepFinishes', 'toolCalls', 'sourceEvents', 'omittedEvents', 'cpuUsageUsec', 'memoryBytes', 'memoryPeakBytes', 'pids', 'pidsPeak', 'pidsDenied', 'oomKills', 'readBytes', 'writeBytes', 'networkRxBytes', 'networkTxBytes', 'cpuLimit', 'memoryLimitBytes', 'pidsLimit', 'httpStatus', 'attempt', 'delayMs', 'streamConnected', 'skill', 'agent', 'querySource', 'tokenType', 'costUsd', 'costSource']);
16
16
  const correlationKeys = ['repository', 'issue', 'pullRequest', 'revision', 'worker', 'stage', 'runId', 'workflowRunId', 'workflowAttempt', 'job', 'runner', 'sessionId', 'parentSessionId', 'requestId', 'routerRunId', 'routerAttempt', 'signalId'];
17
17
  export function metadata(values = {}) {
18
18
  return Object.fromEntries(Object.entries(values).filter(([key]) => attributes.has(key)).map(([key, value]) => [key, typeof value === 'boolean' ? value : typeof value === 'number' ? numeric(value) : identifier(value)]));
@@ -41,7 +41,7 @@ export function telemetrySettings(directory) {
41
41
  return selected;
42
42
  }
43
43
  export const telemetryCapabilities = {
44
- lifecycle: 'host-observed', opencode: 'native-2.1-plugin-with-cli-fallback', usage: 'observed-with-coverage',
44
+ lifecycle: 'host-observed', opencode: 'native-2.1-plugin-with-cli-fallback', claudeCode: 'opt-in-native-otlp-metrics', usage: 'observed-with-coverage',
45
45
  resources: 'linux-cgroup-v2-and-proc', billing: 'unavailable', payloads: 'disabled', transport: 'ndjson-and-otlp-http-json-logs',
46
46
  };
47
47
 
@@ -1,11 +1,24 @@
1
1
  import { createHash } from 'node:crypto';
2
2
  import { execFileSync } from 'node:child_process';
3
- import { sourceFiles, validateImplementationPolicy } from './implementation.mjs';
3
+ import { sourceFiles, validateImplementationPolicy, withinScope } from './implementation.mjs';
4
4
 
5
5
  const hash = value => createHash('sha256').update(value).digest('hex');
6
6
  const contains = (prefix, path) => prefix.endsWith('/') ? path.startsWith(prefix) : prefix === path;
7
7
  const fileDigest = file => file ? hash(file.mode + '\0' + file.content.toString('base64')) : null;
8
8
  export const sourceDigest = source => hash(JSON.stringify([...source].sort(([a], [b]) => a.localeCompare(b)).map(([path, file]) => [path, fileDigest(file)])));
9
+ const policyDigest = policy => hash(JSON.stringify({ checks: policy.checks, verification: policy.verification }));
10
+
11
+ export function verificationPreflight(source, policy, issue) {
12
+ if (!policy.verification) return { status: 'unconfigured' };
13
+ validateImplementationPolicy(policy, issue);
14
+ const { paths, corrections } = policy.verification;
15
+ for (const path of paths.filter(path => !path.endsWith('/'))) {
16
+ if (!source.has(path) && !(Object.hasOwn(corrections, path) && withinScope(path, policy))) {
17
+ throw Error(`Required verification input is absent before model execution: ${path}. Repair the adopter policy or admit its creation with an exact correction reason and write scope before requesting implementation again.`);
18
+ }
19
+ }
20
+ return { status: 'passed', policyDigest: policyDigest(policy) };
21
+ }
9
22
 
10
23
  // Read effective bytes, not Git status: index flags and a candidate commit cannot hide an edit.
11
24
  export async function committedSource(root, revision) {
@@ -37,7 +50,7 @@ export function verificationIntegrity(before, after, policy, issue) {
37
50
  const forbidden = changed.filter(path => !Object.hasOwn(corrections, path));
38
51
  if (forbidden.length) throw Error(`Verification inputs changed without an admitted correction reason: ${forbidden.join(', ')}`);
39
52
  for (const path of paths.filter(path => !path.endsWith('/'))) if (!after.has(path)) throw Error(`Required verification input is absent: ${path}`);
40
- return { status: 'passed', policyDigest: hash(JSON.stringify({ checks: policy.checks, verification: policy.verification })),
53
+ return { status: 'passed', policyDigest: policyDigest(policy),
41
54
  baseline: hash(JSON.stringify(inputs.map(path => [path, fileDigest(before.get(path))]))),
42
55
  candidate: hash(JSON.stringify(inputs.map(path => [path, fileDigest(after.get(path))]))),
43
56
  paths, inputCount: inputs.length, corrections: changed.map(path => ({ path, reason: corrections[path], before: fileDigest(before.get(path)), after: fileDigest(after.get(path)) })) };
@@ -27,7 +27,8 @@ export function classifyTechnicalFailure({ run, jobs, evidence = {} }) {
27
27
  if (run.conclusion === 'cancelled' || agent?.conclusion === 'cancelled') return 'cancelled';
28
28
  if (!['failure', 'timed_out'].includes(run.conclusion)) return 'none';
29
29
  if (evidence.result === 'present' || evidence.result === 'invalid') return 'substantive-failure';
30
- if (evidence.result === 'unknown') return 'evidence-unavailable';
30
+ if (evidence.result === 'unknown' || evidence.runtime === 'unknown') return 'evidence-unavailable';
31
+ if (evidence.failure?.phase === 'preflight' && evidence.failure.code === 'adopter-prerequisite') return 'substantive-failure';
31
32
  if (['out-of-memory', 'process-limit', 'aborted', 'cancelled'].includes(evidence.execution?.status)) return 'substantive-failure';
32
33
  const failed = agent?.conclusion === 'skipped' ? jobs.find(job => ['pre_activation', 'activation'].includes(job.name) && ['failure', 'timed_out'].includes(job.conclusion)) : agent;
33
34
  const started = Date.parse(failed?.started_at), ended = Date.parse(failed?.completed_at);
@@ -48,7 +49,11 @@ export async function readFailureEvidence(api, repository, request, run, jobs, r
48
49
  const value = await readArtifact(api, repository, run.id, `${prefix}-${request.issue}-${run.run_attempt}`, 'envelope.json', true);
49
50
  evidence.result = value == null ? 'absent' : 'present';
50
51
  } catch { evidence.result = 'unknown'; }
51
- try { evidence.execution = (await readArtifact(api, repository, run.id, `${prefix}-${request.issue}-${run.run_attempt}`, 'runtime.json', true))?.execution; } catch {}
52
+ try {
53
+ const runtime = await readArtifact(api, repository, run.id, `${prefix}-${request.issue}-${run.run_attempt}`, 'runtime.json', true);
54
+ evidence.execution = runtime?.execution;
55
+ evidence.failure = runtime?.failure;
56
+ } catch { evidence.runtime = 'unknown'; }
52
57
  const agent = jobs.find(job => job.name === 'agent');
53
58
  if (!agent?.id) return evidence;
54
59
  const prefixUrl = `https://api.github.com/repos/${repository}/check-runs/`;
package/telemetry.md CHANGED
@@ -40,6 +40,10 @@ The runner emits startup, heartbeat, hook wait and stop observations. It closes
40
40
 
41
41
  OpenCode 2.1 uses a native plugin for model steps, stream boundaries, tools, retries, permissions, compactions and session activity. This is version-specific; another engine needs its own declared adapter. Existing CLI events remain a fallback. Usage selects native model-step observations when available, otherwise CLI observations, and never adds both. It reports step starts/finishes and per-field token sums with `observed`, `incomplete` or `unavailable` coverage. Compaction/title usage is outside those primary-step sums. Cost is unknown; neither a zero engine cost field nor requested model configuration proves billing or provider identity.
42
42
 
43
+ Claude Code collection is separately opt-in through `lighthouse-sdlc telemetry claude run -- claude ...`. The wrapper starts a loopback-only OTLP/HTTP JSON metrics receiver, configures Claude Code to export delta metrics, disables log and trace exporters, and records allowlisted token/cost measurements as `claude.usage.observed` and `claude.cost.observed` events. It ignores prompts, transcripts, tool data, user/account/organization/host identifiers and unrecognized metrics. Tokens retain their source type (`input`, `output`, `cacheRead` or `cacheCreation`); reported USD cost is tagged as an estimate and billed cost stays null. Source-reported model and skill names are retained when Claude provides them. The wrapper enables `OTEL_LOG_TOOL_DETAILS=1` so Claude Code versions that support it can report named skills on metrics; because logs are disabled, tool contents and arguments are not exported. Use Claude Code v2.1.273 or later for skill attribution on token and cost metrics. Session IDs are hashed before becoming correlation metadata and repository attribution remains opt-in. See [Claude Code monitoring](https://code.claude.com/docs/en/monitoring-usage) for supported metric names, attributes, temporality and privacy controls.
44
+
45
+ Claude's native usage metrics do not report a Lighthouse workflow stage, issue command or run ID by default. Those values remain unknown unless an operator supplies the supported `LIGHTHOUSE_CLAUDE_STAGE`, `LIGHTHOUSE_CLAUDE_ISSUE` and `LIGHTHOUSE_CLAUDE_RUN_ID` context to the wrapper. Token buckets are measurements from source metric points, not reconstructed model calls; exporters can retry and the collector deduplicates repeated source points by stable source identity. The `usage` command reports a separate `claudeCode` aggregate and never adds those observations to OpenCode totals.
46
+
43
47
  `durationMs` is wall-clock milliseconds between matched observations. The native `session.step.streamed` duration separates provider response streaming from tool settlement. Cgroup samples expose cumulative `cpuUsageUsec`, current/peak memory bytes, process counts, cumulative block-device read/write bytes and container-namespace network bytes. Disk counters exclude cache-backed IO that does not reach the block layer. Unsupported counters remain null. Limits and execution/independent-check receipts remain separate from utilization. Sampled values do not establish a billing rate or human effort.
44
48
 
45
49
  ## Export and health