diff --git a/notations/packages/documents.md b/notations/packages/documents.md index a4d609a0..799bcc39 100644 --- a/notations/packages/documents.md +++ b/notations/packages/documents.md @@ -405,196 +405,81 @@ automatic submission, signing or timestamp-provider integration. ## 10. Traceability queries — bidirectional document-model linkage -The DMS integration produces three derived queries that enable computable traceability between issued documents and the model elements they cite. These queries run on demand against run records and snapshot manifests, with no persistent storage or index beyond what those two artefacts provide (§10.5). - -### 10.1 Query 1: Documents citing an element - -**Purpose:** Given a model state (git commit) and an element ID, find all issued documents that cite that element. - -**Signature:** -``` -documents_citing_element(commit: string, element_id: string) - -> List[{document_id, document_version, rendered_at, recipe_id}] -``` - -**Inputs:** -- `commit`: Git commit hash at which to query the model state (e.g. `a1b2c3d4…`). -- `element_id`: A core element ID in grammar-valid form per [`IDS_AND_REFERENCES.md`](../IDS_AND_REFERENCES.md) §1 (e.g. `CAPABILITY-V2`, `REQUIREMENT-sched-auth-1`). - -**Output:** An array of document records, each carrying: -- `document_id`: The document's package id (`doc-…` per §2.2). -- `document_version`: SemVer version of that document instance. -- `rendered_at`: ISO 8601 UTC timestamp when the document was issued. -- `recipe_id`: The recipe that rendered this document. -- `recipe_version`: Version of the recipe. - -**Evaluation:** -1. Enumerate all run records where `repository.commit` is `commit` or an ancestor thereof (within the canonical rendering workflow's lookback window; see §10.5). -2. For each run record, inspect its `slots[].attributions[]` to identify which elements are cited. -3. For each document rendered by that run, check its snapshot manifest: if `elements_cited` contains `element_id`, include the document in the result. - -**Example:** -``` -documents_citing_element( - commit="release-2026-q3", - element_id="CAPABILITY-V2" -) --> [ - { - document_id: "doc-srs-v2-1", - document_version: "2.0", - rendered_at: "2026-09-02T14:30:00Z", - recipe_id: "product.srs", - recipe_version: "1.0" - } -] -``` - -**Called from:** Adopter dashboards, internal audit tools, downstream DMS traceability queries (e.g. "which documents cite this capability?"). - -### 10.2 Query 2: Documents affected by a model change - -**Purpose:** Given an element ID that was deleted or moved, find all issued documents that are now potentially stale because they cited the old element state. - -**Signature:** -``` -stale_documents_for_change(element_id: string, change_type: enum["deleted", "moved"]) - -> List[{document_id, document_version, last_rendered_at, stale_since}] -``` - -**Inputs:** -- `element_id`: The core element ID that changed (e.g. `REQUIREMENT-auth-1`). -- `change_type`: The nature of the change — `"deleted"` if the element no longer exists in `canon/`, or `"moved"` if it was renamed or reclassified. - -**Output:** An array of stale-document records, each carrying: -- `document_id`: The document's package id. -- `document_version`: SemVer version of the document instance. -- `last_rendered_at`: ISO 8601 UTC timestamp when the document was last issued. -- `stale_since`: ISO 8601 UTC timestamp of the commit that deleted/moved the element. -- `recommendation`: One of `"re-render"`, `"retire"`, or `"review"` (based on time elapsed since render, per DMS policy). - -**Evaluation:** -1. Query git history to find the commit where `element_id` was deleted or moved. -2. Enumerate all run records where `repository.commit` is before that deletion commit. -3. For each run record, check all documents it rendered: if the snapshot manifest's `elements_cited` contains `element_id`, the document is stale. -4. Return all stale documents, sorted by `last_rendered_at` (oldest first). - -**Example:** -``` -stale_documents_for_change( - element_id="REQUIREMENT-auth-1", - change_type="deleted" -) --> [ - { - document_id: "doc-srs-v2-1", - document_version: "2.0", - last_rendered_at: "2026-09-01T10:00:00Z", - stale_since: "2026-09-02T08:45:00Z", - recommendation: "re-render" - } -] -``` - -**Called from:** Adopter DMS on model change events, CI/CD workflows that flag stale documents, change-impact dashboards. - -### 10.3 Query 3: Document provenance and elements - -**Purpose:** Given an issued document ID, retrieve the model state it was rendered from, its render metadata, and the complete list of elements it cites. - -**Signature:** -``` -document_provenance(document_id: string) - -> { - document_version, - rendered_at, - recipe_id, - recipe_version, - baseline_commit, - methodology_version, - elements_cited: List[string], - run_record: object - } -``` - -**Inputs:** -- `document_id`: The document's package id (`doc-…` per §2.2). - -**Output:** A single document-provenance record carrying: -- `document_version`: SemVer version of the document. -- `rendered_at`: ISO 8601 UTC timestamp when rendered. -- `recipe_id`: The recipe that produced this document. -- `recipe_version`: Version of the recipe. -- `baseline_commit`: Git commit hash of the model state that was rendered. -- `baseline_tag`: Git tag or reference name if the render was tagged (e.g. `release-2026-q3`). -- `methodology_version`: The Transitrix methodology version the render used. -- `elements_cited`: Array of core element IDs in `elements_cited` from the snapshot manifest. -- `run_record`: The full run record JSON (for audit trails and detailed inspection). - -**Evaluation:** -1. Look up the snapshot manifest for `document_id` in the DMS metadata store. -2. Retrieve the corresponding run record from the same store. -3. Return the full provenance object. - -**Example:** -``` -document_provenance("doc-srs-v2-1") --> { - document_version: "2.0", - rendered_at: "2026-09-02T14:30:00Z", - recipe_id: "product.srs", - recipe_version: "1.0", - baseline_commit: "a1b2c3d4…", - baseline_tag: "release-2026-q3", - methodology_version: "7.0.0", - elements_cited: ["CAPABILITY-V2", "REQUIREMENT-sched-auth-1"], - run_record: { … } -} -``` - -**Called from:** DMS UI (document details pane), adopter integration tools, audit and compliance workflows, document versioning dashboards. - -### 10.4 Calling convention and error handling - -All three queries are **stateless and demand-computed**. They run synchronously on invocation, with no caching or warming phase. - -| Error case | Behavior | -|---|---| -| `element_id` not found in any run record | Return empty list (Query 1, 2) or `null` (Query 3). | -| `commit` not in git history | Return empty list (Query 1). | -| `document_id` not found in DMS | Return `null` (Query 3). | -| Run record or snapshot manifest corrupted | Raise `DataIntegrityError` with the affected document id. | -| Git history unavailable | Raise `GitHistoryError` — queries are offline and fail gracefully if the repository is not accessible. | - -### 10.5 Implementation location and performance - -**Where they run:** -- **Primary:** Studio's document-render workflow, after rendering completes and before metadata is handed to the DMS. -- **Secondary:** The adopter's own integration layer or DMS plugin, querying via a REST API the module exposes (see §10.6). -- **Offline:** An adopter's internal dashboard or audit tool that has read access to run records and git history but not the DMS. - -**Performance characteristics:** -- Query 1 (documents citing element): O(R × S), where R = number of run records in the lookback window, S = average snapshot size. Typical: < 500ms for 10 years of renders. -- Query 2 (stale documents): O(R × S × G), where G = git-history depth (worst case: full repo walk to find the deletion commit). Typical: < 2s for 10 years of renders. Mitigation: cache the deletion commit once found. -- Query 3 (document provenance): O(1) — direct lookup in DMS metadata store. - -**No persistent index.** Queries derive results from run records and git history on demand. This trades latency for simplicity: no index to keep in sync, no storage beyond what the DMS already holds, and every result is guaranteed current (never stale cached data). - -**Lookback window:** Queries enumerate run records back to the earliest document still in-scope under the adopter's retention policy (see §9.6). The module does not enforce a limit; it is the adopter DMS's responsibility to bound the window (e.g. "only documents from the last 7 years" or "only documents marked 'active'"). - -### 10.6 API surface — how callers invoke the queries - -Each query is a callable function in the module's integration layer, exposed as: -- **Studio plugin:** `@transitrix/documents-dms-queries` package, imported as `{ documentsForElement, staleDocuments, documentProvenance } from '@transitrix/documents-dms-queries'`. -- **REST API:** `POST /query/` on the adopter's integration endpoint, with JSON body carrying the query inputs. -- **Python CLI:** `@transitrix/documents-cli query ` (reference implementation). - -Each invocation logs (to the DMS audit trail): -- Query name -- Inputs (commit, element id, or document id) -- Timestamp -- Caller identity (if available from the calling context) -- Result count +The optional documents package exposes `queryIssuedDocuments` from +`@transitrix/documents-cli/src/queries.mjs`. It enumerates retained issuance events +(§8), loads their exact flat run records (§9.4), checks explicit baseline bindings +and reads historical Git objects. It reuses the renderer's +[`checkDocumentProvenance`](../../packages/document-renderer/PROVENANCE.md). +See the [query interface and adapter contract](../../packages/documents-cli/README.md#querying-retained-issuance-events) +for installation, baseline JSON, authorization and complete arguments. + +### 10.1 Element → issued documents + +`query: { kind: 'element', id: elementId }` examines every retained event in the +selected register. Matching events name their exact document and edition, run +and baseline pointers, recipe and observed input closure. Multiple handoffs are +returned separately. It does not infer issuance from a render or choose the latest +edition by date. Run `slots[].attributions` are reported separately from complete +input closure: a matching input need not be quoted verbatim in the output. + +### 10.2 Changed element → review of issued documents + +`query: { kind: 'review', id: elementId, target: exactCommit }` compares each +issued baseline with an explicit full target commit. Changes include **content +modifications**, additions, deletions and moves; changed element IDs are read from +both Git trees. Path dependencies include directory membership, so a retained +observer can account for dynamic selections. Moves conservatively require review. + +Within a complete independently observed closure, intersection yields +`review-needed`; nonintersection yields `no-relevant-change`. The selected element +must itself have changed for the event to appear in `matches`; the per-event review +result considers every input in its closure. Missing history, closure, retained +bytes or binding yields `unknown`. No dates, wall-clock stale-since value or +persistent stale flag is computed. A review result describes Git evidence, not +proof that an edition is invalid or permission to regenerate it. + +### 10.3 Issued document → model and elements + +`query: { kind: 'document', id: documentId }` returns **all** retained handoffs for +that document, preserving the explicitly recorded edition and release association. +It reports the repository identity, exact baseline commit, run attributions and +observed input closure. The generated-prose `model_id` is not the model repository +identity. No current checkout, latest review, edition label or timestamp substitutes +for a historical binding. A/B retention, independent unchanged reviews without C, +and explicit release/B association remain as illustrated by +[RP-17](../examples/packages/rp17.md); proposed semantic validators remain proposed. + +### 10.4 Unknown and conflict semantics + +Results contain `status`, `matches`, per-event `records` and enumeration `failures`. +Malformed/unreadable rows cannot silently become nonmatches. A missing register, +unknown document, unavailable baseline/history or absent closure returns +`incomplete`, never an empty successful result. Contradictory document, run, +baseline, output or release bindings remain `inconsistent` even if an individual +hash or review check passes. `match` and `review` retain explicit unknown states. +Matching hashes and associations never establish actual generation, so a known +review result can coexist with incomplete overall provenance. + +### 10.5 Retention and execution boundary + +Queries read an adopter-selected immutable register snapshot, retained evidence +and explicit committed Git states. They do not write source files, event rows, +run records, outputs, indexes, element inventories, stale flags or audit logs. +They enumerate the complete selected register without an implicit lookback window. +The adopter owns retention and authorization; no result claims completeness for +records outside that selected retained scope. Reads and tree comparisons occur +on demand; no performance promise or persistent cache is part of the contract. + +### 10.6 Supported surface + +The shipped surface is the asynchronous Node.js API in `@transitrix/documents-cli`, +with `@transitrix/document-renderer` installed as its optional query peer. The +record/read/validate CLI remains available (§8). There is no shipped query REST +endpoint, Studio DMS plugin, Python query command or automatic audit logging. +Adapters own authorized external byte access and independent observer evidence; +missing adapters produce unknown results, not fabricated observations. Storage, +workflow, approval, signing, scheduling and provider integration remain outside +this package. --- diff --git a/packages/documents-cli/README.md b/packages/documents-cli/README.md index 30e7c28d..4b88dc21 100644 --- a/packages/documents-cli/README.md +++ b/packages/documents-cli/README.md @@ -120,3 +120,128 @@ Validation exits 1 on structural or evidence-conflict findings, and 0 when struc valid (possibly incomplete). `read` exits 1 for an invalid/conflicting row. Invocation, parse, write/refusal and filesystem failures exit 2. All commands keep unavailable evidence explicit in their output. + +## Querying retained issuance events + +The supported query interface is the asynchronous JavaScript export +`queryIssuedDocuments` in `src/queries.mjs`. It enumerates the selected `events/` +register and reads actual retained runs and Git objects. There is no REST service, +Studio query plugin, Python query CLI, automatic audit write or persistent index. +Install the renderer alongside the documents package to use its provenance checker: + +```sh +npm pack /path/to/methodology/packages/document-renderer +npm install ./transitrix-document-renderer-0.0.1.tgz +``` + +The optional peer is required only for queries; validation and record/read work +without it. A missing checker returns `incomplete`, never a successful empty list. + +```js +import { queryIssuedDocuments } from '@transitrix/documents-cli/src/queries.mjs'; + +const options = { + folder: './documents', + repository: { root: '.', id: 'adopter-stable-model-id' }, + authorize: async () => policyAllowsEntireRegisterAndRepository, + load: async pointer => retainedBytesForAuthorizedPointer(pointer), + observe: async row => retainedObserverBundleFor(row), +}; +const reverse = await queryIssuedDocuments({ ...options, + query: { kind: 'document', id: 'doc-rp17-b-1' } }); +const forward = await queryIssuedDocuments({ ...options, + query: { kind: 'element', id: 'REQ-14' } }); +const review = await queryIssuedDocuments({ ...options, + query: { kind: 'review', id: 'REQ-14', target: exactTargetCommit } }); +``` + +The callbacks above belong to the adopter: they are not supplied services. +`authorize` must grant the entire register, repository, retained bytes and every +observer fact atomically. Denial or an exception returns a constant unavailable +result without reading them. `load` returns exact bytes or null and must handle +local event paths as well as evidence pointers; when omitted it uses `localLoader` +from `src/register.mjs` and never fetches external URIs. `observe` returns the +existing [provenance bundle](../document-renderer/PROVENANCE.md), including claims, +recipe bytes and **independently retained** observations for that event. Neither +callback may write, fetch unapproved resources or reconstruct supposed historical +observations from current claims. Select an immutable register snapshot for each +call. Reads are memoized only for that invocation; no cache survives it. + +### Baseline binding + +For these queries, the event's existing `baseline` pointer must resolve to UTF-8 +JSON with this supported envelope (values below are synthetic placeholders): + +```json +{ + "format": "document-baseline/1", + "repository_id": "synthetic-model", + "commit": "", + "document": "doc-rp17-b-1", + "edition": "B", + "run_sha256": "<64 lowercase hex digits>", + "output_sha256": "<64 lowercase hex digits>", + "product_id": "PRODUCT-portal-1", + "release_id": "RELEASE-portal-3.2" +} +``` + +This is an explicit retained association, not renderer-generated identity or an +edition registry. `product_id` and `release_id` are optional; if present in the +baseline, claims or observations, all three must supply agreeing values. Release +membership is checked by the provenance checker. Missing release data cannot +establish applicability to a release. The event still stores only its act and +hashed pointers, with no copied recipe version, element inventory or stale flag. +Existing arbitrary baseline bytes remain valid event evidence; their query binding +is unknown until independently supported in this envelope. Do not rewrite old +evidence or manufacture this association for a legacy record. + +The observed committed snapshot ID and commit, claim snapshot ID, baseline commit +and flat run `repository_commit` must agree. `model_id` remains the generated-prose +model; the model repository identity comes from explicit baseline/observer binding. +The query passes the register's run/output bytes to the existing checker; conflicting +adapter substitutes cannot replace them. Recipe, product/release, tools, rules, +configuration and external evidence retain that checker's semantics. + +### Closure, Git comparisons and results + +`observed.closure` must bind the exact run digest and commit with complete input +IDs. Citations alone do not prove closure. For a fixed-ID selection, these can be +core element IDs. Dynamic membership needs its material dependencies too: use +`path:canon/elements` for all changes beneath that directory, or `path:` for narrower dependencies. The observer owns this completeness +judgment. No closure is inferred for old runs, omitted records or unobserved +external changes. Review results cover the compared Git snapshots only. + +Targets are full commit IDs, never tags, HEAD, dates or "latest". Git is read +without optional locks or replacement objects, and without lazy network fetching. +Complete tree comparisons include added/modified paths and both sides of a move +or deletion; changed canonical YAML element IDs are read from both snapshots. +Moves count conservatively as review-worthy even if bytes are identical. Invalid +changed element identity, missing Git objects, unsupported tree entries, command +limits or unreadable history keep review unknown. No ancestry or time window +silently drops an older retained issuance. + +Results contain `matches` (event IDs), `records` and enumeration `failures`. +Each record retains its exact document/edition and evidence pointers, recorded +model/baseline, recipe labels, run attributions, observed closure and checker +report. Repeated handoffs remain separate events; no latest-edition selection +occurs. `match` is `yes`, `no` or `unknown`; `review` is `review-needed`, +`no-relevant-change` or `unknown`. Review considers all closure inputs; a review +query's matches additionally require the selected element itself to have changed. +A match says the element was in the observed input closure, not necessarily quoted +verbatim in the output. Run attributions are returned separately. + +Conflicts dominate aggregate status, even when a review subcheck passes. Missing +closure, binding, bytes, history or observations prevents a conclusive element +match/nonmatch and review result. Reverse lookup still returns retained claims, +marked incomplete or inconsistent. Missing/empty registers and absent document IDs +return incomplete with a reason, never an empty success. Overall provenance stays +`incomplete` even with a known review result because matching bytes and recorded +associations do not prove generation. A review-needed result is not approval, +invalidity, automatic reissuance or permission to alter retained bytes. + +The [RP-17 example](../../notations/examples/packages/rp17.md) remains applicable: +A/B editions and release/B bindings are explicit; an actual unchanged review +creates no C. These queries create neither reviews nor editions. Proposed identity, +predecessor and recurrence semantics remain proposed. diff --git a/packages/documents-cli/package-lock.json b/packages/documents-cli/package-lock.json index 497eab4d..6bb30744 100644 --- a/packages/documents-cli/package-lock.json +++ b/packages/documents-cli/package-lock.json @@ -16,6 +16,14 @@ }, "engines": { "node": ">=20" + }, + "peerDependencies": { + "@transitrix/document-renderer": "0.0.1" + }, + "peerDependenciesMeta": { + "@transitrix/document-renderer": { + "optional": true + } } }, "node_modules/yaml": { diff --git a/packages/documents-cli/package.json b/packages/documents-cli/package.json index 8525ecf7..9fc8c665 100644 --- a/packages/documents-cli/package.json +++ b/packages/documents-cli/package.json @@ -20,5 +20,13 @@ "repository": "https://github.com/transitrix/methodology", "dependencies": { "yaml": "2.9.1" + }, + "peerDependencies": { + "@transitrix/document-renderer": "0.0.1" + }, + "peerDependenciesMeta": { + "@transitrix/document-renderer": { + "optional": true + } } } diff --git a/packages/documents-cli/src/queries.mjs b/packages/documents-cli/src/queries.mjs new file mode 100644 index 00000000..4bf0a53b --- /dev/null +++ b/packages/documents-cli/src/queries.mjs @@ -0,0 +1,195 @@ +// Read-only register enumeration with explicit retained bindings and Git evidence. +import { readdir } from 'node:fs/promises'; +import { resolve } from 'node:path'; +import { execFileSync } from 'node:child_process'; +import { hashBytes, inspectEvent } from './events.mjs'; +import { localLoader, parseRecord } from './register.mjs'; + +const map = v => v !== null && typeof v === 'object' && !Array.isArray(v); +const text = v => typeof v === 'string' && v.length > 0; +const oid = v => typeof v === 'string' && /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(v); +const hash = bytes => hashBytes(bytes).slice(7); +const unknown = reason => ({ status: 'incomplete', reason, matches: [], records: [] }); +const json = bytes => JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)); +function gitInput(root, args, input) { + return execFileSync('git', ['--no-optional-locks', '-C', root, ...args], + { input, env: { ...process.env, GIT_NO_LAZY_FETCH: '1', GIT_NO_REPLACE_OBJECTS: '1' }, encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'], maxBuffer: 32 * 1024 * 1024 }); +} +const git = (root, ...args) => gitInput(root, args); +function commit(root, value) { + if (!oid(value) || git(root, 'rev-parse', '--verify', `${value}^{commit}`).trim() !== value) throw new Error('history unavailable'); + return value; +} +function tree(root, revision) { + const result = new Map(); + for (const line of git(root, 'ls-tree', '-rz', '--full-tree', revision).split('\0').filter(Boolean)) { + const tab = line.indexOf('\t'); + const meta = line.slice(0, tab), path = line.slice(tab + 1); + const [mode, kind, object] = meta.split(' '); + if (!path || kind !== 'blob' || !['100644', '100755'].includes(mode)) throw new Error('unsupported tree entry'); + result.set(path, object); + } + if (result.size) { + const objects = [...new Set(result.values())]; + const available = gitInput(root, ['cat-file', '--batch-check=%(objectname) %(objecttype)'], `${objects.join('\n')}\n`).trim().split('\n'); + if (available.length !== objects.length || available.some((line, i) => line !== `${objects[i]} blob`)) { + throw new Error('retained blobs unavailable'); + } + } + return result; +} +// Compare complete trees, including both sides of moves and deletions. No +// rename heuristic, timestamp, shallow-log walk or current working-tree read. +function changes(root, base, target) { + const before = tree(root, base), after = tree(root, target); + const ids = new Set(); + const files = []; + for (const path of [...new Set([...before.keys(), ...after.keys()])].sort()) { + if (before.get(path) === after.get(path)) continue; + files.push({ path, kind: !before.has(path) ? 'added' : !after.has(path) ? 'deleted' : 'modified' }); + const parts = path.split('/'); + for (let i = 1; i <= parts.length; i++) ids.add(`path:${parts.slice(0, i).join('/')}`); + if (!path.startsWith('canon/elements/') || !/\.ya?ml$/.test(path)) continue; + for (const object of [before.get(path), after.get(path)].filter(Boolean)) { + const value = parseRecord(git(root, 'cat-file', 'blob', object)); + if (!text(value?.id)) throw new Error('element identity unavailable'); + ids.add(value.id); + } + } + return { ids: [...ids].sort(), files }; +} + +/** + * authorize covers the entire selected register, Git repository and observations. + * observe(row) supplies independent, retained provenance adapter observations; + * it must not manufacture closure from run citations. See ../README.md. + */ +export async function queryIssuedDocuments({ folder, repository, query, authorize, observe, + load = localLoader(folder) } = {}) { + try { if (await authorize?.() !== true) return unknown('unavailable'); } + catch { return unknown('unavailable'); } + if (!query || !['document', 'element', 'review'].includes(query.kind) + || !text(query.id) || !text(repository?.id) || !text(repository?.root)) return unknown('invalid-query'); + const retained = new Map(); + const safeLoad = async ref => { + if (!retained.has(ref.uri)) { + let bytes; + try { bytes = await load(ref); } catch { /* unavailable */ } + retained.set(ref.uri, bytes instanceof Uint8Array ? Buffer.from(bytes) : null); + } + return retained.get(ref.uri); + }; + let checker; + try { ({ checkDocumentProvenance: checker } = await import('@transitrix/document-renderer/src/provenance.mjs')); } + catch { return unknown('provenance-checker-unavailable'); } + let entries; + try { entries = await readdir(resolve(folder, 'events'), { withFileTypes: true }); } + catch { return unknown('register-unavailable'); } + const records = [], failures = [], seen = new Set(); + for (const entry of entries.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0)) { + if (!/\.ya?ml$/.test(entry.name)) continue; + let row; + try { + if (!entry.isFile()) throw new Error('not a record'); + row = parseRecord(await safeLoad({ uri: `events/${entry.name}` })); + if (!map(row)) throw new Error('invalid record'); + if (entry.name.replace(/\.ya?ml$/, '') !== row.id || seen.has(row.id)) { + failures.push({ file: entry.name, status: 'inconsistent', reason: 'invalid-or-duplicate-identity' }); + continue; + } + seen.add(row.id); + } catch { failures.push({ file: entry.name, status: 'incomplete', reason: 'record-unreadable-or-duplicate' }); continue; } + // Validate before filtering: malformed rows cannot silently disappear. + const event = await inspectEvent(row, { load: safeLoad }); + if (event.status === 'invalid') { failures.push({ file: entry.name, status: 'inconsistent', reason: 'invalid-event' }); continue; } + if (query.kind === 'document' && row.document !== query.id) continue; + const r = { event_id: row.id, document: row.document, edition: row.edition, + synthetic: row.synthetic === true, status: 'incomplete', review: 'unknown', match: 'unknown', + baseline: row.baseline, run_record: row.run_record, resource: row.resource, + evidence: event, findings: [] }; + records.push(r); + const conflict = reason => r.findings.push({ status: 'inconsistent', reason }); + const missing = reason => r.findings.push({ status: 'incomplete', reason }); + if (event.status === 'conflict') conflict('retained-bytes-conflict'); + if (event.status === 'incomplete') missing('retained-bytes-unavailable'); + let run, baseline, bundle; + const runBytes = await safeLoad(row.run_record), baselineBytes = await safeLoad(row.baseline); + try { run = json(runBytes); if (!map(run)) throw new Error('invalid run'); } catch { missing('run-unavailable'); } + try { baseline = json(baselineBytes); if (!map(baseline)) throw new Error('invalid baseline'); } catch { missing('baseline-unavailable'); } + try { bundle = structuredClone(await observe?.(structuredClone(row))); } catch { /* missing observation */ } + const b = map(baseline) ? baseline : {}; + const c = map(bundle?.claims) ? bundle.claims : {}, o = map(bundle?.observed) ? bundle.observed : {}; + const compare = (a, z, reason) => { + if (!text(a) || !text(z)) missing(`${reason}-unavailable`); + else if (a !== z) conflict(`${reason}-conflict`); + }; + if (b.format !== 'document-baseline/1') missing('baseline-format-unavailable'); + for (const [a, z, name] of [ + [b.document, row.document, 'document'], [b.edition, row.edition, 'edition'], + [b.repository_id, repository.id, 'repository'], [b.commit, run?.repository_commit, 'run-baseline'], + [b.run_sha256, row.run_record.sha256.slice(7), 'run-binding'], + [b.output_sha256, row.resource.sha256.slice(7), 'output-binding'], + [c.repository_id, b.repository_id, 'claimed-repository'], [o.repository_id, b.repository_id, 'observed-repository'], + [c.document_issue_id, row.document, 'claimed-document'], [o.document_issue_id, row.document, 'observed-document'], + [c.document_revision, row.edition, 'claimed-edition'], [o.document_revision, row.edition, 'observed-edition'], + [c.output_run_sha256, b.run_sha256, 'claimed-run'], [c.output_sha256, b.output_sha256, 'claimed-output'], + [o.snapshot?.commit, b.commit, 'observed-commit'], [o.snapshot?.id, b.commit, 'observed-snapshot'], + [c.snapshot_id, b.commit, 'claimed-snapshot'], + ]) compare(a, z, name); + for (const field of ['release_id', 'product_id']) { + if (field in b || field in c || field in o) { + compare(b[field], c[field], `claimed-${field}`); + compare(b[field], o[field], `observed-${field}`); + } + } + if (o.snapshot?.kind !== 'committed' || c.input_kind !== 'committed' || o.snapshot?.available !== true) missing('committed-observation-unavailable'); + if (bundle?.run instanceof Uint8Array && runBytes instanceof Uint8Array + && hash(bundle.run) !== hash(runBytes)) conflict('observer-run-conflict'); + // The register's retained bytes, never a substituted adapter run/output. + const output = await safeLoad(row.resource); + if (bundle?.output instanceof Uint8Array && output instanceof Uint8Array + && hash(bundle.output) !== hash(output)) conflict('observer-output-conflict'); + const closure = o.closure; + const bound = closure?.complete === true && closure.run_sha256 === b.run_sha256 + && closure.snapshot_id === b.commit && Array.isArray(closure.input_ids) + && closure.input_ids.every(text) && new Set(closure.input_ids).size === closure.input_ids.length; + if (!bound) missing('closure-unavailable'); + let diff; + try { + commit(repository.root, b.commit); + tree(repository.root, b.commit); // prove full retained tree availability for reverse lookup too + if (query.kind === 'review') diff = changes(repository.root, b.commit, commit(repository.root, query.target)); + } catch { missing('history-unavailable'); } + const observed = { ...o }; + delete observed.changes; // callers cannot substitute an unexecuted comparison + if (diff) observed.changes = { complete: true, repository_id: repository.id, + base_snapshot_id: b.commit, target_snapshot_id: query.target, ids: diff.ids }; + const provenance = await checker({ authorize: async () => true, + load: async () => ({ ...bundle, run: runBytes, output, observed }) }); + r.provenance = provenance; + if (provenance.status === 'inconsistent') conflict('provenance-conflict'); + r.model = { repository_id: b.repository_id ?? null, commit: b.commit ?? null, + generated_prose_model: run?.model_id ?? null, release_id: b.release_id ?? null, product_id: b.product_id ?? null }; + r.recipe = { id: run?.recipe_id ?? null, version: run?.recipe_version ?? null }; + r.elements = { inputs: bound ? [...closure.input_ids] : null, + attributions: Array.isArray(run?.slots) ? run.slots.flatMap(s => Array.isArray(s?.attributions) ? s.attributions : []) : null }; + if (diff) r.changes = diff; + const usable = r.findings.length === 0; + r.status = r.findings.some(f => f.status === 'inconsistent') ? 'inconsistent' + : !usable || provenance.status === 'incomplete' ? 'incomplete' : 'consistent'; + if (query.kind === 'document') r.match = 'yes'; + else if (usable) r.match = closure.input_ids.includes(query.id) ? 'yes' : 'no'; + if (query.kind === 'review' && usable && diff) { + const check = provenance.checks.find(x => x.id === 'changes.review'); + if (check?.status === 'consistent') r.review = check.reason === 'relevant-change-review-needed' ? 'review-needed' : 'no-relevant-change'; + // The selected element must actually change; all inputs still contribute + // to the per-document review result, without date/latest inference. + r.match = closure.input_ids.includes(query.id) && diff.ids.includes(query.id) ? 'yes' : 'no'; + } + } + const inconsistent = [...records, ...failures].some(r => r.status === 'inconsistent'); + return { status: inconsistent ? 'inconsistent' : 'incomplete', + reason: inconsistent ? 'evidence-conflict' : failures.length ? 'register-incomplete' + : records.length ? 'generation-not-proven' : 'no-retained-match', + matches: records.filter(r => r.match === 'yes').map(r => r.event_id), records, failures }; +} diff --git a/packages/documents-cli/tests/test_documents_integrity.py b/packages/documents-cli/tests/test_documents_integrity.py index f6e2d090..82f384b4 100644 --- a/packages/documents-cli/tests/test_documents_integrity.py +++ b/packages/documents-cli/tests/test_documents_integrity.py @@ -61,10 +61,12 @@ def main(): temp = Path(temp) # Verify the distributable, not a fake validator or source-tree symlink. packed = json.loads(success("npm", "pack", "--json", "--pack-destination", temp, cwd=PACKAGE)) + renderer = json.loads(success("npm", "pack", "--json", "--pack-destination", temp, + cwd=ROOT / "packages/document-renderer")) root = temp / "adopter" root.mkdir() success("npm", "install", "--ignore-scripts", "--no-audit", "--no-fund", - "--prefix", root, temp / packed[0]["filename"]) + "--prefix", root, temp / packed[0]["filename"], temp / renderer[0]["filename"]) manifest = f'transitrix: 1\nmethodology_version: "{VERSION}"\ncoverage_profile: core\n' (root / "transitrix.yaml").write_text(manifest + "packages: [documents]\n") # Two admitted synthetic goals, including an actual core-to-core reference. @@ -156,6 +158,7 @@ def main(): write(docpath, doc) print(success("node", PACKAGE / "tests/test_events.mjs", root)) + print(success("node", PACKAGE / "tests/test_queries.mjs", root)) canon_before = snapshot(root / "canon") shutil.rmtree(root / "documents") diff --git a/packages/documents-cli/tests/test_queries.mjs b/packages/documents-cli/tests/test_queries.mjs new file mode 100644 index 00000000..07cf5570 --- /dev/null +++ b/packages/documents-cli/tests/test_queries.mjs @@ -0,0 +1,208 @@ +// Synthetic retained editions queried through the installed distribution. +import assert from 'node:assert/strict'; +import { mkdtemp, mkdir, readFile, writeFile, readdir, rm, rename } from 'node:fs/promises'; +import { join, resolve } from 'node:path'; +import { tmpdir } from 'node:os'; +import { pathToFileURL } from 'node:url'; +import { execFileSync } from 'node:child_process'; +import { buildRunRecord, serializeRunRecord } from '../../document-renderer/src/run-record.mjs'; +const installed = resolve(process.argv[2], 'node_modules/@transitrix/documents-cli'); +const { queryIssuedDocuments } = await import(pathToFileURL(join(installed, 'src/queries.mjs'))); +const { createEvent, localLoader } = await import(pathToFileURL(join(installed, 'src/register.mjs'))); +const { hashBytes, issueHash } = await import(pathToFileURL(join(installed, 'src/events.mjs'))); +const digest = b => hashBytes(b).slice(7); +const root = await mkdtemp(join(tmpdir(), 'documents-query-')); +const folder = join(root, 'documents'); +const git = (...args) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim(); +const put = async (p, bytes) => { await mkdir(join(root, p, '..'), { recursive: true }); await writeFile(join(root, p), bytes); }; +const save = message => { git('add', 'canon'); git('-c', 'user.name=Synthetic Test', '-c', 'user.email=synthetic@example.invalid', 'commit', '-qm', message); return git('rev-parse', 'HEAD'); }; +const snapshot = async dir => { + const files = {}; + async function walk(p, prefix = '') { + for (const e of await readdir(p, { withFileTypes: true })) { + const key = prefix + e.name; + if (e.isDirectory()) await walk(join(p, e.name), `${key}/`); + else files[key] = hashBytes(await readFile(join(p, e.name))); + } + } + await walk(dir); return files; +}; +try { + git('init', '-q'); + await put('canon/elements/REQ-14.yaml', 'id: REQ-14\nname: Synthetic retained content\n'); + await put('canon/elements/REQ-99.yaml', 'id: REQ-99\nname: Synthetic unrelated content\n'); + const base = save('Synthetic baseline'); + await put('canon/elements/REQ-14.yaml', 'id: REQ-14\nname: Synthetic relevant modification\n'); + const relevant = save('Synthetic relevant content'); + git('checkout', '-q', base); + await put('canon/elements/REQ-99.yaml', 'id: REQ-99\nname: Synthetic unrelated modification\n'); + const unrelated = save('Synthetic unrelated content'); + git('checkout', '-q', base); + await rename(join(root, 'canon/elements/REQ-14.yaml'), join(root, 'canon/elements/REQ-14-moved.yaml')); + const moved = save('Synthetic move'); + await rm(join(root, 'canon/elements/REQ-14-moved.yaml')); + const deleted = save('Synthetic deletion'); + git('checkout', '-q', base); + const recipe = await readFile(new URL('../../document-renderer/tests/fixtures/product.mrd.ttrs', import.meta.url)); + const run = Buffer.from(serializeRunRecord(buildRunRecord({ + header: { recipe_id: 'product.mrd', recipe_version: '1.0' }, repositoryCommit: base, + modelId: 'synthetic-prose-model', runTimestamp: '2026-07-10T09:00:00Z', renderDate: '2026-07-10', profile: 'strict', + slotResults: [{ slotId: 'synthetic', question: 'Synthetic', inputs: ['REQ-14'], sufficient: true, + verdict: 'sufficient', text: 'Synthetic', attributions: ['REQ-14'] }], + }))); + const output = Buffer.from('Synthetic retained RP-17 B; no real issuance'); + const baseline = { format: 'document-baseline/1', document: 'doc-rp17-b-1', edition: 'B', + repository_id: 'synthetic-model', commit: base, run_sha256: digest(run), output_sha256: digest(output), + product_id: 'PRODUCT-portal-1', release_id: 'RELEASE-portal-3.2' }; + await put('documents/evidence/run-b.json', run); + await put('documents/evidence/baseline-b.json', JSON.stringify(baseline)); + const act = { package: 'documents', kind: 'issuance-event', id: 'issue-rp17-b-1', synthetic: true, + document: baseline.document, edition: baseline.edition, issued_at: '2026-07-10T10:00:00Z', + issuer: 'Synthetic Issuer', recipient: 'Synthetic Recipient', + run_record: { uri: 'evidence/run-b.json', sha256: hashBytes(run) }, + baseline: { uri: 'evidence/baseline-b.json', sha256: hashBytes(Buffer.from(JSON.stringify(baseline))) }, + resource: { uri: 'resource://documents/rp17/b.pdf', sha256: hashBytes(output) } }; + await createEvent(folder, act); + await createEvent(folder, { ...act, id: 'issue-rp17-b-2', recipient: 'Synthetic Second Recipient' }); + const input = Buffer.from('Synthetic tool/rule/configuration evidence'); + const claims = { repository_id: baseline.repository_id, input_kind: 'committed', snapshot_id: base, + document_issue_id: act.document, document_revision: 'B', product_id: baseline.product_id, release_id: baseline.release_id, + output_sha256: digest(output), output_run_sha256: digest(run), recipe_sha256: digest(recipe), selection_sha256: digest(input), + tools: [{ id: 'synthetic-tool', sha256: digest(input) }], rules: [{ id: 'synthetic-rule', sha256: digest(input) }], + configuration: [{ id: 'synthetic-config', sha256: digest(input) }], external: [] }; + // This synthetic observer witnessed a fixed-ID selection over the controlled + // baseline. A dynamic query must include its membership dependencies instead. + const observed = { repository_id: baseline.repository_id, snapshot: { kind: 'committed', id: base, available: true, commit: base }, + document_issue_id: act.document, document_revision: 'B', product_id: baseline.product_id, release_id: baseline.release_id, + release_product_id: baseline.product_id, selection_sha256: digest(input), as_at: '2026-07-10', profile: 'strict', + closure: { complete: true, run_sha256: digest(run), snapshot_id: base, input_ids: ['REQ-14'] }, + tools: [{ id: 'synthetic-tool', bytes: input }], rules: [{ id: 'synthetic-rule', bytes: input }], + configuration: [{ id: 'synthetic-config', bytes: input }], external: [] }; + const bundle = { run, recipe, output, claims, observed }; + const options = { folder, repository: { root, id: baseline.repository_id }, authorize: async () => true, + load: async ref => ref.uri === act.resource.uri ? output : localLoader(folder)(ref), + observe: async () => bundle }; + const query = (q, extra = {}) => queryIssuedDocuments({ ...options, query: q, ...extra }); + const before = await snapshot(root); + const originalBundle = structuredClone(bundle); + let result = await query({ kind: 'document', id: act.document }); + assert.equal(result.status, 'incomplete'); // generation is never established + assert.deepEqual(result.matches, ['issue-rp17-b-1', 'issue-rp17-b-2']); + assert.equal(result.records[0].model.commit, base); + assert.equal(result.records[0].model.repository_id, baseline.repository_id); + assert.equal(result.records[0].model.generated_prose_model, 'synthetic-prose-model'); + assert.equal(result.records[0].model.release_id, baseline.release_id); + assert.deepEqual(result.records[0].elements.attributions, ['REQ-14']); + assert.equal(result.records[0].findings.length, 0, JSON.stringify(result)); + assert.deepEqual((await query({ kind: 'element', id: 'REQ-14' })).matches, result.matches); + assert.deepEqual((await query({ kind: 'element', id: 'REQ-99' })).records.map(r => r.match), ['no', 'no']); + for (const [name, target, expected] of [['relevant-content', relevant, 'review-needed'], ['unrelated-content', unrelated, 'no-relevant-change'], + ['move', moved, 'review-needed'], ['deletion', deleted, 'review-needed']]) { + result = await query({ kind: 'review', id: 'REQ-14', target }); + assert.deepEqual(result.records.map(r => r.review), [expected, expected], JSON.stringify(result)); + assert.equal(result.matches.length, expected === 'review-needed' ? 2 : 0); + console.log(JSON.stringify({ case: name, status: result.status, review: expected, matches: result.matches })); + } + for (const [name, mutate, conflict] of [ + ['missing-closure', b => { delete b.observed.closure; }, false], + ['partial-closure', b => { b.observed.closure.complete = false; }, false], + ['missing-binding', b => { delete b.claims.output_run_sha256; }, false], + ['wrong-document', b => { b.observed.document_issue_id = 'doc-other-1'; }, true], + ['wrong-edition', b => { b.observed.document_revision = 'A'; }, true], + ['wrong-release', b => { b.observed.release_id = 'RELEASE-portal-9'; }, true], + ['substituted-run', b => { b.run = Buffer.from('{}'); }, true], + ]) { + const b = structuredClone(bundle); mutate(b); + result = await query({ kind: 'review', id: 'REQ-14', target: relevant }, { observe: async () => b }); + assert.equal(result.status, conflict ? 'inconsistent' : 'incomplete', name); + assert(result.records.every(r => r.review === 'unknown' && r.match === 'unknown'), name); + } + result = await query({ kind: 'review', id: 'REQ-14', target: '0'.repeat(40) }); + assert(result.records.every(r => r.review === 'unknown' && r.findings.some(f => f.reason === 'history-unavailable'))); + for (const unavailable of [act.baseline.uri, act.run_record.uri, act.resource.uri]) { + result = await query({ kind: 'review', id: 'REQ-14', target: relevant }, + { load: async ref => ref.uri === unavailable ? null : options.load(ref) }); + assert.equal(result.status, 'incomplete'); + assert(result.records.every(r => r.review === 'unknown')); + } + result = await query({ kind: 'review', id: 'REQ-14', target: relevant }, + { load: async ref => ref.uri === act.baseline.uri ? Buffer.from('{}') : options.load(ref) }); + assert.equal(result.status, 'inconsistent'); + assert(result.records.every(r => r.review === 'unknown')); + let loaded = false; + result = await query({ kind: 'document', id: act.document }, { authorize: async () => false, load: async () => { loaded = true; } }); + assert.deepEqual(result, { status: 'incomplete', reason: 'unavailable', matches: [], records: [] }); + assert.equal(loaded, false); + assert.deepEqual(await snapshot(root), before, 'queries must preserve Git, records and all retained bytes'); + assert.deepEqual(structuredClone(bundle), originalBundle, 'adapter input must not mutate'); + const blob = git('rev-parse', `${base}:canon/elements/REQ-14.yaml`); + const objectPath = join(root, '.git/objects', blob.slice(0, 2), blob.slice(2)); + const objectBytes = await readFile(objectPath); + await rm(objectPath); + result = await query({ kind: 'review', id: 'REQ-14', target: base }); + assert(result.records.every(r => r.review === 'unknown' && r.findings.some(f => f.reason === 'history-unavailable'))); + await writeFile(objectPath, objectBytes); + const membership = structuredClone(bundle); + membership.observed.closure.input_ids.push('path:canon/elements'); + result = await query({ kind: 'review', id: 'REQ-14', target: unrelated }, { observe: async () => membership }); + assert(result.records.every(r => r.review === 'review-needed'), 'dynamic membership changes remain relevant'); + // Retained A is selected by its own identity; later actual reviews of A or B + // remain independent external evidence and never select or mint an edition. + const outputA = Buffer.from('Synthetic retained RP-17 A; original content'); + const baselineA = { ...baseline, document: 'doc-rp17-a-1', edition: 'A', output_sha256: digest(outputA) }; + delete baselineA.release_id; delete baselineA.product_id; + await put('documents/evidence/baseline-a.json', JSON.stringify(baselineA)); + const actA = { ...act, id: 'issue-rp17-a-1', document: baselineA.document, edition: 'A', issued_at: '2026-04-10T10:00:00Z', + baseline: { uri: 'evidence/baseline-a.json', sha256: hashBytes(Buffer.from(JSON.stringify(baselineA))) }, + resource: { uri: 'resource://documents/rp17/a.pdf', sha256: hashBytes(outputA) } }; + await createEvent(folder, actA); + const bundleA = structuredClone(bundle); + bundleA.output = outputA; + for (const data of [bundleA.claims, bundleA.observed]) { + data.document_issue_id = actA.document; data.document_revision = 'A'; + delete data.product_id; delete data.release_id; delete data.release_product_id; + } + bundleA.claims.output_sha256 = digest(outputA); + const editions = { load: async ref => ref.uri === actA.resource.uri ? outputA : options.load(ref), + observe: async row => row.document === actA.document ? bundleA : bundle }; + result = await query({ kind: 'document', id: actA.document }, editions); + assert.deepEqual(result.matches, ['issue-rp17-a-1']); + assert.equal(result.records[0].edition, 'A'); + assert.equal(result.records[0].findings.length, 0); + const retainedEditions = await snapshot(folder); + // These are synthetic external observations, not newly adopted review schema. + await put('actual-reviews.json', JSON.stringify([ + { document: 'RP-17', edition: 'A', performed: '2026-04-20', outcome: 'unchanged' }, + { document: 'RP-17', edition: 'B', performed: '2027-04-20', outcome: 'unchanged' }, + ])); + result = await query({ kind: 'document', id: act.document }, editions); + assert.deepEqual(result.matches, ['issue-rp17-b-1', 'issue-rp17-b-2']); + assert(result.records.every(r => r.edition === 'B' && r.model.release_id === baseline.release_id)); + assert.deepEqual(await snapshot(folder), retainedEditions, 'unchanged review must not rewrite A/B or create C'); + for (const malformed of ['null', '[]', '"unknown"']) { + const badBytes = Buffer.from(malformed); + const malformedAct = { ...act, baseline: { ...act.baseline, sha256: hashBytes(badBytes) } }; + malformedAct.issue_hash = issueHash(malformedAct); + result = await query({ kind: 'document', id: act.document }, { load: async ref => + ref.uri === 'events/issue-rp17-b-1.yaml' ? Buffer.from(JSON.stringify(malformedAct)) : + ref.uri === act.baseline.uri ? badBytes : options.load(ref) }); + assert.equal(result.records[0].status, 'incomplete'); + assert.equal(result.records[0].review, 'unknown'); + } + // Persisted contradictions remain conflicts even when event hashes agree. + const badBaseline = { ...baseline, edition: 'A' }; + await put('documents/evidence/baseline-b.json', JSON.stringify(badBaseline)); + const bad = { ...act, baseline: { ...act.baseline, sha256: hashBytes(Buffer.from(JSON.stringify(badBaseline))) } }; + bad.issue_hash = issueHash(bad); + await put('documents/events/issue-rp17-b-1.yaml', JSON.stringify(bad)); + result = await query({ kind: 'document', id: act.document }); + assert.equal(result.records[0].status, 'inconsistent'); + assert(result.records[0].findings.some(f => f.reason === 'edition-conflict')); + await put('documents/events/broken.yaml', 'package: ['); + result = await query({ kind: 'element', id: 'REQ-99' }); + assert(result.failures.length > 0); + assert.notEqual(result.status, 'consistent'); + await rm(join(folder, 'events'), { recursive: true }); + assert.equal((await query({ kind: 'document', id: act.document })).reason, 'register-unavailable'); + console.log('PASS packed queries: reverse/forward; controlled Git content/move/deletion; missing/conflicting evidence; read-only bytes; authorization; explicit release/B binding'); +} finally { await rm(root, { recursive: true, force: true }); }