@juangcarmona/lighthouse-sdlc 0.25.1 → 0.25.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -0
- package/epic-delivery.md +2 -0
- package/package.json +1 -1
- package/skills/product-change/retained-composition.md +23 -1
- package/src/issue-actions.mjs +4 -1
- package/src/opencode-execute.mjs +24 -5
- package/src/product-change.mjs +29 -3
- package/src/product-composition-server.mjs +41 -13
- package/src/product-composition.mjs +90 -12
- package/src/product-context.mjs +148 -0
package/README.md
CHANGED
|
@@ -67,6 +67,8 @@ Planning and Product Change workers select detailed evidence from artifact IDs i
|
|
|
67
67
|
|
|
68
68
|
Product Change workers can also [compose retained structured draft objects](skills/product-change/retained-composition.md) through two bounded local tools. The adapter projects their configuration only for Product Change preparation; ordinary literal candidates remain supported. The operation selects admitted source/path/hash identities, requires explicit latest-per-path replacement or omission, and atomically writes the complete envelope with provider validation pending. It adds no shell, arbitrary filesystem or approval capability and retains the 64-file/64-KiB-file/512-KiB-candidate limits.
|
|
69
69
|
|
|
70
|
+
The same inspection tool accepts supported inert MCP metadata separately from strict tool arguments: optional `progressToken` (string or finite number) and `ai.opencode/sessionID` (string). Unknown metadata and malformed supported values still refuse. When whole-answer transport is active, its exclusive `history` argument retrieves original indexed answer bodies in at most 1024 UTF-8 bytes per call, bound to the raw read-only audit digest, current request and whole-answer source/hash/byte identity. Follow `nextOffset` and verify the complete decoded body before reviewing its decisions; a truncated single-line audit read is not inspection. See the retained-composition guide for exact arguments, integrity checks and refusal handling. The owner captured the session/progress request shape in an operator native probe; synthetic protocol, adapter and packed-server regressions are not native qualification.
|
|
71
|
+
|
|
70
72
|
Adopt this correction through a released package and the normal workflow installer with a reviewed immutable source pin or exact package mode. Do not patch installed modules or a live image policy. Source tests and local transport execution do not establish installed qualification: after integration/publication, record registry/tarball/source provenance, clean-consumer installation, and an actual invocation of both tools on the pinned OpenCode 2.1.0 planning runtime with one complete synthetic candidate. A `configured` runtime receipt is not invocation evidence. If local MCP is incompatible, the maintainer must build/review/repin a compatible image through its owning installation path; report an actionable technical blocker rather than adding general planning permissions. Product approval, apply, parent continuation, merge and release keep their separate gates.
|
|
71
73
|
|
|
72
74
|
See [workflow handoffs](handoffs.md) for outcome meanings, publication order, interruption reconciliation and bounded retry evidence.
|
package/epic-delivery.md
CHANGED
|
@@ -26,6 +26,8 @@ The owner-driven workflow provides `reconcile`, `refine-child`, `register-pr`, `
|
|
|
26
26
|
|
|
27
27
|
Readiness uses the [adopter-owned GitHub App](github-actions.md#eligible-ci-for-bot-delivery) to create an immutable verification branch pointing to the exact head/base integration commit, then observes its native push CI and waits for enforced checks. The candidate must preserve the trusted CI workflow. The journal records intent before branch creation; an unconfirmed request is reconciled by observation, never blindly resent. `workflow_dispatch` checks cannot satisfy PR rules. Acknowledgement alone cannot make a PR ready. Each child merge still requires the owner's current-head review, and final aggregate acceptance preserves the parent's separate decision.
|
|
28
28
|
|
|
29
|
+
For native epic children, implementation policy `reviewRequired` is enforced at epic acceptance. A verified implementation can pass its own stage and register its PR for review; that result grants no merge authority. Missing implementation evidence, failed independent checks and model-reported blockers still prevent a passing result. Ordinary implementation routes retain their policy review stop.
|
|
30
|
+
|
|
29
31
|
`recover-publication` is an explicit owner action for a failed correction that wrote its exact independently checked tree but lost its final publication receipt. Supply the child, original run, PR, head and current epic base. The host verifies retained dispatch, content, cleanup, intent and dependencies before recording the old reservation as failed; it never repeats execution or writes a Git ref, PR or merge. Review feedback can then request fresh verification on the same PR. A reviewed workflow branch may run this recovery without changing the epic's frozen default branch.
|
|
30
32
|
|
|
31
33
|
Native child delivery requires the default branch to remain at the authenticated refinement revision. An explicitly owner-selected controller branch retains its workflow revision and ref separately; both the real Actions origin and its artifact must match, while the original parent, plan and delivery revision remain unchanged. Aggregate acceptance can inspect an advanced default branch after merge using retained readiness, child history, current checks and owner approval. Missing evidence or changed authority stops the action. Retain separate two-child and aggregate acceptance receipts; tests and installation do not establish native acceptance. [Issue #146](https://github.com/juangcarmona/lighthouse/issues/146) tracks that qualification.
|
package/package.json
CHANGED
|
@@ -6,8 +6,30 @@ Use this contract only in an admitted `product-change` worker when existing draf
|
|
|
6
6
|
|
|
7
7
|
Read `context.productChange.composition`. The adapter configures `productcomposition_inspect` and `productcomposition_compose` as local MCP tools on the pinned planning runtime. `configured` means configuration was projected, not that the engine connected or invoked a tool.
|
|
8
8
|
|
|
9
|
+
The protocol accepts optional `_meta` separately from tool arguments: only `progressToken` (string or finite number) and the pinned client's `ai.opencode/sessionID` (string) are supported. Both are inert and never passed to the composition service as arguments or authority. Unknown metadata fields, malformed supported values, unsafe tool arguments and altered bindings still refuse. Do not put metadata in tool arguments or record real session values as evidence. The owner-observed native metadata refusal remains a failure until separate pinned-native qualification succeeds; a process exit of zero is not catalog-inspection evidence.
|
|
10
|
+
|
|
9
11
|
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
12
|
|
|
13
|
+
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.
|
|
14
|
+
|
|
15
|
+
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.
|
|
16
|
+
|
|
17
|
+
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.
|
|
18
|
+
|
|
19
|
+
Before resolving relevant product decisions, retrieve each relevant indexed answer with `productcomposition_inspect` using only `history: { binding, auditSha256, answer, offset, limit }`. Copy `binding` from `historyIndex.binding`, `auditSha256` from `productChange.audit.sha256`, and the entire `{ source, sha256, bytes }` answer reference from `historyIndex.answers`. Start at byte `offset: 0` with `limit: 1024`; do not combine `history` with `reference`. The source is a context field selector, never a filesystem path. The service rechecks the raw audit digest, full current binding, exact indexed identity and existing bounds on every request; callers cannot supply another audit path or index.
|
|
20
|
+
|
|
21
|
+
Each reply contains `auditSha256`, `answer`, `offset`, `bytes`, `sha256`, exact inert `content` and `nextOffset`. Check the echoed identities and offset, chunk SHA-256 and UTF-8 byte count (at most the requested limit). Continue sequentially at `nextOffset` until it is `null`, concatenate the decoded content in offset order, then verify the whole body's SHA-256 and UTF-8 byte count against the answer reference before claiming it was inspected. Offsets and limits count bytes, not characters; a chunk may end early to preserve a UTF-8 boundary. An empty body returns zero bytes and `nextOffset: null`. Do not treat a truncated tool result or an incomplete sequence as a complete answer. If the permitted runtime cannot verify these identities, report that technical blocker rather than enabling shell, imports or another reader.
|
|
22
|
+
|
|
23
|
+
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. A line-limited read of the single-line audit may truncate it at 2000 characters: that is not evidence of complete inspection. This history variant uses the same authenticated read-only audit and existing inspection tool, not a new tool, permission or source of authority.
|
|
24
|
+
|
|
25
|
+
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.
|
|
26
|
+
|
|
27
|
+
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.
|
|
28
|
+
|
|
29
|
+
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.
|
|
30
|
+
|
|
31
|
+
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.
|
|
32
|
+
|
|
11
33
|
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
34
|
|
|
13
35
|
```json
|
|
@@ -32,7 +54,7 @@ Supported inputs are the host-supplied `context.productChange.files` array and t
|
|
|
32
54
|
|
|
33
55
|
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
56
|
|
|
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.
|
|
57
|
+
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
58
|
|
|
37
59
|
## Select and compose
|
|
38
60
|
|
package/src/issue-actions.mjs
CHANGED
|
@@ -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
|
|
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 } : {}) } };
|
package/src/opencode-execute.mjs
CHANGED
|
@@ -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
|
-
|
|
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;
|
|
@@ -391,7 +408,9 @@ async function main() {
|
|
|
391
408
|
receipt.verification = verification;
|
|
392
409
|
await writeFile(join(runDir, 'checks.json'), JSON.stringify(receipt));
|
|
393
410
|
await recordPhase(receipt.checks.every(c => c.exitCode === 0) ? 'passed' : 'failed');
|
|
394
|
-
|
|
411
|
+
// Native epic acceptance separately authenticates the current-head owner review.
|
|
412
|
+
// Blocking a verified implementation here prevents it from reaching that review.
|
|
413
|
+
if (request.implementation.policy.reviewRequired && !request.epic) {
|
|
395
414
|
envelope.result.status = 'blocked';
|
|
396
415
|
envelope.result.pendingReview.push('Repository policy requires owner acceptance of this candidate; engine assertions cannot grant it.');
|
|
397
416
|
}
|
package/src/product-change.mjs
CHANGED
|
@@ -255,9 +255,35 @@ export async function loadProductCore({ entry = require.resolve('@prodshape/core
|
|
|
255
255
|
}
|
|
256
256
|
|
|
257
257
|
export function productEvidenceScopeText(value) {
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
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 } = {}) {
|
|
@@ -1,14 +1,22 @@
|
|
|
1
1
|
import { constants } from 'node:fs';
|
|
2
2
|
import { open, lstat, rename, unlink } from 'node:fs/promises';
|
|
3
3
|
import { join } from 'node:path';
|
|
4
|
-
import { randomUUID } from 'node:crypto';
|
|
4
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
5
5
|
import { fileURLToPath } from 'node:url';
|
|
6
6
|
import { StringDecoder } from 'node:string_decoder';
|
|
7
7
|
import { retainedInventory, composeRetainedProduct, parseCompositionJson } from './product-composition.mjs';
|
|
8
|
+
import { inspectRetainedAnswer } from './product-context.mjs';
|
|
8
9
|
|
|
9
10
|
const referenceSchema = { type: 'object', additionalProperties: false, required: ['source', 'sha256'], properties: { source: { type: 'string' }, sha256: { type: 'string' } } };
|
|
10
11
|
export const compositionTools = [
|
|
11
|
-
{ name: 'inspect', description: 'Inspect admitted retained Product Change objects and current binding. No
|
|
12
|
+
{ name: 'inspect', description: 'Inspect admitted retained Product Change objects and current binding. No arguments returns the measured catalog; reference returns one exact inert document. Exclusive history retrieves an indexed original answer in at most 1024 UTF-8 bytes, bound to the raw audit digest, current binding and whole-answer source/hash/bytes. Follow nextOffset and verify the reconstructed whole answer before reviewing its decisions. No approval or execution authority.', inputSchema: { type: 'object', additionalProperties: false, properties: {
|
|
13
|
+
reference: { ...referenceSchema, required: ['path', 'source', 'sha256'], properties: { ...referenceSchema.properties, path: { type: 'string' } } },
|
|
14
|
+
history: { type: 'object', additionalProperties: false, required: ['binding', 'auditSha256', 'answer', 'offset', 'limit'], properties: {
|
|
15
|
+
binding: { type: 'object' }, auditSha256: { type: 'string', pattern: '^[a-f0-9]{64}$' },
|
|
16
|
+
answer: { ...referenceSchema, required: ['source', 'sha256', 'bytes'], properties: { ...referenceSchema.properties, bytes: { type: 'integer', minimum: 0 } } },
|
|
17
|
+
offset: { type: 'integer', minimum: 0 }, limit: { type: 'integer', minimum: 1, maximum: 1024 },
|
|
18
|
+
} },
|
|
19
|
+
}, not: { required: ['reference', 'history'] } } },
|
|
12
20
|
{ name: 'compose', description: 'Compose explicit latest-per-path retained selections into /output/envelope.json atomically. Requires exhaustive selections/omissions, current binding, and a caller-authored candidate envelope without files or digest, with provider validation pending. Returns measured counts, bytes and digest; never runs provider validation or approval.', inputSchema: { type: 'object', additionalProperties: false, required: ['binding', 'plan', 'envelope'], properties: { binding: { type: 'object' }, envelope: { type: 'object' }, plan: { type: 'array', maxItems: 128, items: { type: 'object', additionalProperties: false, required: ['path', 'selected', 'omitted'], properties: { path: { type: 'string' }, selected: { anyOf: [referenceSchema, { type: 'null' }] }, omitted: { type: 'array', maxItems: 128, items: referenceSchema } } } } } } },
|
|
13
21
|
];
|
|
14
22
|
|
|
@@ -31,9 +39,12 @@ export function compositionService(contextFile = '/input/context.json', outputDi
|
|
|
31
39
|
busy = true;
|
|
32
40
|
try {
|
|
33
41
|
if (!compositionTools.some(tool => tool.name === name)) throw Error('Unsupported composition capability');
|
|
34
|
-
const
|
|
42
|
+
const raw = await safeRegular(contextFile, 4 * 1024 * 1024);
|
|
43
|
+
const context = parseCompositionJson(raw);
|
|
35
44
|
if (name === 'inspect') {
|
|
36
|
-
if (!args || typeof args !== 'object' || Array.isArray(args) || Object.keys(args).some(key => key
|
|
45
|
+
if (!args || typeof args !== 'object' || Array.isArray(args) || Object.keys(args).some(key => !['reference', 'history'].includes(key)) || (Object.hasOwn(args, 'reference') && Object.hasOwn(args, 'history'))) throw Error('Unsupported inspection arguments');
|
|
46
|
+
if (Object.hasOwn(args, 'history')) return inspectRetainedAnswer(context, createHash('sha256').update(raw).digest('hex'), args.history);
|
|
47
|
+
if (Object.hasOwn(args, 'reference') && args.reference === undefined) throw Error('Invalid inspection reference');
|
|
37
48
|
return retainedInventory(context, args.reference);
|
|
38
49
|
}
|
|
39
50
|
const candidate = composeRetainedProduct(context, args);
|
|
@@ -61,24 +72,41 @@ export function compositionService(contextFile = '/input/context.json', outputDi
|
|
|
61
72
|
}
|
|
62
73
|
|
|
63
74
|
export function compositionRpc(call) {
|
|
75
|
+
const record = value => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
76
|
+
const fields = (value, allowed) => record(value) && Object.keys(value).every(key => allowed.includes(key));
|
|
77
|
+
const metadata = value => {
|
|
78
|
+
if (!fields(value, ['progressToken', 'ai.opencode/sessionID']) || (Object.hasOwn(value, 'progressToken') && typeof value.progressToken !== 'string' && !(typeof value.progressToken === 'number' && Number.isFinite(value.progressToken))) || (Object.hasOwn(value, 'ai.opencode/sessionID') && typeof value['ai.opencode/sessionID'] !== 'string')) throw Error('Unsupported composition request metadata');
|
|
79
|
+
};
|
|
64
80
|
return async request => {
|
|
65
|
-
if (!request || request.jsonrpc !== '2.0') throw Error('Invalid composition protocol');
|
|
66
|
-
if (request.id === undefined) return null;
|
|
67
81
|
let result;
|
|
68
82
|
try {
|
|
69
|
-
if (request
|
|
70
|
-
|
|
71
|
-
|
|
83
|
+
if (!fields(request, ['jsonrpc', 'id', 'method', 'params']) || request.jsonrpc !== '2.0' || typeof request.method !== 'string') throw Error('Invalid composition protocol');
|
|
84
|
+
if (!Object.hasOwn(request, 'id')) {
|
|
85
|
+
if (request.method !== 'notifications/initialized' || (request.params !== undefined && !fields(request.params, []))) throw Error('Unsupported composition notification');
|
|
86
|
+
return null;
|
|
87
|
+
}
|
|
88
|
+
if (typeof request.id !== 'string' && !(typeof request.id === 'number' && Number.isFinite(request.id))) throw Error('Invalid composition request ID');
|
|
89
|
+
if (request.params !== undefined && !record(request.params)) throw Error('Invalid composition method parameters');
|
|
90
|
+
if (Object.hasOwn(request.params ?? {}, '_meta')) metadata(request.params._meta);
|
|
91
|
+
if (request.method === 'initialize') {
|
|
92
|
+
const params = request.params;
|
|
93
|
+
if (!fields(params, ['protocolVersion', 'capabilities', 'clientInfo', '_meta']) || typeof params.protocolVersion !== 'string' || (params.capabilities !== undefined && !record(params.capabilities)) || (params.clientInfo !== undefined && !record(params.clientInfo))) throw Error('Unsupported composition initialization fields');
|
|
94
|
+
const versions = ['2024-11-05', '2025-03-26', '2025-06-18', '2025-11-25'];
|
|
95
|
+
result = { protocolVersion: versions.includes(params.protocolVersion) ? params.protocolVersion : versions[0], capabilities: { tools: {} }, serverInfo: { name: 'lighthouse-product-composition', version: '1.0.0' } };
|
|
96
|
+
} else if (request.method === 'ping' || request.method === 'tools/list') {
|
|
97
|
+
if (request.params !== undefined && !fields(request.params, ['_meta'])) throw Error('Unsupported composition discovery fields');
|
|
98
|
+
result = request.method === 'ping' ? {} : { tools: compositionTools };
|
|
99
|
+
}
|
|
72
100
|
else if (request.method === 'tools/call') {
|
|
73
|
-
if (!request.params
|
|
74
|
-
const value = await call(request.params.name, request.params.arguments);
|
|
101
|
+
if (!fields(request.params, ['name', 'arguments', '_meta']) || !['inspect', 'compose'].includes(request.params.name) || (Object.hasOwn(request.params, 'arguments') && !record(request.params.arguments))) throw Error('Unsupported composition call fields');
|
|
102
|
+
const value = await call(request.params.name, request.params.arguments ?? {});
|
|
75
103
|
result = { content: [{ type: 'text', text: JSON.stringify(value) }] };
|
|
76
104
|
} else throw Error('Unsupported composition method');
|
|
77
105
|
return { jsonrpc: '2.0', id: request.id, result };
|
|
78
106
|
} catch (error) {
|
|
79
107
|
// Do not echo input bodies, file paths from I/O errors or retained content into diagnostics.
|
|
80
108
|
const message = error.code ? 'Composition I/O unavailable; preserve inputs and prior output and ask the workflow maintainer to inspect installation.' : error instanceof SyntaxError ? 'Malformed retained JSON input' : error.message;
|
|
81
|
-
return { jsonrpc: '2.0', id: request.id, error: { code: -32602, message } };
|
|
109
|
+
return { jsonrpc: '2.0', id: typeof request?.id === 'string' || (typeof request?.id === 'number' && Number.isFinite(request.id)) ? request.id : null, error: { code: -32602, message } };
|
|
82
110
|
}
|
|
83
111
|
};
|
|
84
112
|
}
|
|
@@ -103,6 +131,6 @@ export async function runCompositionServer(input = process.stdin, output = proce
|
|
|
103
131
|
}
|
|
104
132
|
|
|
105
133
|
if (process.argv[1] === fileURLToPath(import.meta.url)) {
|
|
106
|
-
try { await runCompositionServer(); }
|
|
134
|
+
try { await runCompositionServer(process.stdin, process.stdout, compositionService('/workspace/.lighthouse-product-audit.json')); }
|
|
107
135
|
catch { process.stderr.write('Product composition unavailable; preserve prior output and report a technical blocker.\n'); process.exitCode = 1; }
|
|
108
136
|
}
|
|
@@ -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
|
|
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 (++
|
|
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,148 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { isDeepStrictEqual } from 'node:util';
|
|
3
|
+
import { bindRetainedCopies, compositionBinding, currentRetainedInventory, historicalFilesSpan, historicalMarkdown, parseCompositionJson } from './product-composition.mjs';
|
|
4
|
+
import { productEvidenceScopeText } from './product-change.mjs';
|
|
5
|
+
|
|
6
|
+
const hash = value => createHash('sha256').update(value).digest('hex');
|
|
7
|
+
const fence = /^```json[ \t]*\r?\n([\s\S]*?)^```[ \t]*\r?$/gm;
|
|
8
|
+
|
|
9
|
+
// Selectors are existing whole-answer index identities, never arbitrary field or file paths.
|
|
10
|
+
export function inspectRetainedAnswer(context, auditSha256, history) {
|
|
11
|
+
const exact = (value, keys) => {
|
|
12
|
+
if (!value || typeof value !== 'object' || Array.isArray(value) || Object.keys(value).length !== keys.length || keys.some(key => !Object.hasOwn(value, key))) throw Error('Invalid history inspection fields');
|
|
13
|
+
};
|
|
14
|
+
exact(history, ['binding', 'auditSha256', 'answer', 'offset', 'limit']);
|
|
15
|
+
exact(history.answer, ['source', 'sha256', 'bytes']);
|
|
16
|
+
if (!/^[a-f0-9]{64}$/.test(auditSha256 ?? '') || history.auditSha256 !== auditSha256) throw Error('Stale history audit binding');
|
|
17
|
+
if (!isDeepStrictEqual(history.binding, compositionBinding(context))) throw Error('Stale history request/source/baseline/schema binding');
|
|
18
|
+
// Reuse projection's complete validation, including shared historical/answer reference bounds.
|
|
19
|
+
const index = productWorkingContext(context, auditSha256).productChange.historyIndex;
|
|
20
|
+
const reference = index?.answers.find(answer => isDeepStrictEqual(answer, history.answer));
|
|
21
|
+
if (!reference) throw Error('Unknown indexed answer source/hash/byte identity');
|
|
22
|
+
const { offset, limit } = history;
|
|
23
|
+
if (!Number.isSafeInteger(offset) || offset < 0 || offset > reference.bytes || !Number.isSafeInteger(limit) || limit < 1 || limit > 1024) throw Error('History inspection range exceeds bounds');
|
|
24
|
+
const answerIndex = Number(/^issue\.ownerAnswers\[(\d+)\]\.body$/.exec(reference.source)[1]);
|
|
25
|
+
const bytes = Buffer.from(context.issue.ownerAnswers[answerIndex].body, 'utf8');
|
|
26
|
+
const continuation = position => position < bytes.length && (bytes[position] & 0xc0) === 0x80;
|
|
27
|
+
if (continuation(offset)) throw Error('History inspection offset splits UTF-8');
|
|
28
|
+
let end = Math.min(offset + limit, bytes.length);
|
|
29
|
+
while (continuation(end)) end--;
|
|
30
|
+
if (end === offset && offset < bytes.length) throw Error('History inspection limit splits UTF-8');
|
|
31
|
+
const content = bytes.subarray(offset, end).toString('utf8');
|
|
32
|
+
return { auditSha256, answer: reference, offset, bytes: end - offset, sha256: hash(content), content, nextOffset: end < bytes.length ? end : null };
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// The original remains the authority. Literal aliases require exact retained-object binding.
|
|
36
|
+
export function productWorkingContext(context, auditSha256, composition) {
|
|
37
|
+
if (context.request?.worker !== 'product-change') throw Error('Current product context requires a Product Change worker');
|
|
38
|
+
if (!context.productChange || typeof context.productChange !== 'object' || Array.isArray(context.productChange)) throw Error('Current product context needs host Product Change metadata');
|
|
39
|
+
if (context.issue?.ownerAnswers !== undefined && !Array.isArray(context.issue.ownerAnswers)) throw Error('Unsupported retained answer inventory');
|
|
40
|
+
if ((context.issue?.ownerAnswers?.length ?? 0) > 100) throw Error('Retained answer inventory exceeds bounds');
|
|
41
|
+
if (auditSha256 !== undefined && !/^[a-f0-9]{64}$/.test(auditSha256)) throw Error('Invalid Product audit SHA-256 binding');
|
|
42
|
+
const sources = [{ source: 'issue.body', body: context.issue?.body }, ...(context.issue?.ownerAnswers ?? []).map((answer, i) => ({ source: `issue.ownerAnswers[${i}].body`, body: answer.body }))];
|
|
43
|
+
const retained = context.productChange?.files !== undefined || sources.some(({ body }) => typeof body === 'string' && body.includes('lighthouse-retained-product-draft/'));
|
|
44
|
+
const catalog = retained ? currentRetainedInventory(context) : null;
|
|
45
|
+
const projected = new Map();
|
|
46
|
+
const copies = [], spans = new Map();
|
|
47
|
+
for (const { source, body } of sources) {
|
|
48
|
+
if (typeof body !== 'string') continue;
|
|
49
|
+
const replacements = [];
|
|
50
|
+
if (catalog) {
|
|
51
|
+
let markdownIndex = 0;
|
|
52
|
+
for (const match of body.matchAll(historicalMarkdown)) {
|
|
53
|
+
// A path outside the retained change is unrelated prose, not a document route.
|
|
54
|
+
if (!match[1].startsWith(`openspec/changes/${catalog.binding.changeName}/`)) continue;
|
|
55
|
+
const reference = `${source}#markdown-${markdownIndex++}`;
|
|
56
|
+
copies.push({ source: reference, inventory: `${source}#markdown`, markdown: true, files: [{ path: match[1], content: match[2] }] });
|
|
57
|
+
replacements.push({ start: match.index, end: match.index + match[0].length, reference, heading: match[0].slice(0, match[0].indexOf('```')) });
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
let index = 0;
|
|
61
|
+
for (const match of body.matchAll(fence)) {
|
|
62
|
+
const [block, raw] = match;
|
|
63
|
+
const reference = `${source}#json-${index++}`;
|
|
64
|
+
if (replacements.some(span => match.index >= span.start && match.index < span.end)) continue;
|
|
65
|
+
if (raw.includes('lighthouse-retained-product-draft/')) {
|
|
66
|
+
// currentRetainedInventory validated every declaration before any projection.
|
|
67
|
+
replacements.push({ start: match.index, end: match.index + block.length, reference, retained: true });
|
|
68
|
+
} else if (catalog) {
|
|
69
|
+
let value;
|
|
70
|
+
try { value = JSON.parse(raw); } catch {
|
|
71
|
+
if (/^\s*\{\s*"files"\s*:/.test(raw)) throw Error('Malformed historical file inventory; supply an explicitly bound retained draft');
|
|
72
|
+
continue;
|
|
73
|
+
}
|
|
74
|
+
if (!value || Array.isArray(value) || !Object.hasOwn(value, 'files')) continue;
|
|
75
|
+
value = parseCompositionJson(raw);
|
|
76
|
+
const field = historicalFilesSpan(raw);
|
|
77
|
+
copies.push({ source: reference, inventory: reference, files: value.files });
|
|
78
|
+
if (Object.keys(value).length === 1) replacements.push({ start: match.index, end: match.index + block.length, reference });
|
|
79
|
+
else {
|
|
80
|
+
const offset = match.index + block.indexOf('\n') + 1;
|
|
81
|
+
replacements.push({ start: offset + field.start, end: offset + field.end, reference, jsonField: true });
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
spans.set(source, replacements);
|
|
86
|
+
}
|
|
87
|
+
const aliases = copies.length ? bindRetainedCopies(context, copies) : [];
|
|
88
|
+
for (const { source, body } of sources) {
|
|
89
|
+
if (typeof body !== 'string') continue;
|
|
90
|
+
let end = 0, value = '';
|
|
91
|
+
for (const span of spans.get(source).sort((a, b) => a.start - b.start)) {
|
|
92
|
+
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.]`;
|
|
93
|
+
value += body.slice(end, span.start) + (span.heading ?? '') + (span.jsonField ? JSON.stringify(label) : label);
|
|
94
|
+
end = span.end;
|
|
95
|
+
}
|
|
96
|
+
projected.set(source, value + body.slice(end));
|
|
97
|
+
}
|
|
98
|
+
const copy = structuredClone(context);
|
|
99
|
+
// Redundant body copies in idea/scope, continuations and parent context are pointers,
|
|
100
|
+
// not additional decisions. All nonmatching text is preserved exactly.
|
|
101
|
+
const replacements = sources.filter(({ body }) => typeof body === 'string' && body.length);
|
|
102
|
+
const pointer = value => {
|
|
103
|
+
const match = replacements.find(({ body }) => body === value);
|
|
104
|
+
return match ? `[Original ${match.source}; read the working issue text and audit input.]` : value;
|
|
105
|
+
};
|
|
106
|
+
function project(value, depth = 0) {
|
|
107
|
+
if (depth > 64) throw Error('Product working context nesting exceeds bounds');
|
|
108
|
+
if (value && typeof value === 'object') for (const key of Object.keys(value)) {
|
|
109
|
+
if (['body', 'originalRequest'].includes(key) && typeof value[key] === 'string') value[key] = pointer(value[key]);
|
|
110
|
+
else if (value[key] && typeof value[key] === 'object') project(value[key], depth + 1);
|
|
111
|
+
}
|
|
112
|
+
return value;
|
|
113
|
+
}
|
|
114
|
+
for (const value of [copy.continuation, copy.answerHistory, copy.request?.answerHistory, copy.productChange?.parent]) project(value);
|
|
115
|
+
if (copy.issue && projected.has('issue.body')) copy.issue.body = projected.get('issue.body');
|
|
116
|
+
copy.issue?.ownerAnswers?.forEach((answer, i) => { if (projected.has(`issue.ownerAnswers[${i}].body`)) answer.body = projected.get(`issue.ownerAnswers[${i}].body`); });
|
|
117
|
+
if (copy.productChange) {
|
|
118
|
+
if (Object.hasOwn(copy.productChange, 'scope')) copy.productChange.scope = pointer(copy.productChange.scope);
|
|
119
|
+
if (copy.productChange.idea === `${context.issue?.title}\n\n${context.issue?.body ?? ''}`) copy.productChange.idea = `${context.issue.title}\n\n${pointer(context.issue.body)}`;
|
|
120
|
+
delete copy.productChange.files;
|
|
121
|
+
copy.productChange.currentDocuments = catalog;
|
|
122
|
+
if (aliases.length) copy.productChange.historicalCopies = aliases;
|
|
123
|
+
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.' };
|
|
124
|
+
if (composition) copy.productChange.composition = composition;
|
|
125
|
+
}
|
|
126
|
+
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.';
|
|
127
|
+
if (Buffer.byteLength(JSON.stringify(copy)) > 256 * 1024) {
|
|
128
|
+
// Validate the original, not the compressed view. No overflowing input is made admissible.
|
|
129
|
+
productEvidenceScopeText(context);
|
|
130
|
+
const binding = compositionBinding(context);
|
|
131
|
+
const answers = sources.slice(1).filter(({ body }) => typeof body === 'string').map(({ source, body }) => {
|
|
132
|
+
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`);
|
|
133
|
+
return { source, sha256: hash(body), bytes: Buffer.byteLength(body) };
|
|
134
|
+
});
|
|
135
|
+
const references = (catalog?.measured.references ?? 0) + aliases.reduce((sum, alias) => sum + alias.files.length, 0) + answers.length;
|
|
136
|
+
if (references > 512) throw Error('Retained reference inventory exceeds bounds including whole-answer history');
|
|
137
|
+
// Index every transported body, including empty bodies. Null/absent bodies and all
|
|
138
|
+
// answer metadata remain in place. Nothing is chosen by order, meaning or approval.
|
|
139
|
+
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.' };
|
|
140
|
+
for (const reference of answers) {
|
|
141
|
+
const index = Number(/^issue\.ownerAnswers\[(\d+)\]\.body$/.exec(reference.source)[1]);
|
|
142
|
+
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.]`;
|
|
143
|
+
}
|
|
144
|
+
if (copy.contract?.rules) copy.contract.rules += ' Whole-answer transport is active: productChange.historyIndex exhaustively indexes original verified answer bodies. Use productcomposition_inspect with the exclusive history argument { binding: productChange.historyIndex.binding, auditSha256: productChange.audit.sha256, answer: one exact historyIndex.answers reference, offset: 0, limit: 1024 }. The service verifies the raw audit digest and current binding on every request. Check each returned auditSha256, answer, offset, content SHA-256 and UTF-8 byte count; follow nextOffset sequentially until null. Concatenate exact decoded chunks, verify the whole body SHA-256/UTF-8 byte count against the index, and inspect its decisions before resolving relevant product decisions. Offsets are UTF-8 bytes, not characters; truncated replies or partial sequences are not complete inspection. Do not rely on a line-limited read of the single-line audit or enable shell/imports to retrieve or verify it. 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.';
|
|
145
|
+
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`);
|
|
146
|
+
}
|
|
147
|
+
return copy;
|
|
148
|
+
}
|