@juangcarmona/lighthouse-sdlc 0.25.0 → 0.25.2

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/issue-control.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # Issue-control SDK
2
2
 
3
- The `./issue-control` export supplies `createIssueControl`, `parseIssueComment`, `parseIssueIntent` and `validateIssueIntent`. The [intent schema](schemas/issue-control-intent.schema.json) describes version 1; runtime validation also checks canonical JSON and UTF-8 byte limits. This implementation is awaiting packed-consumer and actual-user native qualification. Source availability does not establish a published or adopted release.
3
+ The `./issue-control` export supplies `createIssueControl`, `parseIssueComment`, `parseIssueIntent` and `validateIssueIntent`. The [intent schema](schemas/issue-control-intent.schema.json) describes version 1; runtime validation also checks canonical JSON and UTF-8 byte limits. The original contract was published in SDLC 0.22.0 after source-owned owner-user qualification. Current release, consumer adoption and connected App-user outcomes require their own revision-bound receipts; see [issue #119](https://github.com/juangcarmona/lighthouse/issues/119).
4
4
 
5
5
  ## Adoption
6
6
 
@@ -34,6 +34,8 @@ const reconciled = await control.reconcile(prepared);
34
34
 
35
35
  `prepare` returns either a prepared object with `version`, `intent`, `key`, `payloadDigest` and `effect`, or an explicit unavailable/rejected state. Call `submit` only for a prepared object. `observe` and `prepare` perform reads only. They report source eligibility separately from execution readiness and can become stale while a request queues; source admission rechecks current authority.
36
36
 
37
+ `observe` includes a `prerequisites` object on each Refine/Propose assessment: `installedContract`, `writeAuthority`, `repositoryPolicy`, `sourceReservations` and `stageEvidence`. Each reports `availability` and an optional reason. A check skipped after an earlier unmet prerequisite stays unavailable with `earlier-prerequisite-not-met`. Valid direct owner entry reports `owner-direct-entry`; it does not claim triage evidence. These observations add no reservation or execution authority.
38
+
37
39
  The transport receives `{scope, repository?, path, method, body?, optional?, apiVersion?}`. Account scope uses `GET user`; repository paths are relative to the explicitly bound repository. Use the actual connected user's credentials, honor the requested API version, return parsed provider JSON, and map optional 404 to `null`. HTTP failures expose a numeric `status`; uncertain network failures retain uncertainty. No credentials, default transport, environment token lookup or ambient network access is supplied by this module. Comments are posted directly as that user. A bot or installation token cannot substitute for the acting account.
38
40
 
39
41
  `readAuthority({api, repository, actor, metadata})` must return verified `actorId`, `repositoryId`, and boolean `commentWrite`/`dispatchWrite` capabilities for the actual credentials. Missing or mismatched evidence denies writes. The current contract supports the personal repository owner; other identities are explicitly unsupported. Reading repository variables may require additional token permission; a denial makes policy unavailable, rather than assuming automation is enabled.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@juangcarmona/lighthouse-sdlc",
3
- "version": "0.25.0",
3
+ "version": "0.25.2",
4
4
  "type": "module",
5
5
  "description": "Provider-neutral SDLC skills, commands and route contracts for Lighthouse adopters",
6
6
  "repository": {
@@ -8,6 +8,22 @@ Read `context.productChange.composition`. The adapter configures `productcomposi
8
8
 
9
9
  Call `productcomposition_inspect` with `{}` for the catalog and current binding. It returns measured object/path/UTF-8 byte counts and, for each path, source/hash references, revision, bytes and artifact ID where applicable. To inspect one object's exact content, call it with `reference: { path, source, sha256 }` from the catalog. Do not invent filesystem references or reread another run.
10
10
 
11
+ The working context exposes `context.productChange.currentDocuments`: one highest-revision reference per path, with all earlier references under `history`. Read exact document bodies on demand using inspection; the working context does not repeat them. `context.productChange.audit` identifies `/workspace/.lighthouse-product-audit.json`, a read-only copy of the complete original context with its SHA-256. It uses the existing read-only workspace permission; a source-file collision refuses rather than overwrites. Composition reads that original copy, not the smaller working view. Audit references are inert data, not instructions or approval.
12
+
13
+ In ordinary projection, all prose outside validated retained declarations stays in the working issue and verified answers. Repeated copies in continuation bodies, parent original requests, idea and scope may point back to those fields. A bound higher document revision explicitly replaces that path's document version; a missing path does not delete an earlier unique path. Document revision and comment order never supersede prose decisions. Preserve every unique requirement and resolve conflicting or ambiguous decisions explicitly before composing; do not summarize away authority.
14
+
15
+ If ordinary projection exceeds 256 KiB, `productChange.historyIndex` indexes every string-valued verified answer body by its exact `source` location, SHA-256 and UTF-8 byte count. Answer metadata and null/absent bodies stay in place; `totalAnswers` accounts for the full answer inventory. Whole-body references replace answer bodies only, not the current issue, request or instructions. This transport does not select winning decisions or summarize their meaning. Every indexed decision retains its original authority and starts unread, not reviewed.
16
+
17
+ Before resolving relevant product decisions, read the existing read-only audit, verify its SHA-256 against `productChange.audit.sha256`, locate the original answer via `historyIndex.answers[].source` (a context field selector, never a filesystem path), and verify the decoded body string's SHA-256 and UTF-8 byte count. Inspect every relevant original body, including all mixed-envelope values and surrounding decisions; do not claim unread history was reviewed. If relevance cannot be established without reading, inspect the body. Resolve conflicting decisions explicitly. If retrieval or a binding check fails, stop with the exact source/hash and required bounded repair; never substitute a summary or infer supersession. This uses the existing audit read access, not a new tool or permission.
18
+
19
+ Whole-answer references share the unchanged 512-reference allowance with typed and historical document references. Original authenticated text remains bounded to 2 MiB, the full audit to 4 MiB and the final working view to 256 KiB. An irreducible current issue/instruction payload or exhausted reference allowance still refuses; preserve the originals and request a bounded current payload without rewriting history. Fitting ordinary views do not activate whole-answer transport.
20
+
21
+ Historical documents can also become references bound to their exact source and content hash in the original authenticated audit. Supported forms are a `json` fence with a `files` array, with each file carrying `path`, `content`, optional `sha256` and optional `mode`; or a level-three Markdown heading containing only an allowed path in inline code, followed immediately by a three-backtick fence labelled `markdown`, `md`, `yaml`, `yml`, `json`, `text` or unlabelled. Mixed JSON envelopes keep every non-file value in place, including provenance, status and obligations; those values do not become current binding or approval evidence. Unrelated prose and JSON are not document bindings.
22
+
23
+ The working view records `productChange.historicalCopies` with exact audit source locations, file indices and raw content hashes. Exact aliases also link validated retained sources; inspect those sources for retained bodies. Older distinct texts or unique safe paths have `historicalOnly: true` and no retained sources: retrieve them only from the read-only audit using `audit.source` and `audit.fileIndex`, verifying `audit.sha256`. For JSON, hash the decoded `content` string; for Markdown, hash the captured fenced body, including its final newline. A Markdown alias can exclude a structural newline only when exactly one retained identity matches; multiple matches refuse, and CRLF is never normalized. For unmatched Markdown the top-level hash identifies the exact captured body, not a guessed original file ending.
24
+
25
+ Historical references grant no revision, supersession, omission, composition or approval authority. Historical-only documents require the existing explicit typed admission before composition. The eight-declaration allowance applies only to typed retained inputs, not aliases; every historical file still consumes one of the existing 512 references. All Markdown copies in one source body form one file inventory, with no duplicate paths. Unsafe paths/content/modes, changed supplied hashes, duplicate keys/paths, fabricated source bindings and ambiguous retained-byte recovery refuse. Preserve the originals and report the exact source/hash and required bounded repair instead of dropping prose or guessing a revision. Without a validated catalog, ordinary literal drafting stays unchanged.
26
+
11
27
  Supported inputs are the host-supplied `context.productChange.files` array and tagged JSON fences in `context.issue.body` or verified `context.issue.ownerAnswers[].body`. The host identifies these sources by their field location. A tagged document has exactly these fields:
12
28
 
13
29
  ```json
@@ -32,7 +48,7 @@ Supported inputs are the host-supplied `context.productChange.files` array and t
32
48
 
33
49
  This is a shape example, not a valid bound input. A file can also carry an existing regular mode (`100644` or `100755`). Provider artifact IDs must be unambiguous plain `id: UPPERCASE-ID` fields in Markdown frontmatter or YAML, or a JSON `id` string. Unsupported forms require ordinary literal drafting or a truthful blocker, not guessed conversion. The trusted provider still owns full artifact and manifest validation.
34
50
 
35
- Split large drafts across admitted documents rather than enlarging a prompt. At most eight documents, 64 files per document, 128 retained objects and 512 KiB of retained content are admitted. The final candidate remains at most 64 files, 64 KiB per file and 512 KiB total. Issue and answer text together are bounded to 2 MiB. A revision is a positive integer; an existing host candidate has revision zero. Multiple objects for the same path at the same revision are ambiguous and rejected.
51
+ Split large drafts across admitted documents rather than enlarging a prompt. At most eight documents, 64 files per document, 128 distinct retained path/content/mode objects and 512 KiB of distinct retained content are admitted. Repeated exact objects consume storage once, but every source/revision reference remains explicit, bounded to 512 references. The final candidate remains at most 64 files, 64 KiB per file and 512 KiB total. Issue and answer text together are bounded to 2 MiB. A revision is a positive integer; an existing host candidate has revision zero. Multiple objects for the same path at the same revision are ambiguous and rejected.
36
52
 
37
53
  ## Select and compose
38
54
 
@@ -89,6 +89,9 @@ export function continuationContext(continuation, answer) {
89
89
  const question = pendingQuestion(continuation.envelope.result.output?.handoff?.question ?? continuation.envelope.result.output?.productChange?.question);
90
90
  return { ...(question ? { question } : {}), answer: { body: answer.body, url: answer.html_url }, priorRunId: continuation.request.runId };
91
91
  }
92
+ export async function prepareProductContextEvidence(root, destination, context, core, { baselineDigest, parentEvidence } = {}) {
93
+ return prepareProductEvidence(root, destination, core, { baselineDigest, scopeText: productEvidenceScopeText({ issue: context.issue, parentEvidence }) });
94
+ }
92
95
  export function continuationHistory(continuation, answer) {
93
96
  const prior = continuation.request.answerHistory ?? [];
94
97
  if (!Array.isArray(prior) || prior.length > 16 || prior.some(item => typeof item?.question !== 'string' || typeof item.answer?.body !== 'string' || typeof item.answer?.url !== 'string' || typeof item.priorRunId !== 'string')) throw Error('Invalid retained question and answer history');
@@ -647,7 +650,7 @@ async function main(command) {
647
650
  if (Buffer.byteLength(JSON.stringify(parentEvidence)) > 128000) throw Error('Parent evidence exceeds the bounded product context');
648
651
  }
649
652
  const productChange = await prepareProductChange(process.cwd(), productChangeName, existingFiles, bridge);
650
- const productEvidence = await prepareProductEvidence(process.cwd(), join(dir, 'product-evidence'), await loadProductCore(), { baselineDigest, scopeText: productEvidenceScopeText({ issue: context.issue, parentEvidence }) });
653
+ const productEvidence = await prepareProductContextEvidence(process.cwd(), join(dir, 'product-evidence'), context, await loadProductCore(), { baselineDigest, parentEvidence });
651
654
  context.request.worker = 'product-change';
652
655
  context.authorization = { status: 'verified', verifiedBy: 'GitHub Actions workflow', authorizedStage: stage, owner, entry: snapshot.productEntry, event: env.GITHUB_EVENT_NAME };
653
656
  context.productChange = { ...productChange, baselineDigest, acceptedModelPath: `/workspace/${await productModelDirectory(process.cwd())}`, evidenceRoot: '/workspace/.lighthouse-product-evidence', idea: `${issue.title}\n\n${issue.body ?? ''}`, scope: issue.body ?? issue.title, ...(dispatch.request.productFeedback ? { feedback: dispatch.request.productFeedback } : {}), ...(productReview ? { review: productReview } : {}), parent: { issue: issueNumber, stage, authorizationDigest, policyDigest, sourceRevision: revision.sha, ...(snapshot.productParent ? { prerequisite: snapshot.productParent, evidence: parentEvidence } : {}) } };
@@ -82,7 +82,9 @@ export async function collectIssueControlFacts({ api, repository, number, actor,
82
82
  if (supported) try { reservation = await reservations(read, repository, metadata.owner.login, issue, comments, capability, readArtifact); }
83
83
  catch { reservation = { availability: 'unavailable', reason: 'reservation-evidence-unavailable', active: [] }; }
84
84
  const actions = { comment: supported ? writeAllowed('commentWrite') ?? { eligible: true, availability: 'available' } : refusal('installed-contract-unsupported', 'unsupported') };
85
+ const stageEvidence = {};
85
86
  for (const stage of ['refine', 'propose']) {
87
+ stageEvidence[stage] = { availability: 'unavailable', reason: 'earlier-prerequisite-not-met' };
86
88
  if (!supported || !capability.stages.includes(stage)) { actions[stage] = refusal('stage-contract-unsupported', 'unsupported'); continue; }
87
89
  if (writeAllowed('dispatchWrite')) { actions[stage] = writeAllowed('dispatchWrite'); continue; }
88
90
  if (!policyKnown) { actions[stage] = unavailable('policy-unavailable'); continue; }
@@ -93,12 +95,32 @@ export async function collectIssueControlFacts({ api, repository, number, actor,
93
95
  if (reservation.availability !== 'available') { actions[stage] = unavailable(reservation.reason); continue; }
94
96
  if (reservation.active.length) { actions[stage] = refusal('authenticated-source-reservation'); continue; }
95
97
  try {
98
+ let triage;
96
99
  if (stage === 'refine' || issue.user.login !== metadata.owner.login)
97
- await collectTriageAdmission({ api: read, repository, owner: metadata.owner.login, issue, comments, sourceRevision, readArtifact });
100
+ triage = await collectTriageAdmission({ api: read, repository, owner: metadata.owner.login, issue, comments, sourceRevision, readArtifact });
98
101
  if (stage === 'propose') await collectProposalAdmission({ api: read, repository, owner: metadata.owner.login, issue, comments, sourceRevision, taskDigest: inputDigest, readArtifact });
102
+ stageEvidence[stage] = { availability: 'available', reason: stage === 'propose' ? 'validated-refinement'
103
+ : triage ? 'validated-triage' : 'owner-direct-entry' };
99
104
  actions[stage] = { eligible: true, availability: 'available' };
100
- } catch (error) { actions[stage] = error instanceof IssueAdmissionRefusal ? { ...refusal(error.reason, error.availability), message: error.message }
101
- : unavailable(stage === 'refine' ? 'triage-not-verified' : 'proposal-prerequisites-not-verified'); }
105
+ } catch (error) {
106
+ actions[stage] = error instanceof IssueAdmissionRefusal ? { ...refusal(error.reason, error.availability), message: error.message }
107
+ : unavailable(stage === 'refine' ? 'triage-not-verified' : 'proposal-prerequisites-not-verified');
108
+ stageEvidence[stage] = { availability: actions[stage].availability, reason: actions[stage].reason };
109
+ }
110
+ }
111
+ for (const stage of ['refine', 'propose']) {
112
+ const authorityRefusal = writeAllowed('dispatchWrite');
113
+ actions[stage].prerequisites = {
114
+ installedContract: supported && capability.stages.includes(stage) ? { availability: 'available' }
115
+ : { availability: 'unsupported', reason: 'stage-contract-unsupported' },
116
+ writeAuthority: authorityRefusal ? { availability: authorityRefusal.availability, reason: authorityRefusal.reason } : { availability: 'available' },
117
+ repositoryPolicy: !policyKnown ? { availability: 'unavailable', reason: 'policy-unavailable' }
118
+ : !policy.automationEnabled ? { availability: 'denied', reason: 'automation-disabled' }
119
+ : policy.epicEnabled ? { availability: 'unsupported', reason: 'epic-admission-contract-unsupported' } : { availability: 'available' },
120
+ sourceReservations: reservation.availability !== 'available' ? { availability: reservation.availability, reason: reservation.reason }
121
+ : reservation.active.length ? { availability: 'denied', reason: 'authenticated-source-reservation' } : { availability: 'available' },
122
+ stageEvidence: stageEvidence[stage]
123
+ };
102
124
  }
103
125
  let question = { availability: 'none' };
104
126
  const pending = pendingStage(comments);
@@ -29,6 +29,21 @@ import { createTelemetry, telemetryContext, readTelemetry } from './telemetry.mj
29
29
  import { observeCli, collectNativeFile, usageSummary } from './telemetry-opencode.mjs';
30
30
  import { configureProductCompositionWorker } from './product-composition-runtime.mjs';
31
31
  import { engineResultByteLimit } from './engine-result-limits.mjs';
32
+ import { productWorkingContext } from './product-context.mjs';
33
+ import { parseCompositionJson } from './product-composition.mjs';
34
+
35
+ export async function prepareProductWorkingContext(contextPath, auditPath, capability) {
36
+ const raw = await readFile(contextPath, 'utf8');
37
+ if (Buffer.byteLength(raw) > 4 * 1024 * 1024) throw Error('Product audit context exceeds bounds');
38
+ const original = parseCompositionJson(raw), auditSha256 = createHash('sha256').update(raw).digest('hex');
39
+ const working = productWorkingContext(original, auditSha256, capability);
40
+ const serialized = JSON.stringify(working);
41
+ if (Buffer.byteLength(serialized) > 256 * 1024) throw Error('Product working context exceeds bounds');
42
+ await writeFile(auditPath, raw, { flag: 'wx', mode: 0o444 });
43
+ await writeFile(contextPath, serialized);
44
+ // The adapter still adds its execution budget before its existing final chmod.
45
+ return { auditSha256, originalBytes: Buffer.byteLength(raw), workingBytes: Buffer.byteLength(serialized), retained: working.productChange.currentDocuments?.measured ?? null };
46
+ }
32
47
 
33
48
  export function completionOutput(envelope, request) {
34
49
  const errors = validateStageEnvelope(envelope, request);
@@ -261,10 +276,7 @@ async function main() {
261
276
  } catch {
262
277
  capability = { status: 'unavailable', reason: 'Pinned planning image does not support the composition configuration. Workflow maintainer: update the package/workflow pin and qualify local MCP on the pinned image; do not broaden planning permissions.' };
263
278
  }
264
- const compositionContext = JSON.parse(await readFile(context, 'utf8'));
265
- compositionContext.productChange ??= {};
266
- compositionContext.productChange.composition = capability;
267
- await writeFile(context, JSON.stringify(compositionContext));
279
+ runtimeReceipt.productContext = await prepareProductWorkingContext(context, join(source, '.lighthouse-product-audit.json'), capability);
268
280
  runtimeReceipt.productComposition = capability;
269
281
  }
270
282
  if (telemetry.health().status !== 'disabled') {
@@ -294,6 +306,11 @@ async function main() {
294
306
  runtimeReceipt.budget = budget;
295
307
  const executionContext = JSON.parse(await readFile(context, 'utf8'));
296
308
  executionContext.executionBudget = budget;
309
+ if (request.worker === 'product-change') {
310
+ const bytes = Buffer.byteLength(JSON.stringify(executionContext));
311
+ if (bytes > 256 * 1024) throw Error('Product working context exceeds bounds after host metadata');
312
+ runtimeReceipt.productContext.workingBytes = bytes;
313
+ }
297
314
  await writeFile(context, JSON.stringify(executionContext)); await chmod(context, 0o444);
298
315
  await writeFile(join(runDir, 'runtime.json'), JSON.stringify(runtimeReceipt));
299
316
  const started = budget.startedAt;
@@ -255,9 +255,35 @@ export async function loadProductCore({ entry = require.resolve('@prodshape/core
255
255
  }
256
256
 
257
257
  export function productEvidenceScopeText(value) {
258
- if (typeof value === 'string') return value;
259
- if (value && typeof value === 'object') return Object.values(value).map(productEvidenceScopeText).join('\n');
260
- return '';
258
+ const references = new Set();
259
+ let inputBytes = 0, referenceBytes = 0, entries = 0;
260
+ const issue = record(value?.issue) ? value.issue : null;
261
+ if (issue) {
262
+ if (issue.ownerAnswers !== undefined && (!Array.isArray(issue.ownerAnswers) || issue.ownerAnswers.length > 100)) throw Error('ProductShape evidence answer inventory exceeds bounds');
263
+ let authenticatedBytes = 0;
264
+ for (const body of [issue.body, ...(issue.ownerAnswers ?? []).map(answer => answer?.body)]) {
265
+ if (body === undefined || body === null) continue;
266
+ if (typeof body !== 'string' || (authenticatedBytes += Buffer.byteLength(body)) > 2 * 1024 * 1024) throw Error('ProductShape authenticated input text exceeds bounds');
267
+ }
268
+ }
269
+ // Host metadata and repeated continuation copies are not additional issue text.
270
+ // The complete projection input still fits the existing audit transport bound.
271
+ const inputLimit = (issue ? 4 : 2) * 1024 * 1024;
272
+ function visit(item, depth) {
273
+ if (depth > 64 || ++entries > 100000) throw Error('ProductShape evidence input nesting or inventory exceeds bounds');
274
+ if (typeof item === 'string') {
275
+ if ((inputBytes += Buffer.byteLength(item)) > inputLimit) throw Error('ProductShape evidence input text exceeds bounds');
276
+ for (const [id] of item.matchAll(/\b[A-Z][A-Z0-9]*(?:-[A-Z0-9]+)+\b/g)) {
277
+ if (references.has(id)) continue;
278
+ if ((referenceBytes += Buffer.byteLength(id) + (references.size ? 1 : 0)) > 256 * 1024) throw Error('ProductShape evidence reference selection exceeds bounds');
279
+ references.add(id);
280
+ }
281
+ } else if (item && typeof item === 'object') {
282
+ for (const child of Object.values(item)) visit(child, depth + 1);
283
+ }
284
+ }
285
+ visit(value, 0);
286
+ return [...references].join('\n');
261
287
  }
262
288
 
263
289
  export async function prepareProductEvidence(root, destination, core, { baselineDigest, scopeText } = {}) {
@@ -103,6 +103,6 @@ export async function runCompositionServer(input = process.stdin, output = proce
103
103
  }
104
104
 
105
105
  if (process.argv[1] === fileURLToPath(import.meta.url)) {
106
- try { await runCompositionServer(); }
106
+ try { await runCompositionServer(process.stdin, process.stdout, compositionService('/workspace/.lighthouse-product-audit.json')); }
107
107
  catch { process.stderr.write('Product composition unavailable; preserve prior output and report a technical blocker.\n'); process.exitCode = 1; }
108
108
  }
@@ -41,6 +41,36 @@ export function compositionBinding(context) {
41
41
  return { runId: request.runId, taskDigest: request.taskDigest, sourceRevision: request.sourceRevision, baselineDigest: request.baselineDigest, changeName: product.changeName, schemaPinSha256: hash(product.schemaPin) };
42
42
  }
43
43
 
44
+ // Locations are audit selectors, never filesystem paths or composition admission.
45
+ export const historicalMarkdown = /^### `([^`\r\n]+)`[ \t]*\r?\n```(?:markdown|md|yaml|yml|json|text)?[ \t]*\r?\n([\s\S]*?)^```[ \t]*\r?$/gm;
46
+
47
+ export function historicalFilesSpan(raw) {
48
+ let depth = 0, start;
49
+ const tokens = [...raw.matchAll(/"(?:[^"\\]|\\[\s\S])*"|[{}\[\]:,]/g)];
50
+ for (let i = 0; i < tokens.length; i++) {
51
+ const token = tokens[i][0];
52
+ if (depth === 1 && token.startsWith('"') && JSON.parse(token) === 'files' && tokens[i + 1]?.[0] === ':' && tokens[i + 2]?.[0] === '[') start = tokens[i + 2].index;
53
+ if (token === '{' || token === '[') depth++;
54
+ else if (token === '}' || token === ']') {
55
+ depth--;
56
+ if (start !== undefined && depth === 1) return { start, end: tokens[i].index + 1 };
57
+ }
58
+ }
59
+ throw Error('Invalid historical files field');
60
+ }
61
+
62
+ function validateRetainedFile(context, binding, file) {
63
+ const prefix = `openspec/changes/${binding.changeName}/`;
64
+ const scaffolding = [
65
+ { path: `${prefix}.openspec.yaml`, content: context.productChange.schemaPin },
66
+ { path: `${prefix}product-change/change.md`, content: '---\nid: CHG-COMPOSITION-CHECK\nstatus: draft\n---\n' },
67
+ { path: `${prefix}product-change/proposed/composition-check.md`, content: 'Text' },
68
+ ];
69
+ const candidateFile = { path: file.path, content: file.content, ...(file.mode !== undefined ? { mode: file.mode } : {}) };
70
+ validateProductChangeFiles([...scaffolding.filter(item => item.path !== file.path), candidateFile], { changeName: binding.changeName });
71
+ return candidateFile;
72
+ }
73
+
44
74
  function artifactId(file) {
45
75
  if (!file.path.includes('/product-change/proposed/')) return null;
46
76
  let id;
@@ -92,8 +122,8 @@ function documents(context, binding) {
92
122
  }
93
123
 
94
124
  function inventory(context) {
95
- const binding = compositionBinding(context), paths = new Map();
96
- let bytes = 0, count = 0;
125
+ const binding = compositionBinding(context), paths = new Map(), unique = new Set();
126
+ let bytes = 0, count = 0, references = 0, duplicateBytes = 0;
97
127
  for (const document of documents(context, binding)) {
98
128
  if (!Array.isArray(document.files) || !document.files.length || document.files.length > PRODUCT_FILE_LIMITS.files) throw Error('Retained file inventory exceeds bounds');
99
129
  const seen = new Set();
@@ -102,25 +132,23 @@ function inventory(context) {
102
132
  text(file.content);
103
133
  if (!hex.test(file.sha256 ?? '') || hash(file.content) !== file.sha256) throw Error('Missing or changed retained content hash');
104
134
  // Reuse the complete candidate validator for every path/type/mode, even omitted objects.
105
- const prefix = `openspec/changes/${binding.changeName}/`;
106
- const scaffolding = [
107
- { path: `${prefix}.openspec.yaml`, content: context.productChange.schemaPin },
108
- { path: `${prefix}product-change/change.md`, content: '---\nid: CHG-COMPOSITION-CHECK\nstatus: draft\n---\n' },
109
- { path: `${prefix}product-change/proposed/composition-check.md`, content: 'Text' },
110
- ];
111
- const candidateFile = { path: file.path, content: file.content, ...(file.mode !== undefined ? { mode: file.mode } : {}) };
112
- validateProductChangeFiles([...scaffolding.filter(item => item.path !== file.path), candidateFile], { changeName: binding.changeName });
135
+ const candidateFile = validateRetainedFile(context, binding, file);
113
136
  if (seen.has(file.path)) throw Error('Duplicate retained path');
114
137
  seen.add(file.path);
115
138
  const size = Buffer.byteLength(file.content);
116
- if (++count > 128 || (bytes += size) > PRODUCT_FILE_LIMITS.totalBytes) throw Error('Retained aggregate inventory exceeds bounds');
139
+ if (++references > 512) throw Error('Retained reference inventory exceeds bounds');
140
+ const identity = JSON.stringify([file.path, file.sha256, file.mode ?? '100644']);
141
+ if (!unique.has(identity)) {
142
+ unique.add(identity);
143
+ if (++count > 128 || (bytes += size) > PRODUCT_FILE_LIMITS.totalBytes) throw Error('Retained aggregate inventory exceeds bounds');
144
+ } else duplicateBytes += size;
117
145
  const objects = paths.get(file.path) ?? [];
118
146
  if (objects.some(item => item.revision === document.revision)) throw Error('Ambiguous retained path revision');
119
147
  objects.push({ ref: { source: document.source, sha256: file.sha256 }, revision: document.revision, bytes: size, id: artifactId(candidateFile), file: candidateFile });
120
148
  paths.set(file.path, objects);
121
149
  }
122
150
  }
123
- return { binding, paths, count, bytes };
151
+ return { binding, paths, count, bytes, references, duplicateBytes };
124
152
  }
125
153
 
126
154
  export function retainedInventory(context, reference) {
@@ -134,6 +162,56 @@ export function retainedInventory(context, reference) {
134
162
  return { binding: data.binding, measured: { objects: data.count, paths: data.paths.size, bytes: data.bytes }, paths: [...data.paths].map(([path, objects]) => ({ path, objects: objects.map(({ file: _file, ...item }) => item) })) };
135
163
  }
136
164
 
165
+ export function currentRetainedInventory(context) {
166
+ const data = inventory(context);
167
+ return {
168
+ binding: data.binding,
169
+ measured: { objects: data.count, paths: data.paths.size, bytes: data.bytes, references: data.references, duplicateBytes: data.duplicateBytes },
170
+ paths: [...data.paths].map(([path, objects]) => {
171
+ const current = objects.reduce((a, b) => a.revision > b.revision ? a : b);
172
+ const describe = ({ file: _file, ...item }) => item;
173
+ return { path, current: describe(current), history: objects.filter(item => item !== current).map(describe) };
174
+ }),
175
+ };
176
+ }
177
+
178
+ // Audit bindings prove historical bytes only. They never enter revision selection or composition.
179
+ export function bindRetainedCopies(context, copies) {
180
+ const data = inventory(context);
181
+ const seenInventories = new Map();
182
+ let references = data.references;
183
+ const recover = detail => Error(`Unbound or ambiguous historical document copy (${detail}); supply an explicitly bound retained draft with exact path/content/hash and revision`);
184
+ return copies.map(copy => {
185
+ const location = /^(issue\.body|issue\.ownerAnswers\[(\d+)\]\.body)#(json|markdown)-(\d+)$/.exec(copy.source);
186
+ const body = location?.[1] === 'issue.body' ? context.issue?.body : context.issue?.ownerAnswers?.[Number(location?.[2])]?.body;
187
+ if (!location || typeof body !== 'string' || Boolean(copy.markdown) !== (location[3] === 'markdown')) throw recover(`${copy.source}: missing authenticated source`);
188
+ const blocks = [...body.matchAll(copy.markdown ? historicalMarkdown : /^```json[ \t]*\r?\n([\s\S]*?)^```[ \t]*\r?$/gm)];
189
+ const block = (copy.markdown ? blocks.filter(match => match[1].startsWith(`openspec/changes/${data.binding.changeName}/`)) : blocks)[Number(location[4])];
190
+ const original = block && (copy.markdown ? [{ path: block[1], content: block[2] }] : parseCompositionJson(block[1]).files);
191
+ if (!isDeepStrictEqual(original, copy.files)) throw recover(`${copy.source}: changed source; sha256=${hash(JSON.stringify(copy.files))}`);
192
+ if (!Array.isArray(copy.files) || !copy.files.length || copy.files.length > PRODUCT_FILE_LIMITS.files) throw recover(copy.source);
193
+ const seen = seenInventories.get(copy.inventory) ?? new Set();
194
+ seenInventories.set(copy.inventory, seen);
195
+ const files = copy.files.map((file, index) => {
196
+ exact(file, ['path', 'content', ...(Object.hasOwn(file ?? {}, 'mode') ? ['mode'] : []), ...(Object.hasOwn(file ?? {}, 'sha256') ? ['sha256'] : [])], 'historical file');
197
+ try { text(file.content); validateRetainedFile(context, data.binding, file); } catch { throw recover(`${copy.source} files[${index}]: unsafe path/content/mode`); }
198
+ if (file.sha256 !== undefined && (!hex.test(file.sha256) || file.sha256 !== hash(file.content))) throw recover(`${copy.source} files[${index}]: changed hash; sha256=${hash(file.content)}`);
199
+ if (seen.has(file.path)) throw recover(`duplicate path in ${copy.source}`);
200
+ seen.add(file.path);
201
+ if (seen.size > PRODUCT_FILE_LIMITS.files) throw recover(`file inventory in ${copy.source}`);
202
+ if (++references > 512) throw Error('Retained reference inventory exceeds bounds');
203
+ const contents = copy.markdown && file.content.endsWith('\n') ? [file.content, file.content.slice(0, -1)] : [file.content];
204
+ if (copy.markdown && file.content.endsWith('\r\n')) contents.push(file.content.slice(0, -2));
205
+ const matches = (data.paths.get(file.path) ?? []).filter(item => contents.includes(item.file.content) && (item.file.mode ?? '100644') === (file.mode ?? '100644') && (file.sha256 === undefined || file.sha256 === item.ref.sha256));
206
+ if (new Set(matches.map(item => item.ref.sha256)).size > 1) throw recover(`${copy.source} files[${index}]: ambiguous retained bytes; sha256=${hash(file.content)}`);
207
+ const content = matches[0]?.file.content ?? file.content;
208
+ return { path: file.path, sha256: hash(content), sources: matches.map(item => item.ref.source), historicalOnly: !matches.length,
209
+ audit: { source: copy.source, fileIndex: index, sha256: hash(file.content), bytes: Buffer.byteLength(file.content), extraction: copy.markdown ? 'fenced-body' : 'files-content' } };
210
+ });
211
+ return { source: copy.source, files };
212
+ });
213
+ }
214
+
137
215
  export function composeRetainedProduct(context, args) {
138
216
  exact(args, ['binding', 'plan', 'envelope'], 'composition');
139
217
  const data = inventory(context);
@@ -0,0 +1,121 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { bindRetainedCopies, compositionBinding, currentRetainedInventory, historicalFilesSpan, historicalMarkdown, parseCompositionJson } from './product-composition.mjs';
3
+ import { productEvidenceScopeText } from './product-change.mjs';
4
+
5
+ const hash = value => createHash('sha256').update(value).digest('hex');
6
+ const fence = /^```json[ \t]*\r?\n([\s\S]*?)^```[ \t]*\r?$/gm;
7
+
8
+ // The original remains the authority. Literal aliases require exact retained-object binding.
9
+ export function productWorkingContext(context, auditSha256, composition) {
10
+ if (context.request?.worker !== 'product-change') throw Error('Current product context requires a Product Change worker');
11
+ if (!context.productChange || typeof context.productChange !== 'object' || Array.isArray(context.productChange)) throw Error('Current product context needs host Product Change metadata');
12
+ if (context.issue?.ownerAnswers !== undefined && !Array.isArray(context.issue.ownerAnswers)) throw Error('Unsupported retained answer inventory');
13
+ if ((context.issue?.ownerAnswers?.length ?? 0) > 100) throw Error('Retained answer inventory exceeds bounds');
14
+ if (auditSha256 !== undefined && !/^[a-f0-9]{64}$/.test(auditSha256)) throw Error('Invalid Product audit SHA-256 binding');
15
+ const sources = [{ source: 'issue.body', body: context.issue?.body }, ...(context.issue?.ownerAnswers ?? []).map((answer, i) => ({ source: `issue.ownerAnswers[${i}].body`, body: answer.body }))];
16
+ const retained = context.productChange?.files !== undefined || sources.some(({ body }) => typeof body === 'string' && body.includes('lighthouse-retained-product-draft/'));
17
+ const catalog = retained ? currentRetainedInventory(context) : null;
18
+ const projected = new Map();
19
+ const copies = [], spans = new Map();
20
+ for (const { source, body } of sources) {
21
+ if (typeof body !== 'string') continue;
22
+ const replacements = [];
23
+ if (catalog) {
24
+ let markdownIndex = 0;
25
+ for (const match of body.matchAll(historicalMarkdown)) {
26
+ // A path outside the retained change is unrelated prose, not a document route.
27
+ if (!match[1].startsWith(`openspec/changes/${catalog.binding.changeName}/`)) continue;
28
+ const reference = `${source}#markdown-${markdownIndex++}`;
29
+ copies.push({ source: reference, inventory: `${source}#markdown`, markdown: true, files: [{ path: match[1], content: match[2] }] });
30
+ replacements.push({ start: match.index, end: match.index + match[0].length, reference, heading: match[0].slice(0, match[0].indexOf('```')) });
31
+ }
32
+ }
33
+ let index = 0;
34
+ for (const match of body.matchAll(fence)) {
35
+ const [block, raw] = match;
36
+ const reference = `${source}#json-${index++}`;
37
+ if (replacements.some(span => match.index >= span.start && match.index < span.end)) continue;
38
+ if (raw.includes('lighthouse-retained-product-draft/')) {
39
+ // currentRetainedInventory validated every declaration before any projection.
40
+ replacements.push({ start: match.index, end: match.index + block.length, reference, retained: true });
41
+ } else if (catalog) {
42
+ let value;
43
+ try { value = JSON.parse(raw); } catch {
44
+ if (/^\s*\{\s*"files"\s*:/.test(raw)) throw Error('Malformed historical file inventory; supply an explicitly bound retained draft');
45
+ continue;
46
+ }
47
+ if (!value || Array.isArray(value) || !Object.hasOwn(value, 'files')) continue;
48
+ value = parseCompositionJson(raw);
49
+ const field = historicalFilesSpan(raw);
50
+ copies.push({ source: reference, inventory: reference, files: value.files });
51
+ if (Object.keys(value).length === 1) replacements.push({ start: match.index, end: match.index + block.length, reference });
52
+ else {
53
+ const offset = match.index + block.indexOf('\n') + 1;
54
+ replacements.push({ start: offset + field.start, end: offset + field.end, reference, jsonField: true });
55
+ }
56
+ }
57
+ }
58
+ spans.set(source, replacements);
59
+ }
60
+ const aliases = copies.length ? bindRetainedCopies(context, copies) : [];
61
+ for (const { source, body } of sources) {
62
+ if (typeof body !== 'string') continue;
63
+ let end = 0, value = '';
64
+ for (const span of spans.get(source).sort((a, b) => a.start - b.start)) {
65
+ const label = `[${span.retained ? 'Retained draft' : 'Exact historical copy'} ${span.reference}; inspect ${span.retained ? 'currentDocuments' : 'historicalCopies and currentDocuments'} and the read-only audit input for exact content. No decision or revision authority is implied.]`;
66
+ value += body.slice(end, span.start) + (span.heading ?? '') + (span.jsonField ? JSON.stringify(label) : label);
67
+ end = span.end;
68
+ }
69
+ projected.set(source, value + body.slice(end));
70
+ }
71
+ const copy = structuredClone(context);
72
+ // Redundant body copies in idea/scope, continuations and parent context are pointers,
73
+ // not additional decisions. All nonmatching text is preserved exactly.
74
+ const replacements = sources.filter(({ body }) => typeof body === 'string' && body.length);
75
+ const pointer = value => {
76
+ const match = replacements.find(({ body }) => body === value);
77
+ return match ? `[Original ${match.source}; read the working issue text and audit input.]` : value;
78
+ };
79
+ function project(value, depth = 0) {
80
+ if (depth > 64) throw Error('Product working context nesting exceeds bounds');
81
+ if (value && typeof value === 'object') for (const key of Object.keys(value)) {
82
+ if (['body', 'originalRequest'].includes(key) && typeof value[key] === 'string') value[key] = pointer(value[key]);
83
+ else if (value[key] && typeof value[key] === 'object') project(value[key], depth + 1);
84
+ }
85
+ return value;
86
+ }
87
+ for (const value of [copy.continuation, copy.answerHistory, copy.request?.answerHistory, copy.productChange?.parent]) project(value);
88
+ if (copy.issue && projected.has('issue.body')) copy.issue.body = projected.get('issue.body');
89
+ copy.issue?.ownerAnswers?.forEach((answer, i) => { if (projected.has(`issue.ownerAnswers[${i}].body`)) answer.body = projected.get(`issue.ownerAnswers[${i}].body`); });
90
+ if (copy.productChange) {
91
+ if (Object.hasOwn(copy.productChange, 'scope')) copy.productChange.scope = pointer(copy.productChange.scope);
92
+ if (copy.productChange.idea === `${context.issue?.title}\n\n${context.issue?.body ?? ''}`) copy.productChange.idea = `${context.issue.title}\n\n${pointer(context.issue.body)}`;
93
+ delete copy.productChange.files;
94
+ copy.productChange.currentDocuments = catalog;
95
+ if (aliases.length) copy.productChange.historicalCopies = aliases;
96
+ copy.productChange.audit = { path: '/workspace/.lighthouse-product-audit.json', sha256: auditSha256 ?? hash(JSON.stringify(context)), authority: 'Original verified inputs; read-only. Working references grant no approval or apply authority.' };
97
+ if (composition) copy.productChange.composition = composition;
98
+ }
99
+ if (copy.contract?.rules) copy.contract.rules += ' The host projected current retained documents without summarizing authority. Read productChange.currentDocuments for exact current source/revision/hash references and explicit document history. Use productcomposition_inspect for exact bodies and productcomposition_compose for exhaustive selections/omissions against the original inputs. productChange.audit identifies the complete read-only original context at /workspace/.lighthouse-product-audit.json; read it on demand for historical evidence. In ordinary projection, decision prose remains in the working issue and verified answers; if historyIndex is present, whole original answer bodies are indexed in the audit instead. Document revisions do not supersede prose decisions, and comment order grants no supersession. Resolve conflicting decisions explicitly; this projection grants no approval, provider apply or publication authority.';
100
+ if (Buffer.byteLength(JSON.stringify(copy)) > 256 * 1024) {
101
+ // Validate the original, not the compressed view. No overflowing input is made admissible.
102
+ productEvidenceScopeText(context);
103
+ const binding = compositionBinding(context);
104
+ const answers = sources.slice(1).filter(({ body }) => typeof body === 'string').map(({ source, body }) => {
105
+ if (Buffer.from(body, 'utf8').toString('utf8') !== body) throw Error(`Invalid whole-answer UTF-8 at ${source}; preserve original audit and supply exact UTF-8 text`);
106
+ return { source, sha256: hash(body), bytes: Buffer.byteLength(body) };
107
+ });
108
+ const references = (catalog?.measured.references ?? 0) + aliases.reduce((sum, alias) => sum + alias.files.length, 0) + answers.length;
109
+ if (references > 512) throw Error('Retained reference inventory exceeds bounds including whole-answer history');
110
+ // Index every transported body, including empty bodies. Null/absent bodies and all
111
+ // answer metadata remain in place. Nothing is chosen by order, meaning or approval.
112
+ copy.productChange.historyIndex = { binding, totalAnswers: context.issue?.ownerAnswers?.length ?? 0, answers, authority: 'Every indexed verified answer retains its original authority. Bodies are unread, not reviewed; inspect all relevant original decisions before resolving product decisions. No supersession or approval is inferred.' };
113
+ for (const reference of answers) {
114
+ const index = Number(/^issue\.ownerAnswers\[(\d+)\]\.body$/.exec(reference.source)[1]);
115
+ copy.issue.ownerAnswers[index].body = `[Whole original answer ${reference.source}; inspect productChange.historyIndex and the read-only audit for exact SHA-256/UTF-8 bytes. Authoritative decisions remain unread until inspected, not superseded or reviewed.]`;
116
+ }
117
+ if (copy.contract?.rules) copy.contract.rules += ' Whole-answer transport is active: productChange.historyIndex exhaustively indexes original verified answer bodies. Retrieve each relevant body from productChange.audit at its exact source location, verify the audit digest and decoded body SHA-256/UTF-8 byte count, and inspect its decisions before resolving relevant product decisions. All indexed decisions retain their original authority; unread bodies are not reviewed. Report conflicts or unavailable/stale bindings explicitly rather than guessing, summarizing or inferring supersession.';
118
+ if (Buffer.byteLength(JSON.stringify(copy)) > 256 * 1024) throw Error(`Product working context exceeds bounds after exact history transport; current issue/instructions must fit without truncation (issue.body sha256=${hash(context.issue?.body ?? '')}); preserve original inputs and request a bounded current payload`);
119
+ }
120
+ return copy;
121
+ }