@juangcarmona/lighthouse-sdlc 0.28.0 → 0.29.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,5 +1,11 @@
1
1
  # Lighthouse delivery
2
2
 
3
+ For optional worker command presentation, see [compact output and complete diagnostic recovery](compact-output.md). Operators explicitly select it in their private configuration; ordinary and trusted check output keeps its existing behavior.
4
+
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
+
7
+ 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
+
3
9
  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.
4
10
 
5
11
  ## Check the installed version first
@@ -0,0 +1,11 @@
1
+ # Change context and instruction review
2
+
3
+ Before proposing or continuing a change, use `context.continuity` to locate the admitted work item, task digest, source revision, decision owner and original inputs. The full intent and criteria remain in `context.issue`; questions and decisions remain in its owner answers and the retained predecessor evidence. Read those original records. The context contains pointers and provenance instead of a second product definition. Imported observations and task text do not establish approval. ProductShape owns product meaning; ArcShape owns architecture; the trusted host authenticates execution and decisions.
4
+
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
+
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.
8
+
9
+ 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
+
11
+ Keep shared instructions in their canonical package source and host projections thin. Regenerate provider-owned projections through the pinned provider and verify drift. Repair project-owned guidance in the reviewable candidate. Preserve historical ADR decisions and qualify their later implementation status with current source evidence. Unrelated guidance does not require a rewrite, and this review creates no new lifecycle stage or approval authority.
@@ -0,0 +1,11 @@
1
+ # Optional compact command output
2
+
3
+ Operators can set `"compactOutput": true` in their private engine configuration after installing and pinning RTK in the selected worker image. Lighthouse qualifies [RTK 1.2.0](https://github.com/rtk-ai/rtk/releases/tag/v1.2.0), source `e288a18c04452fd26192f59132e5324a8bb6924d`. Installation and upgrades leave this option disabled. Turning it off restores ordinary output; existing logs remain evidence.
4
+
5
+ The worker's managed command slot executes the original command once and saves its complete stdout/stderr. For successful `git status`, `git diff`, `git log`, `rg`, `grep`, `find`, `fd`, `tsc`, `pytest` and `vitest` commands, the adapter can feed that retained log to `rtk pipe --filter`. It uses no OpenCode hook and rewrites no executable command. Unsupported commands and failed commands remain unabridged. Missing RTK, incompatible filters, errors, warnings, timeout, oversized input/output or an empty/non-reducing result produce a visible fallback to the complete log. Shell-wrapped commands remain unabridged because their command identity is not inferred.
6
+
7
+ The terminal command receipt records the presentation status and `rawLog`; compact output also prints the full-log path. Read that file for complete diagnostics. Failed commands and successful output containing explicit fatal, panic, exception, error or failure markers remain unabridged. For a failing build or test, inspect both the original `exitCode` and full output before continuing. Caller redirection into the same managed log keeps the original output; use a separate caller log when compact presentation is wanted.
8
+
9
+ Only the model's command presentation changes. Trusted host commands, check receipts, CI, content digests and publication decisions retain their existing inputs. The option is passed only to the worker container. It grants no new tool, write, review or merge authority. The engine image, operator configuration and retained log lifecycle remain operator-owned.
10
+
11
+ Task-specific lifecycle instructions already load from the selected packaged skill; required repository policy and startup/fallback instructions remain in force. The adapter adds no always-loaded RTK plugin or replacement system prompt. A real-worker exercise must establish compact output and diagnostic recovery independently of source tests; this feature claims no token or cost savings.
package/epic-delivery.md CHANGED
@@ -41,3 +41,15 @@ The credentialed host must supply `withLease(parentKey, work)` with a serialized
41
41
  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
42
 
43
43
  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
+
45
+ ## An approved product prerequisite before implementation
46
+
47
+ When an epic child's planning is blocked by product intent already reviewed and applied outside the worker, the owner can adopt that exact product source before the child publishes an implementation PR. The source PR must target the current epic branch and contain only the ProductShape model delta and one completed change manifest. Keep the source PR open and its head unchanged until the child is accepted. Product approval, stage execution and merge retain their separate authority.
48
+
49
+ The owner reviews the complete applied diff and posts an unedited comment on that PR with `/epic-product approve CHILD CHANGE_NAME HEAD_SHA BASE_SHA`, replacing the four values with the child number, completed change directory name and exact source and epic commits. Run the installed epic workflow with `action: adopt-product`, the parent `issue`, `child`, `pull-request`, `product-change`, `product-approval` comment ID, `head` and `base`. Use a reviewed workflow revision containing this capability for the adoption and later child stages; an older default-branch workflow cannot select the new source.
50
+
51
+ The trusted host reconstructs the approved Product Change in a temporary checkout of the current epic base. Provider replay runs in a separate process without publisher or model credentials. The pinned ProductShape core plans and executes the apply, validates the resulting model, reports affected citations and verifies every resulting path and byte against the source PR. The host records a separate product-source journal entry and retained successful action. Adoption updates no source branch, creates no implementation publication and performs no merge.
52
+
53
+ Fresh triage, refinement and implementation bind the adopted source head while retaining the original plan, default-branch policy and accepted dependency base. The implementation verifier protects both the model and the completed change evidence. The native child PR includes the product delta and code together; its checked acceptance advances the epic branch through the ordinary child receipt. The source PR is review evidence, so it is never registered as the child's implementation.
54
+
55
+ Changed or edited approval, a later owner product command, source changes, missing or expired evidence, a moved epic base or unrelated source files stop continuation. Adoption after an implementation publication is unsupported and stops without replacing that work. A failed or uncertain adoption needs journal reconciliation; repeating a worker against the unchanged product baseline cannot resolve it.
package/github-actions.md CHANGED
@@ -134,6 +134,8 @@ The [router](workflows/lighthouse-sdlc-router.yml) and [event handler](src/issue
134
134
 
135
135
  The `apply-review` worker is installed with proposal support. It also handles implementation feedback when implementation is installed, preserving its `implement` result. Verified feedback has a stable dispatch identity across repeated events. Approval retains its separate integration route.
136
136
 
137
+ An owner can also request an implementation correction through the router's `workflow_dispatch` entry with `stage=implement`, the source `issue`, exact `pull_request` and `head`, and bounded `feedback`. This lets a reviewed recovery controller update the existing PR while the default workflow remains unchanged. The host authenticates the owner-triggered router run and immutable request, binds the feedback to the current head, rechecks its origin and discussion before publication, and uses the same `apply-review` checks and non-forced update. A cancelled or failed source request stops publication. This entry grants no approval or merge authority; stage-only client intents cannot supply correction feedback.
138
+
137
139
  ## GitHub read recovery
138
140
 
139
141
  Bodyless GitHub GET requests can make up to three total HTTP attempts, including the initial attempt, for responses 429, 500, 502, 503 and 504. All attempts and waits share the original thirty-second request budget; `Retry-After` is respected only when its delay fits the remaining budget. This transport retry does not automatically repeat POST/PATCH/PUT/DELETE, permanent refusals, thrown network errors or uncertain publication effects.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@juangcarmona/lighthouse-sdlc",
3
- "version": "0.28.0",
3
+ "version": "0.29.0",
4
4
  "type": "module",
5
5
  "description": "Provider-neutral SDLC skills, commands and route contracts for Lighthouse adopters",
6
6
  "repository": {
@@ -50,7 +50,10 @@
50
50
  "issue-control.md",
51
51
  "practice-evidence.md",
52
52
  "delivery-acceptance.md",
53
- "measurements.md"
53
+ "measurements.md",
54
+ "compact-output.md",
55
+ "change-continuity.md",
56
+ "process-guards.md"
54
57
  ],
55
58
  "bin": {
56
59
  "lighthouse-sdlc": "./src/sdlc.mjs"
@@ -0,0 +1,20 @@
1
+ # Verified process guards
2
+
3
+ Use this route during review when a real delivery failure suggests a recurring check. Retain the original claim, actual outcome and evidence first. Distinguish the code defect from the process gap; a bug fix does not automatically justify another process control.
4
+
5
+ Choose one owning source and maintainer. Sharpen an existing check before adding a mechanism. Reproduce the original behavior with that check and retain its failing revision, actual nonzero exit and evidence. Run the same behavioral assertion on the corrected revision and retain its passing exit and evidence. An unrelated infrastructure failure is not the required failing case. If the evidence is unavailable or the guard is still a proposal, keep it in the existing retrospective/backlog with its owner; do not call it verified.
6
+
7
+ For newly admitted review work, return `output.processGuards` with `schemaVersion: 1`, `outcome`, `reason` and `records`. Use `outcome: no-guard` with an empty array and a reason when existing controls suffice or no additional recurring control is justified. `outcome: recorded` requires at least one verified record with these fields:
8
+
9
+ | Field | Required content |
10
+ | --- | --- |
11
+ | `id`, `version` | Stable lowercase guard ID and semantic record version |
12
+ | `failure` | `claim`, `outcome`, `codeDefect`, `processGap` and nonempty `evidence` references |
13
+ | `owner`, `source` | Responsible maintainer and one canonical owning source |
14
+ | `check` | Owning `command`; `red` and `green` each with the actual full Git `revision`, `exitCode` and nonempty `evidence` references |
15
+ | `adoption` | Adopted `version`, affected `scope`, `rollback`, `retireWhen` and owned `followUp` |
16
+ | `observations` | `recurrence`, `falsePositives` and `maintenanceCost`, each with observed evidence or an explicit unavailable reason |
17
+
18
+ The host validates the record's shape and failing/passing dispositions. The review must authenticate the cited evidence; a record's assertions do not prove their own source. The durable stage result and its existing issue/PR review preserve the finding. Tests prove their exercised cases; they do not establish operational recurrence rates or pilot costs. The parent pilot retains those observations and their coverage gaps.
19
+
20
+ Change a provider-owned guard through its provider and verify generated drift; change project-owned checks in an ordinary reviewed candidate. A policy change follows its owning Product Change and approval process. This review cannot change its permissions, scope or acceptance criteria. Retain adopted version, rollback and retirement conditions with the follow-up owner, and reassess false positives and maintenance cost before expanding a guard. No general learning service or automatic policy mutation is introduced.
@@ -19,7 +19,7 @@ For user-facing view or interaction changes, read [visual evidence](../visual-ev
19
19
  2. Read `/harness/skills/propose/SKILL.md` for planning and use the supplied OpenSpec instructions to create or update the proposal, specifications, design and tasks before changing production code. This is the planning part of implementation; return one final implementation envelope. Keep tasks coarse and dependency ordered. Reuse existing planning work where it still applies.
20
20
  3. Implement the tasks, with tests that exercise the changed behavior. Follow the repository's architecture and allowed write scope.
21
21
  4. Run dependency installation, builds and tests through the workspace command slot below. Capture their completed exit status and evidence before marking tasks done.
22
- 5. Write a short PR summary: what changed, how it was checked, and any blocker. Put logs, screenshots and the retrospective in the evidence output. Complete the audience policy's human-writing reviews and evidence comparison, using its explicit fallback when the pinned helper is unavailable.
22
+ 5. Apply [change continuity and instruction review](../../change-continuity.md), returning `output.instructionReview` when requested by the host. Write a short PR summary: what changed, how it was checked, and any blocker. Put logs, screenshots and the retrospective in the evidence output. Complete the audience policy's human-writing reviews and evidence comparison, using its explicit fallback when the pinned helper is unavailable.
23
23
  6. Return the implementation stage result and envelope. Keep missing evidence, failed checks and required decisions explicit. The host publishes the branch for review.
24
24
 
25
25
  ## Completion
@@ -28,7 +28,9 @@ Return `passed` when the bounded candidate is ready and its available workspace
28
28
 
29
29
  ## Workspace command slot
30
30
 
31
- Run installation, build, verification and browser commands sequentially with `node /harness/src/managed-command.mjs run /output/evidence/commands <unique-attempt-id> -- <executable> <arguments...>`. Create the evidence directory first and redirect each attempt's output to its own log. The wrapper rejects overlapping commands and writes `/output/evidence/commands/<unique-attempt-id>.json`.
31
+ When a command receipt reports compact output, read [the output recovery contract](../../compact-output.md) before diagnosing a failure or relying on omitted details. Its `rawLog` retains the original output; presentation never establishes a passing check.
32
+
33
+ Run installation, build, verification and browser commands sequentially with `node /harness/src/managed-command.mjs run /output/evidence/commands <unique-attempt-id> -- <executable> <arguments...>`. Create the evidence directory first and redirect each attempt's output to `/output/evidence/<unique-attempt-id>.log`. The wrapper owns the receipt and live capture files under `/output/evidence/commands/`; it rejects overlapping commands and writes `/output/evidence/commands/<unique-attempt-id>.json`.
32
34
 
33
35
  When the shell tool backgrounds a command, poll that receipt until `state` is `completed` or `cancelled`. A tool response or a quiet log does not establish command completion. Read `exitCode` before editing the workspace or starting the next command. To interrupt an attempt, run `node /harness/src/managed-command.mjs stop /output/evidence/commands` and wait for its terminal receipt before retrying with a new ID.
34
36
 
@@ -15,7 +15,7 @@ For proposals, change overviews, PR descriptions or agent-facing instructions, r
15
15
 
16
16
  For proposed user-facing views or interactions, read [visual evidence](../visual-evidence/SKILL.md) and return concrete proposed examples with the design. Requests with `request.visualEvidence` also require an explicit non-applicability or unavailable assessment when appropriate.
17
17
 
18
- 1. Read the Ready evidence and inspect the current product and architecture authorities.
18
+ 1. Read the Ready evidence and inspect the current product and architecture authorities. Apply [change continuity](../../change-continuity.md) to retain original intent, criteria, questions and source decisions before planning. Stop for the named owner when current authority conflicts.
19
19
  2. Create or update the OpenSpec change artifacts through the installed OpenSpec workflow. Always return `proposal.md`, `design.md` and `tasks.md`, including for documentation-only changes. For a change without spec-level behavior, return `.openspec.yaml` containing exactly `skip_specs: true` instead of a specification; the host adds it to provider-owned metadata.
20
20
  3. Describe the solution, interfaces, data effects, test impact, slices, risks and Definition of Done.
21
21
  4. Write a concise change overview using the audience policy's human-writing review order and final evidence comparison. Preserve facts, links, commands, frontmatter and code; record the review method in the result output. Complete its explicit fallback when the pinned helper is unavailable.
@@ -25,4 +25,8 @@ The completed change has a durable review result, classified findings and a clea
25
25
 
26
26
  Compare the accepted work item, changed paths, integrated revision and authenticated post-merge checks. Preserve missing and pending evidence. Check instructions affected by the delivered change and report stale or conflicting guidance with file references; an intentional host-specific difference is not drift by itself.
27
27
 
28
+ Apply [change continuity](../../change-continuity.md), compare the implementation's retained `instructionReview` with the integrated source and classify unresolved findings with their responsible owner. Product and architecture observations remain separate from approved decisions.
29
+
28
30
  Return `output.retrospective` as Markdown covering what went well, what went wrong, start doing, stop doing and improvement candidates. State when no finding was established. Each proposed improvement identifies the observed failure, supporting evidence, affected owner, smallest useful guard and how to reproduce the failure before checking the correction. Distinguish recurrence across work items from retries of one attempt. Do not invent attention-time or cost measurements. Changes to policy or provider-owned guidance require their own review; this stage only records the finding.
31
+
32
+ When `request.processGuardReview` is `1`, apply [verified process guards](../../process-guards.md) and return `output.processGuards`. Reuse an existing check where it detects the demonstrated failure. Record a reasoned `no-guard` outcome when no additional recurring control is justified; retain unqualified proposals with their owner in the retrospective.
@@ -0,0 +1,37 @@
1
+ import { taskDigest } from './digests.mjs';
2
+
3
+ export function retainedChangeContext(request, issue) {
4
+ return {
5
+ schemaVersion: 1,
6
+ workItem: { repository: request.repository ?? null, number: request.issue ?? issue.number ?? null, url: issue.html_url ?? null, revision: issue.updated_at ?? null, taskDigest: request.taskDigest ?? null },
7
+ sourceRevision: request.sourceRevision ?? null,
8
+ decisionOwner: request.repository?.split('/')[0] ?? 'repository owner',
9
+ inputs: { intentAndCriteria: 'issue.title and issue.body', questionsAndDecisions: 'issue.ownerAnswers and predecessor/refinement evidence', interpretation: 'Admitted task data and retained observations; product approval requires its authenticated source.' },
10
+ authorities: { product: 'ProductShape: .product/config.yaml and its accepted model', architecture: 'ArcShape: installed provider configuration and architecture sources', instructions: 'Repository AGENTS.md and its applicable pointers; host projections retain their own ownership.' },
11
+ };
12
+ }
13
+
14
+ export function assertRetainedIntent(request, issue, answers) {
15
+ if (taskDigest(issue, answers) !== request.taskDigest) throw Error(`Issue or owner answers changed; request refinement again. Decision owner: ${request.repository?.split('/')[0] ?? 'repository owner'}. Retain the previous intent and authenticate a fresh continuation.`);
16
+ }
17
+
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' }],
21
+ };
22
+
23
+ export function validateInstructionReview(value, files) {
24
+ const errors = [], text = value => typeof value === 'string' && value.trim() && value.length <= 4000;
25
+ const path = value => typeof value === 'string' && value.length <= 512 && !/[\\\0]/.test(value) && !value.startsWith('/') && value.split('/').every(p => p && p !== '.' && p !== '..');
26
+ if (!value || Object.keys(value).sort().join(',') !== 'reason,schemaVersion,sources,status' || value.schemaVersion !== 1 || !['reviewed', 'not-applicable', 'blocked'].includes(value.status) || !text(value.reason) || !Array.isArray(value.sources) || value.sources.length > 100) return ['Instruction review must identify its version, status, scope reason and bounded source findings'];
27
+ if (value.status === 'blocked') errors.push('Unresolved instruction drift requires the named owner before completion');
28
+ if (value.status === 'reviewed' && !value.sources.length || value.status === 'not-applicable' && value.sources.length) errors.push('Instruction review scope and source findings disagree');
29
+ const seen = new Set();
30
+ for (const source of value.sources) {
31
+ if (!source || Object.keys(source).sort().join(',') !== 'evidence,owner,path,status' || !path(source.path) || seen.has(source.path) || !text(source.owner) || !text(source.evidence) || !['current', 'corrected', 'host-specific', 'stale', 'conflict', 'missing'].includes(source.status)) { errors.push('Instruction review has an invalid, duplicate or unowned source finding'); continue; }
32
+ seen.add(source.path);
33
+ if (['stale', 'conflict', 'missing'].includes(source.status)) errors.push(`Instruction ${source.status}: ${source.path}; responsible owner: ${source.owner}`);
34
+ if (files && !files.has(source.path)) errors.push(`Reviewed instruction source is absent from the candidate: ${source.path}`);
35
+ }
36
+ return errors;
37
+ }
@@ -0,0 +1,23 @@
1
+ import { openSync, closeSync, statSync, readFileSync } from 'node:fs';
2
+ import { spawnSync } from 'node:child_process';
3
+ import { basename } from 'node:path';
4
+
5
+ // Format retained output only. Command execution and trusted checks stay upstream.
6
+ export function compactCommandOutput(log, command, exitCode, { env = process.env, execute = spawnSync } = {}) {
7
+ if (env.LIGHTHOUSE_COMPACT_OUTPUT !== 'rtk') return null;
8
+ const raw = { mode: 'rtk', status: 'unabridged', rawLog: log };
9
+ if (exitCode !== 0) return { ...raw, reason: 'command-failed' };
10
+ const [program, subcommand] = command, name = basename(program);
11
+ const filter = name === 'git' && ['status', 'diff', 'log'].includes(subcommand) ? `git-${subcommand}`
12
+ : ({ rg: 'rg', grep: 'grep', find: 'find', fd: 'fd', tsc: 'tsc', pytest: 'pytest', vitest: 'vitest' })[name];
13
+ if (!filter) return { ...raw, reason: 'unsupported-command' };
14
+ if (statSync(log).size > 4 * 1024 * 1024) return { ...raw, reason: 'output-bound' };
15
+ if (/\b(?:fatal|panic|exception|errors?|failed|failure)\b/i.test(readFileSync(log, 'utf8'))) return { ...raw, reason: 'diagnostics-present' };
16
+ const fd = openSync(log, 'r');
17
+ try {
18
+ const result = execute('rtk', ['pipe', '--filter', filter], { stdio: [fd, 'pipe', 'pipe'], encoding: 'utf8', timeout: 10000, maxBuffer: 256 * 1024, env });
19
+ if (result.status !== 0 || result.error || !result.stdout?.trim() || result.stderr?.trim() || Buffer.byteLength(result.stdout) >= statSync(log).size) return { ...raw, reason: result.error?.code === 'ENOENT' ? 'optimizer-missing' : 'optimizer-unavailable' };
20
+ return { mode: 'rtk', status: 'compacted', filter, rawLog: log, text: result.stdout };
21
+ } catch { return { ...raw, reason: 'optimizer-unavailable' }; }
22
+ finally { closeSync(fd); }
23
+ }
@@ -52,7 +52,7 @@ export async function dispatchEpicTriage(api, { repository, owner, runId }, { re
52
52
  const recovery = action.name.startsWith('lighthouse-epic-recovery-');
53
53
  const parent = Number(action.name.match(/-([1-9][0-9]*)-1$/)[1]);
54
54
  const record = await readArtifact(api, repository, runId, action.name, recovery ? 'recovery.json' : 'result.json');
55
- if (run.path !== '.github/workflows/lighthouse-sdlc-epic.yml' || run.event !== 'workflow_dispatch' || run.status !== 'completed' || run.conclusion !== 'success' || run.run_attempt !== 1 || run.actor?.login !== owner || run.triggering_actor?.login !== owner || run.repository?.full_name !== repository || record?.schemaVersion !== 1 || record.repository !== repository || record.workflowRevision !== run.head_sha || (recovery ? record.recoveryRun !== String(run.id) || record.kind !== 'partial-publication-recovery' || record.state !== 'confirmed' || record.status !== 'reconciled' : record.runId !== String(run.id) || record.attempt !== 1 || record.parent !== parent || record.workflowRef !== run.head_branch || !['authorized', 'reconciled', 'linked', 'ready', 'accepted', 'published'].includes(record.result?.status) || !['reconcile', 'refine-child', 'register-pr', 'recover-publication', 'ready-child', 'accept-child', 'publish-aggregate', 'ready-aggregate', 'accept-aggregate'].includes(record.action))) throw Error('Epic action origin is not authenticated');
55
+ if (run.path !== '.github/workflows/lighthouse-sdlc-epic.yml' || run.event !== 'workflow_dispatch' || run.status !== 'completed' || run.conclusion !== 'success' || run.run_attempt !== 1 || run.actor?.login !== owner || run.triggering_actor?.login !== owner || run.repository?.full_name !== repository || record?.schemaVersion !== 1 || record.repository !== repository || record.workflowRevision !== run.head_sha || (recovery ? record.recoveryRun !== String(run.id) || record.kind !== 'partial-publication-recovery' || record.state !== 'confirmed' || record.status !== 'reconciled' : record.runId !== String(run.id) || record.attempt !== 1 || record.parent !== parent || record.workflowRef !== run.head_branch || !['authorized', 'reconciled', 'linked', 'ready', 'accepted', 'published'].includes(record.result?.status) || !['reconcile', 'adopt-product', 'refine-child', 'register-pr', 'recover-publication', 'ready-child', 'accept-child', 'publish-aggregate', 'ready-aggregate', 'accept-aggregate'].includes(record.action))) throw Error('Epic action origin is not authenticated');
56
56
  if (recovery || !['reconcile', 'refine-child'].includes(record.action)) return { status: 'settled', parent, children: [] };
57
57
  }
58
58
  const names = inventory.artifacts.filter(item => !item.expired).map(item => item.name).filter(name => /^lighthouse-epic-journal-[1-9][0-9]*-1$/.test(name));
@@ -6,7 +6,7 @@ const positive = value => Number.isSafeInteger(value) && value > 0;
6
6
  const prefix = '<!-- lighthouse-epic:';
7
7
 
8
8
  export function epicCorrelation({ repository, parent, slice, planDigest, base, dependencies, kind = 'child' }) {
9
- if (!/^[\w.-]+\/[\w.-]+$/.test(repository ?? '') || !positive(parent) || typeof slice !== 'string' || !slice.trim() || !/^[a-f0-9]{64}$/.test(planDigest ?? '') || base !== `lighthouse/epic-${parent}` || !Array.isArray(dependencies) || dependencies.some(id => typeof id !== 'string' || !id.trim()) || !['child', 'pull-request', 'aggregate'].includes(kind)) throw Error('Invalid epic correlation');
9
+ if (!/^[\w.-]+\/[\w.-]+$/.test(repository ?? '') || !positive(parent) || typeof slice !== 'string' || !slice.trim() || !/^[a-f0-9]{64}$/.test(planDigest ?? '') || base !== `lighthouse/epic-${parent}` || !Array.isArray(dependencies) || dependencies.some(id => typeof id !== 'string' || !id.trim()) || !['child', 'pull-request', 'aggregate', 'product-source'].includes(kind)) throw Error('Invalid epic correlation');
10
10
  return { schemaVersion: 1, kind, repository, parent, slice, planDigest, base, dependencies: [...new Set(dependencies)].sort() };
11
11
  }
12
12
 
@@ -5,11 +5,18 @@ import { readActionsJson } from './actions-artifact.mjs';
5
5
  import { epicCorrelation, epicJournalKey } from './epic-github.mjs';
6
6
 
7
7
  const marker = '<!-- lighthouse-epic-journal:';
8
+ const productMarker = '<!-- lighthouse-epic-product-source:';
9
+ const journalComment = comment => comment.body?.includes(marker) || comment.body?.includes(productMarker);
8
10
  const positive = value => Number.isSafeInteger(Number(value)) && /^[1-9][0-9]*$/.test(String(value));
9
11
  const sha = value => /^[a-f0-9]{40}$/.test(value ?? '');
10
12
  const keyFor = epicJournalKey;
11
13
  const artifactName = (parent, attempt) => `lighthouse-epic-journal-${parent}-${attempt}`;
12
14
 
15
+ export function checkEpicProductReceipt(value) {
16
+ if (!value || Object.keys(value).sort().join(',') !== 'approval,base,changeId,changeName,child,filesDigest,head,provider,version' || !Number.isSafeInteger(value.child) || !positive(value.child) || !Number.isSafeInteger(value.approval) || !positive(value.approval) || !sha(value.base) || !sha(value.head) || !/^CHG-[A-Z0-9-]+$/.test(value.changeId ?? '') || !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(value.changeName ?? '') || !/^[a-f0-9]{64}$/.test(value.filesDigest ?? '') || value.provider !== '@prodshape/core' || value.version !== '0.25.0') throw Error('Invalid epic product source receipt');
17
+ return value;
18
+ }
19
+
13
20
  function checkedReceipt(key, receipt, repository, parent) {
14
21
  if (!receipt || receipt.schemaVersion !== 1 || !['intent', 'created', 'linked', 'cancelled', 'merging', 'accepted'].includes(receipt.state) || !isDeepStrictEqual(receipt.correlation, epicCorrelation(receipt.correlation)) || receipt.correlation.repository !== repository || receipt.correlation.parent !== parent || keyFor(receipt.correlation) !== key) throw Error('Invalid epic journal receipt');
15
22
  const resource = receipt.resource;
@@ -22,6 +29,9 @@ function checkedReceipt(key, receipt, repository, parent) {
22
29
  const refusal = receipt.refusal;
23
30
  if (refusal !== undefined && (receipt.correlation.kind !== 'pull-request' || receipt.state !== 'linked' || !refusal || refusal.status !== 405 || !sha(refusal.head) || !sha(refusal.base) || !sha(refusal.candidate) || !Number.isSafeInteger(refusal.review) || refusal.review < 1 || Object.keys(refusal).sort().join(',') !== 'base,candidate,head,review,status')) throw Error('Epic refusal receipt is invalid');
24
31
  const readiness = receipt.readiness;
32
+ const product = receipt.product;
33
+ if (receipt.correlation.kind === 'product-source' && ['created', 'linked'].includes(receipt.state)) checkEpicProductReceipt(product);
34
+ else if (product !== undefined || receipt.correlation.kind === 'product-source' && !['intent', 'cancelled'].includes(receipt.state)) throw Error('Invalid epic product source state');
25
35
  if (readiness !== undefined && (receipt.correlation.kind !== 'aggregate' || receipt.state !== 'linked' || !readiness || !sha(readiness.head) || !sha(readiness.base) || !sha(readiness.candidate) || Object.keys(readiness).sort().join(',') !== 'base,candidate,head')) throw Error('Epic aggregate readiness receipt is invalid');
26
36
  for (const field of ['checks', 'headChecks']) {
27
37
  const checks = receipt[field];
@@ -31,14 +41,14 @@ function checkedReceipt(key, receipt, repository, parent) {
31
41
  if (!['pull-request', 'aggregate'].includes(receipt.correlation.kind) || !resource || !checks || !identity || !sha(identity.head) || !sha(identity.base) || !sha(identity.candidate) || identity.branch !== `lighthouse/verification-${resource.number}-${identity.candidate}` || !Array.isArray(identity.workflows) || !identity.workflows.length || identity.workflows.length > 8 || new Set(identity.workflows).size !== identity.workflows.length || identity.workflows.some(name => !/^[\w.-]+\.ya?ml$/.test(name)) || !['not-sent', 'requested', 'observed'].includes(checks.reference) || !checks.requests || Array.isArray(checks.requests) || typeof checks.requests !== 'object' || Object.keys(checks).sort().join(',') !== 'identity,reference,requests' || Object.keys(identity).sort().join(',') !== 'base,branch,candidate,head,workflows') throw Error('Epic check identity is invalid');
32
42
  for (const [name, request] of Object.entries(checks.requests)) if (!identity.workflows.includes(name) || !request || !['requested', 'acknowledged', 'observed'].includes(request.state) || Object.keys(request).sort().join(',') !== (request.state === 'observed' ? 'run,state' : 'state') || request.state === 'observed' && !positive(request.run)) throw Error('Epic CI request is invalid');
33
43
  }
34
- const expected = [...(receipt.checks ? ['checks'] : []), ...(receipt.headChecks ? ['headChecks'] : []), 'correlation', ...(merge ? ['merge'] : []), ...(publication ? ['publication'] : []), ...(readiness ? ['readiness'] : []), ...(refusal ? ['refusal'] : []), ...(resource ? ['resource'] : []), 'schemaVersion', 'state'].sort().join(',');
44
+ const expected = [...(receipt.checks ? ['checks'] : []), ...(receipt.headChecks ? ['headChecks'] : []), 'correlation', ...(merge ? ['merge'] : []), ...(publication ? ['publication'] : []), ...(product ? ['product'] : []), ...(readiness ? ['readiness'] : []), ...(refusal ? ['refusal'] : []), ...(resource ? ['resource'] : []), 'schemaVersion', 'state'].sort().join(',');
35
45
  if (Object.keys(receipt).sort().join(',') !== expected) throw Error('Epic receipt has unexpected fields');
36
46
  return receipt;
37
47
  }
38
48
 
39
49
  function parseEntry(comment, repository, parent) {
40
50
  if (comment.user?.login !== 'github-actions[bot]' || comment.user.type !== 'Bot' || comment.issue_url !== `https://api.github.com/repos/${repository}/issues/${parent}` || !positive(comment.id)) throw Error('Untrusted epic journal comment');
41
- const matches = [...(comment.body ?? '').matchAll(/<!-- lighthouse-epic-journal:(\{[^\n]*\}) -->/g)];
51
+ const matches = [...(comment.body ?? '').matchAll(/<!-- lighthouse-epic-(?:journal|product-source):(\{[^\n]*\}) -->/g)];
42
52
  if (matches.length !== 1) throw Error('Missing or ambiguous epic journal marker');
43
53
  const value = JSON.parse(matches[0][1]);
44
54
  const workflow = value.workflowRevision !== undefined || value.workflowRef !== undefined;
@@ -46,6 +56,7 @@ function parseEntry(comment, repository, parent) {
46
56
  const fields = ['attempt', 'key', 'parent', 'receipt', 'repository', 'revision', 'runId', 'schemaVersion', ...(workflow ? ['workflowRevision', 'workflowRef'] : [])].sort().join(',');
47
57
  if (Object.keys(value).sort().join(',') !== fields || value.schemaVersion !== 1 || value.repository !== repository || value.parent !== parent || !positive(value.runId) || !Number.isSafeInteger(value.attempt) || value.attempt < 1 || !sha(value.revision) || typeof value.key !== 'string') throw Error('Invalid epic journal identity');
48
58
  checkedReceipt(value.key, value.receipt, repository, parent);
59
+ if ((value.receipt.correlation.kind === 'product-source') !== comment.body.includes(productMarker)) throw Error('Epic journal marker responsibility mismatch');
49
60
  return value;
50
61
  }
51
62
 
@@ -54,7 +65,7 @@ export async function readEpicResourceReceipt({ api, repository, owner, correlat
54
65
  if (!isDeepStrictEqual(correlation, epicCorrelation(correlation)) || correlation.repository !== repository || !sha(sourceRevision) || !defaultBranch || resource && (!positive(resource.id) || !positive(resource.number)) || !Array.isArray(allowedStates) || !allowedStates.length || allowedStates.some(state => !['linked', 'accepted'].includes(state))) throw Error('Invalid epic resource admission');
55
66
  const parent = correlation.parent, key = keyFor(correlation);
56
67
  const comments = await issueComments(api, parent);
57
- const candidates = comments.filter(c => c.user?.login === 'github-actions[bot]' && c.user.type === 'Bot' && c.body?.includes(marker)).map(c => ({ comment: c, entry: parseEntry(c, repository, parent) })).filter(item => item.entry.key === key);
68
+ const candidates = comments.filter(c => c.user?.login === 'github-actions[bot]' && c.user.type === 'Bot' && journalComment(c)).map(c => ({ comment: c, entry: parseEntry(c, repository, parent) })).filter(item => item.entry.key === key);
58
69
  if (candidates.length !== 1) throw Error('Epic resource journal is missing or ambiguous');
59
70
  const { comment, entry } = candidates[0], receipt = entry.receipt;
60
71
  if (entry.revision !== sourceRevision || !allowedStates.includes(receipt.state) || !isDeepStrictEqual(receipt.correlation, correlation) || resource && !isDeepStrictEqual(receipt.resource, resource)) throw Error('Epic resource receipt does not match the current identity');
@@ -74,7 +85,7 @@ export async function readEpicAggregateReceipt(input) {
74
85
  if (input.correlation?.kind !== 'aggregate' || !input.resource) throw Error('Invalid epic aggregate admission');
75
86
  const { api, repository, correlation } = input;
76
87
  const comments = await issueComments(api, correlation.parent);
77
- const matches = comments.filter(c => c.user?.login === 'github-actions[bot]' && c.user.type === 'Bot' && c.body?.includes(marker)).map(c => parseEntry(c, repository, correlation.parent)).filter(entry => entry.key === keyFor(correlation));
88
+ const matches = comments.filter(c => c.user?.login === 'github-actions[bot]' && c.user.type === 'Bot' && journalComment(c)).map(c => parseEntry(c, repository, correlation.parent)).filter(entry => entry.key === keyFor(correlation));
78
89
  if (matches.length !== 1) throw Error('Epic aggregate journal is missing or ambiguous');
79
90
  const sourceRevision = matches[0].revision;
80
91
  const receipt = await readEpicResourceReceipt({ ...input, sourceRevision });
@@ -92,7 +103,7 @@ export async function createEpicJournal({ api, repository, owner, parent, source
92
103
  await save();
93
104
  async function readReceipt(key) {
94
105
  const comments = await issueComments(api, parent);
95
- const candidates = comments.filter(c => c.user?.login === 'github-actions[bot]' && c.user.type === 'Bot' && c.body?.includes(marker)).map(c => ({ comment: c, entry: parseEntry(c, repository, parent) })).filter(item => item.entry.key === key);
106
+ const candidates = comments.filter(c => c.user?.login === 'github-actions[bot]' && c.user.type === 'Bot' && journalComment(c)).map(c => ({ comment: c, entry: parseEntry(c, repository, parent) })).filter(item => item.entry.key === key);
96
107
  if (candidates.length > 1) throw Error('Duplicate epic journal receipts');
97
108
  if (!candidates.length) { loaded.set(key, null); return null; }
98
109
  const { comment, entry } = candidates[0];
@@ -121,10 +132,11 @@ export async function createEpicJournal({ api, repository, owner, parent, source
121
132
  const { commit: previousCommit, ...prior } = previous.receipt.merge;
122
133
  if (!isDeepStrictEqual(identity, prior) || previousCommit && previousCommit !== receipt.merge?.commit || !isDeepStrictEqual(previous.receipt.publication, receipt.publication)) throw Error('Epic merge identity changed');
123
134
  }
135
+ if (previous?.receipt.product && !isDeepStrictEqual(previous.receipt.product, receipt.product)) throw Error('Epic product source identity changed');
124
136
  if (!previous && receipt.state !== 'intent') throw Error('Epic journal must start with intent');
125
137
  if (await authorize() !== true) throw Error('Epic journal authorization changed');
126
138
  const entry = { schemaVersion: 1, repository, parent, revision: sourceRevision, ...workflow, runId: String(run.id), attempt: run.run_attempt, key, receipt };
127
- const body = `${marker}${JSON.stringify(entry).replaceAll('<', '\\u003c').replaceAll('>', '\\u003e')} -->`;
139
+ const body = `${receipt.correlation.kind === 'product-source' ? productMarker : marker}${JSON.stringify(entry).replaceAll('<', '\\u003c').replaceAll('>', '\\u003e')} -->`;
128
140
  const comment = previous ? await api(`issues/comments/${previous.comment.id}`, 'PATCH', { body }) : await api(`issues/${parent}/comments`, 'POST', { body });
129
141
  if (!isDeepStrictEqual(parseEntry(comment, repository, parent), entry)) throw Error('Epic journal write could not be confirmed');
130
142
  journal.entries[key] = { commentId: comment.id, receipt };
@@ -21,6 +21,7 @@ import { observeEpicMerge, mergeEpicChild } from './epic-merge.mjs';
21
21
  import { setPullRequestDraft, projectImplementationPrState } from './pr-state.mjs';
22
22
  import { ensureEpicChecks } from './epic-checks.mjs';
23
23
  import { githubAppCiTrigger } from './github-app-ci.mjs';
24
+ import { adoptEpicProductSource, loadEpicProductSource } from './epic-product-source.mjs';
24
25
 
25
26
  const isOwnerAnswer = (comment, owner) => comment.user?.login === owner && !comment.body?.includes('<!-- lighthouse-run:') && !comment.body?.includes('<!-- lighthouse-actions:');
26
27
  const paused = issue => issue.state !== 'open' || issue.pull_request || issue.labels.some(label => ['future', 'human-working', 'agent-working', 'needs-info', 'waiting-review', 'execution-failed', 'triage', 'refine', 'propose', 'implement'].includes(label.name));
@@ -177,10 +178,12 @@ async function inspectEpicPublication({ api, repository, owner, child, runId, lo
177
178
  const actual = await api(`pulls/${snapshot.implementationReview.number}`);
178
179
  published = { number: actual.number, head: actual.head?.sha };
179
180
  }
180
- if (snapshot?.issue !== child || snapshot.stage !== 'implement' || snapshot.runId !== digest(`${repository}:${child}:implement:${run.id}:1`) || String(snapshot.workflowRunId) !== String(run.id) || snapshot.epic?.parent !== current.parent || snapshot.epic?.slice !== current.slice || snapshot.epic?.planDigest !== current.planDigest || snapshot.epic?.base !== current.base || snapshot.epic?.sourceRevision !== current.sourceRevision || snapshot.baseRevision !== current.sourceRevision || (snapshot.implementationReview ? snapshot.implementationReview.head !== snapshot.sourceRevision || snapshot.implementationReview.base !== current.base || run.path !== '.github/workflows/lighthouse-sdlc-apply-review.lock.yml' : snapshot.epic?.baseSha !== snapshot.sourceRevision || run.path !== '.github/workflows/lighthouse-sdlc-implement.lock.yml') || validateStageEnvelope(envelope, snapshot).length || envelope.result.status !== 'passed') throw Error('Epic implementation evidence is invalid or stale');
181
+ if (snapshot?.issue !== child || snapshot.stage !== 'implement' || snapshot.runId !== digest(`${repository}:${child}:implement:${run.id}:1`) || String(snapshot.workflowRunId) !== String(run.id) || snapshot.epic?.parent !== current.parent || snapshot.epic?.slice !== current.slice || snapshot.epic?.planDigest !== current.planDigest || snapshot.epic?.base !== current.base || snapshot.epic?.sourceRevision !== current.sourceRevision || snapshot.baseRevision !== current.sourceRevision || (snapshot.implementationReview ? snapshot.implementationReview.head !== snapshot.sourceRevision || snapshot.implementationReview.base !== current.base || run.path !== '.github/workflows/lighthouse-sdlc-apply-review.lock.yml' : (snapshot.epicProduct?.head ?? snapshot.epic?.baseSha) !== snapshot.sourceRevision || run.path !== '.github/workflows/lighthouse-sdlc-implement.lock.yml') || validateStageEnvelope(envelope, snapshot).length || envelope.result.status !== 'passed') throw Error('Epic implementation evidence is invalid or stale');
181
182
  const dispatch = await loadDispatch(api, repository, owner, child, snapshot.dispatch?.commentId, run, readArtifact);
182
183
  const { baseSha: dispatchedBase, ...dispatchedEpic } = dispatch.request.epic ?? {};
183
184
  if (dispatch.request.id !== snapshot.dispatch.requestId || dispatch.receipt.digest !== snapshot.dispatch.digest || dispatch.request.stage !== 'implement' || dispatch.request.workflowRevision !== snapshot.workflowRevision || dispatch.request.taskDigest !== snapshot.taskDigest || dispatchedBase !== snapshot.epic.baseSha || !isDeepStrictEqual(dispatchedEpic, current) || !isDeepStrictEqual(dispatch.request.epic, snapshot.epic)) throw Error('Epic implementation dispatch changed');
185
+ const product = await loadEpicProductSource({ api, repository, owner, child, current, readArtifact });
186
+ if (!isDeepStrictEqual(product, snapshot.epicProduct ?? null) || !isDeepStrictEqual(dispatch.request.epicProduct, snapshot.epicProduct) || product && product.base !== snapshot.epic.baseSha) throw Error('Epic implementation product source changed');
184
187
  await checkDispatchClaim(api, repository, child, snapshot.dispatch, run.id);
185
188
  validateChanges(changes, snapshot.implementation.policy);
186
189
  if ((!changes.length && (!isVerificationOnlyCorrection(snapshot) || published?.head !== snapshot.sourceRevision)) || !validateCheckReceipt(checks, snapshot, changes) || !Number.isSafeInteger(published?.number) || published.number < 1 || !/^[a-f0-9]{40}$/.test(published.head ?? '')) throw Error('Epic implementation checks or publication receipt are invalid');
@@ -263,6 +266,7 @@ export async function readyEpicPullRequest({ api, repository, owner, parent, chi
263
266
  if (issue.labels.some(label => ['future', 'human-working', 'agent-working', 'needs-info'].includes(label.name))) throw Error('Epic child is paused or reserved');
264
267
  const dependencies = await inspectEpicDependencies({ api, repository, owner, child, current, load, loadPolicy, readArtifact });
265
268
  if (dependencies.baseSha !== base) throw Error('Epic base changed before readiness');
269
+ await loadEpicProductSource({ api, repository, owner, child, current, readArtifact });
266
270
  const pr = await api(`pulls/${number}`), target = checkImplementationPullRequest(pr, repository);
267
271
  if (target.issue !== child || target.base !== current.base || target.head !== head || pr.mergeable !== true || !/^[a-f0-9]{40}$/.test(pr.merge_commit_sha ?? '')) throw Error('Epic PR changed before readiness');
268
272
  await authenticateEpicPullRequest({ api, repository, owner, child, pr, load, readArtifact, journal });
@@ -511,14 +515,23 @@ export async function runNativeEpic({ api, repository, owner, issue, run, journa
511
515
  return reconcileEpicChildren(snapshot.plan, { repository, parent: issue, base: `lighthouse/epic-${issue}` }, host);
512
516
  }
513
517
 
514
- export async function runEpicAction({ api, repository, owner, issue, run, journalPath, authorizationPath, action, child, implementationRun, decision, readArtifact, load, loadPolicy, observeRefinement, ciTrigger, setDraft = (pr, draft) => setPullRequestDraft(process.env.GH_TOKEN, pr, draft) }) {
518
+ export async function runEpicAction({ api, repository, owner, issue, run, journalPath, authorizationPath, action, child, implementationRun, decision, productRoot, readArtifact, load, loadPolicy, observeRefinement, ciTrigger, setDraft = (pr, draft) => setPullRequestDraft(process.env.GH_TOKEN, pr, draft) }) {
515
519
  if (action === 'reconcile') return runNativeEpic({ api, repository, owner, issue, run, journalPath, readArtifact, load, loadPolicy });
516
520
  if (action === 'accept-aggregate') return acceptEpicAggregate({ api, repository, owner, issue, run, load, loadPolicy, readArtifact });
517
- if (!['refine-child', 'register-pr', 'ready-child', 'accept-child', 'publish-aggregate', 'ready-aggregate'].includes(action) || !['publish-aggregate', 'ready-aggregate'].includes(action) && (!Number.isSafeInteger(child) || child < 1)) throw Error('Invalid epic action or child');
521
+ if (!['adopt-product', 'refine-child', 'register-pr', 'ready-child', 'accept-child', 'publish-aggregate', 'ready-aggregate'].includes(action) || !['publish-aggregate', 'ready-aggregate'].includes(action) && (!Number.isSafeInteger(child) || child < 1)) throw Error('Invalid epic action or child');
518
522
  const snapshot = await prepareNativeEpic(api, repository, owner, issue, load);
519
523
  await checkEpicLeaseConfiguration(api, snapshot.sourceRevision);
520
524
  const authorize = () => authorizeNativeEpic(api, snapshot);
521
525
  const journal = await createEpicJournal({ api, repository, owner, parent: issue, sourceRevision: snapshot.sourceRevision, defaultBranch: snapshot.defaultBranch, run, path: journalPath, authorize, ...(readArtifact ? { readArtifact } : {}) });
526
+ if (action === 'adopt-product') {
527
+ const current = await authenticateEpicChild({ api, repository, owner, child, load, readArtifact });
528
+ if (current.parent !== issue) throw Error('Product adoption targets another epic');
529
+ const state = await api(`issues/${child}`);
530
+ if (state.labels.some(label => ['agent-working', 'human-working', 'future', 'needs-info'].includes(label.name))) throw Error('Product adoption child is paused or reserved');
531
+ const dependencies = await inspectEpicDependencies({ api, repository, owner, child, current, load, loadPolicy, readArtifact });
532
+ if (dependencies.baseSha !== decision?.base) throw Error('Product adoption base or dependencies changed');
533
+ return adoptEpicProductSource({ api, repository, owner, child, current, decision, root: productRoot, journal, authorize });
534
+ }
522
535
  if (action === 'refine-child') {
523
536
  if (!authorizationPath) throw Error('Epic refinement authorization artifact is required');
524
537
  const observe = observeRefinement ?? (await import('./epic-refinement.mjs')).observeEpicRefinement;
@@ -546,7 +559,9 @@ export async function runEpicAction({ api, repository, owner, issue, run, journa
546
559
  if (!isDeepStrictEqual(actual, decision) || await authorize() !== true) return false;
547
560
  const reviews = await list(api, `pulls/${decision.pr}/reviews`);
548
561
  const latest = reviews.filter(review => review.user?.login === owner && review.user.type === 'User' && ['APPROVED', 'CHANGES_REQUESTED', 'DISMISSED'].includes(review.state)).sort((a, b) => b.id - a.id)[0];
549
- return latest?.id === decision.review && latest.state === 'APPROVED' && latest.commit_id === decision.head;
562
+ if (latest?.id !== decision.review || latest.state !== 'APPROVED' || latest.commit_id !== decision.head) return false;
563
+ if (!(await api(`pulls/${decision.pr}`)).merged) await loadEpicProductSource({ api, repository, owner, child, current, readArtifact });
564
+ return true;
550
565
  };
551
566
  const observe = () => observeEpicMerge(api, { repository, owner, child, epic: current, decision }, {
552
567
  authenticateChild: () => authenticateEpicChild({ api, repository, owner, child, load, readArtifact }),
@@ -576,7 +591,8 @@ async function main() {
576
591
  const inputs = JSON.parse(await readFile(env.GITHUB_EVENT_PATH, 'utf8')).inputs ?? {};
577
592
  const positive = value => /^[1-9][0-9]*$/.test(value ?? '') && Number.isSafeInteger(Number(value));
578
593
  const action = inputs.action || 'reconcile';
579
- if (['refine-child', 'register-pr', 'ready-child', 'accept-child'].includes(action) && !positive(inputs.child) || action === 'register-pr' && !positive(inputs.run) || ['ready-child', 'accept-child'].includes(action) && !positive(inputs['pull-request']) || action === 'accept-child' && !positive(inputs.review)) throw Error('Epic action inputs must use canonical positive numbers');
594
+ if (['adopt-product', 'refine-child', 'register-pr', 'ready-child', 'accept-child'].includes(action) && !positive(inputs.child) || action === 'register-pr' && !positive(inputs.run) || ['ready-child', 'accept-child'].includes(action) && !positive(inputs['pull-request']) || action === 'accept-child' && !positive(inputs.review)) throw Error('Epic action inputs must use canonical positive numbers');
595
+ if (action === 'adopt-product' && (!positive(inputs['pull-request']) || !positive(inputs['product-approval']))) throw Error('Product adoption needs canonical PR and approval comment IDs');
580
596
  let result;
581
597
  if (action === 'recover-publication') {
582
598
  if (!positive(inputs.child) || !positive(inputs.run) || !positive(inputs['pull-request']) || run.actor?.login !== owner || run.triggering_actor?.login !== owner || run.path !== '.github/workflows/lighthouse-sdlc-epic.yml' || run.event !== 'workflow_dispatch' || run.status !== 'in_progress' || run.repository?.full_name !== repository || run.head_sha !== env.GITHUB_SHA) throw Error('Partial publication recovery requires an authenticated owner workflow');
@@ -584,7 +600,7 @@ async function main() {
584
600
  if (current.parent !== issue) throw Error('Partial publication recovery targets another parent');
585
601
  await checkEpicLeaseConfiguration(api, current.sourceRevision);
586
602
  result = await recoverEpicCorrection({ api, repository, owner, child: Number(inputs.child), runId: inputs.run, number: Number(inputs['pull-request']), head: inputs.head, base: inputs.base, save: value => writeFile(join(dir, 'recovery.json'), JSON.stringify({ ...value, recoveryRun: String(run.id), workflowRevision: run.head_sha })) });
587
- } else result = await runEpicAction({ api, repository, owner, issue, run, ciTrigger: githubAppCiTrigger(env), journalPath: join(dir, 'journal.json'), authorizationPath: join(dir, 'refinement.json'), action, ...(inputs.child ? { child: Number(inputs.child) } : {}), ...(inputs.run ? { implementationRun: inputs.run } : {}), ...(['ready-child', 'accept-child'].includes(action) ? { decision: { pr: Number(inputs['pull-request']), ...(action === 'accept-child' ? { review: Number(inputs.review) } : {}), head: inputs.head, base: inputs.base } } : {}) });
603
+ } else result = await runEpicAction({ api, repository, owner, issue, run, ciTrigger: githubAppCiTrigger(env), journalPath: join(dir, 'journal.json'), authorizationPath: join(dir, 'refinement.json'), action, ...(inputs.child ? { child: Number(inputs.child) } : {}), ...(inputs.run ? { implementationRun: inputs.run } : {}), ...(action === 'adopt-product' ? { productRoot: join(env.GITHUB_WORKSPACE, '.lighthouse-product-source'), decision: { pr: Number(inputs['pull-request']), approval: Number(inputs['product-approval']), changeName: inputs['product-change'], head: inputs.head, base: inputs.base } } : {}), ...(['ready-child', 'accept-child'].includes(action) ? { decision: { pr: Number(inputs['pull-request']), ...(action === 'accept-child' ? { review: Number(inputs.review) } : {}), head: inputs.head, base: inputs.base } } : {}) });
588
604
  await writeFile(join(dir, 'result.json'), JSON.stringify({ schemaVersion: 1, repository, parent: issue, runId: String(run.id), attempt: run.run_attempt, workflowRevision: run.head_sha, workflowRef: run.head_branch, action, result }));
589
605
  console.log(JSON.stringify(result));
590
606
  if (!['authorized', 'reconciled', 'linked', 'ready', 'accepted', 'published'].includes(result.status)) throw Error('Epic action stopped; inspect the retained journal before continuing');