From b4fda65fc30fcd7910b6d76f4cf661e11421ae2e Mon Sep 17 00:00:00 2001 From: transitrix Date: Tue, 29 Sep 2026 08:29:08 +0400 Subject: [PATCH 1/2] feat: record and validate document handoff events Signed-off-by: transitrix --- notations/packages/documents.md | 234 ++++++++++-------- packages/documents-cli/README.md | 87 ++++++- packages/documents-cli/documents.mjs | 37 ++- packages/documents-cli/src/events.mjs | 101 ++++++++ packages/documents-cli/src/register.mjs | 56 +++++ packages/documents-cli/src/validate.mjs | 7 +- .../tests/test_documents_integrity.py | 3 + packages/documents-cli/tests/test_events.mjs | 179 ++++++++++++++ 8 files changed, 594 insertions(+), 110 deletions(-) create mode 100644 packages/documents-cli/src/events.mjs create mode 100644 packages/documents-cli/src/register.mjs create mode 100644 packages/documents-cli/tests/test_events.mjs diff --git a/notations/packages/documents.md b/notations/packages/documents.md index eca96a28..a4d609a0 100644 --- a/notations/packages/documents.md +++ b/notations/packages/documents.md @@ -31,14 +31,15 @@ packages: [documents] ## 2. Object types and ID grammar -### 2.1 The two object kinds +### 2.1 Object kinds -The package's object model has exactly two kinds: +The package carries document definitions and instances, plus stored handoff events: | Kind | What it holds | |---|---| | `document-type` | A template: a name, a list of required fields (key + datatype), and versioning constraints. | | `document` | An issued instance: an id, the type it instantiates, a version, a status, a timestamp, and a `values` map keyed by field name. | +| `issuance-event` | A retained handoff act with issuer, recipient and pointers to evidence (§8). | ### 2.2 ID grammar — disjoint from core @@ -52,13 +53,14 @@ Per [`PACKAGES.md`](../PACKAGES.md) §4.1, a package identifier must never be sh |---|---| | `doct` | `document-type` | | `doc` | `document` | +| `issue` | `issuance-event` | -- `` is one of the two literal tokens above, followed immediately by a hyphen (so `doc-…` and `doct-…` never collide — the token match is exact, not a prefix test). +- `` is one of the literal tokens above, followed immediately by a hyphen (so `doc-…` and `doct-…` never collide — the token match is exact, not a prefix test). - `` is one or more lowercase alphanumeric segments separated by hyphens. - `` is a terminal positive integer ≥ 1, no leading zeros — same terminal-integer rule as the core grammar ([`IDS_AND_REFERENCES.md`](../IDS_AND_REFERENCES.md) §1). ``` -^(doct|doc)-[a-z0-9]+(?:-[a-z0-9]+)*-[1-9][0-9]*$ +^(doct|doc|issue)-[a-z0-9]+(?:-[a-z0-9]+)*-[1-9][0-9]*$ ``` **Examples:** `doct-requirements-1`, `doc-srs-v2-1`, `doct-architecture-decision-1`, `doc-meeting-notes-2`. @@ -69,9 +71,11 @@ Per [`PACKAGES.md`](../PACKAGES.md) §4.1, a package identifier must never be sh documents/ document-types/.yaml documents/.yaml + events/.yaml # retained handoff acts + evidence/ # optional retained run/baseline/token bytes ``` -One object per file, named by its id. Every file carries `package: documents` and `kind: ` — this pair is how the package's own tooling recognises its files; core tooling never reads them (§4.2 of the mechanism doc). +One object per file, named by its id. Every file carries `package: documents` and `kind: ` — this pair is how the package's own tooling recognises its files; core tooling never reads them (§4.2 of the mechanism doc). ### 2.4 `document-type` schema @@ -150,6 +154,7 @@ The package validator checks that a `canon_refs` value is grammar-valid (DOCS-00 ``` /documents/document-types/.yaml /documents/documents/.yaml +/documents/events/.yaml ``` One artefact per file, named by its canonical package id (§2.2). @@ -170,6 +175,8 @@ Run by `@transitrix/documents-cli validate ` (the reference im | `DOCS-006` | error | A `document.issued_at` is not a valid ISO 8601 timestamp, or `document.version` is neither a full SemVer string nor the two-component numeric compatibility form in §2.5. | | `DOCS-007` | error | A `document.status` is not one of: `draft`, `issued`, `superseded`, `archived`. | +Event-specific structural and evidence diagnostics are defined in §8. + No rule here reaches into `canon/`, `field/`, or `codex/` — package-internal integrity only, per [`PACKAGES.md`](../PACKAGES.md) §4.2. --- @@ -205,28 +212,103 @@ This package carries document identity and traceability metadata: versioning, st --- +## 8. Issuance-event register + +An `issuance-event` records an asserted handoff: **what, when, by whom, to whom**. +It does not prove that software submitted, approved or signed anything. Store one +row per act in `documents/events/.yaml`. A later handoff gets a new ID; +`transitrix-documents record` refuses to overwrite an existing row. Retain the +referenced bytes separately; the command never creates or replaces evidence. +Git history and adopter storage controls remain responsible for retention. + +| Field | Contract | +|---|---| +| `package`, `kind` | Exactly `documents`, `issuance-event`. | +| `id` | `issue--`, unique in the package. | +| `document` | Document ID using the existing `doc-…` grammar. A citation, not a new stable-identity schema. The current local document need not exist. | +| `edition` | Nonblank adopter-supplied edition label, e.g. `B`. Independent of the existing document's numeric `version`; no automatic conversion or latest-edition inference. | +| `issued_at` | Real UTC timestamp, second precision (`YYYY-MM-DDTHH:mm:ssZ`), of the asserted act. | +| `issuer`, `recipient` | Nonblank strings supplied by the recorder. No directory, signature or identity verification. | +| `run_record`, `baseline` | Pointers with exactly `uri` and `sha256`. URI is absolute, or a package-relative retained file path. | +| `resource` | Pointer with `uri` and `sha256` to the externally stored output bytes. Absolute URI required, e.g. `resource://documents/rp17/b.pdf`. | +| `issue_hash` | SHA-256 of the canonical act and pointers, as specified below. Computed by `record` if absent; a supplied mismatch fails. | +| `synthetic` | Optional boolean; use `true` for synthetic acts. | +| `timestamp` | Optional external evidence; absent by default. See below. | + +Every pointer hash is `sha256:` followed by 64 lowercase hexadecimal digits, +computed over the exact referenced bytes. A baseline pointer names retained +baseline evidence in the adopter's format; it does not copy the commit into the +row or imply the renderer created a snapshot. Absolute URIs must be parseable, +nonempty and contain no whitespace, backslash or credentials. Relative pointers +use slash-separated ASCII letters, digits, dots, underscores and hyphens; empty, +`.` and `..` segments are forbidden. The CLI reads relative files inside the +package only, refusing symlink escapes. It does not fetch absolute URIs, even +`file:` URIs. An authorized integration can supply bytes using the `inspectEvent` +loader API; URI resolvability outside the package belongs to that integration. + +Unknown event fields are errors: inventories, recipe editions and stale flags +belong in referenced evidence or derived answers, never copied into the act. +Existing `document-type` and `document` records retain their previous validation +and require no event, timestamp, migration or conversion. The event edition label +does not adopt the proposed RP-17 document/form identity or edition schema. + +**Hash contract.** Remove `issue_hash` and `timestamp`; recursively serialize the +remaining JSON value with object keys sorted by JavaScript string order, array +order retained and `JSON.stringify` scalar escaping, with no whitespace or final +newline. Hash those UTF-8 bytes. This is an integrity binding for recorded claims, +not proof of generation, submission or trusted time. `issueHash` in the CLI's +`src/events.mjs` exports the same algorithm. Retain original record and evidence +bytes; validation and reading never rewrite them. + +**Optional RFC 3161 seam.** `timestamp` contains `format: rfc3161`, `issue_hash` +(equal to the row hash), and `token_base64` and/or `reference` (a URI/hash pointer). +The token must be nonempty canonical base64. When both forms are present, its +bytes must match the reference hash. Supplied values are preserved. The validator +accepts only the envelope and association structurally: it does not parse a token's +DER, verify its message imprint, signature, certificate chain or trust policy. +An external RFC 3161 verifier must do those checks before calling it a trusted +timestamp. A synthetic token is test evidence only. No provider is contacted and +no token is minted. Output says `not-verified`, or `not-supplied` when absent. + +**Validation and evidence states.** `DOCS-EVENT`, `DOCS-POINTER`, `DOCS-HASH` and +`DOCS-TIMESTAMP` are structural errors. Duplicate IDs still fail DOCS-002. +`DOCS-EVIDENCE` is an error for conflicting bytes or contradictory run fields, +and a warning for unavailable evidence or unknown run format. Missing evidence +never becomes an invented successful observation. The read/API result is +`invalid`, `conflict`, `incomplete` or `consistent`; conflict takes precedence over +unavailable evidence. A structurally valid row may be created with unavailable +references, visibly `incomplete`. Matching hashes mean only matching supplied +bytes. The baseline format and its semantic agreement with a run are not inferred; +use the provenance checker with independently observed evidence for that comparison. +Register-wide queries are a separate interface (§10). + +Commands and a synthetic authoring example: [documents CLI](../../packages/documents-cli/README.md). + +--- + ## 9. DMS integration contract This package is upstream of document management. An adopter who keeps issued documents in a document management system (DMS) — whether commercial, open-source, or internal — integrates with this package at a defined seam. This section specifies what the module produces, what the adopter DMS provides, and what deliberate non-scope boundaries protect both sides. ### 9.1 What the module produces — the contract's goods -A rendered document run produces three artefacts: +The supported renderer emits a flat run record alongside rendered output. The +following distinguishes that output from adopter-supplied integration evidence: | Artefact | What it holds | Audience | |---|---|---| | **Run record** | Recipe identity (id, version), repository commit, model id, render timestamp, per-slot instructions and their verdicts. | DMS, integration layer, audit trails. | -| **Snapshot manifest** | The model state the render captured: list of element IDs cited in the document, rendered date, methodology version. | Traceability queries, freshness checks, retirement detection. | -| **Document identity** | Issuer, issue timestamp, document hash (content fingerprint), source reference (URI), baseline tag (git reference). | DMS registration, integrity checking, auditability. | +| **Snapshot/baseline evidence** | Supplied and retained by the adopter; not automatically emitted by the renderer. | Traceability and provenance checks. | +| **Issuance event** | Explicitly recorded act and hashed pointers (§8); not automatically emitted on render. | DMS integration and audit trails. | -**Format:** each is emitted as JSON by the reference implementation. A non-reference renderer may emit another format provided it carries the same semantic content and is documented per §9.6. +**Format:** the renderer serializes its run record as JSON. The optional register stores YAML (the creation command writes JSON, a YAML subset). No automatic snapshot or identity envelope is required or claimed. ### 9.2 What the adopter DMS provides — the contract's consumers | Consumer layer | Role | |---|---| | **Document store** | URI-addressable storage for the PDF (or other output format) — e.g. `resource://documents/srs-2026-q3/issue-1`. The URI is a reference, never dictated by the module. | -| **Metadata intake** | An endpoint or queue where the module deposits run record, snapshot manifest, and document identity on every render. | +| **Metadata intake** | Adopter-owned ingestion of retained run records, baseline evidence and explicit handoff events. The module has no delivery endpoint or webhook. | | **Query surface** | An API exposing facts the adopter needs — e.g. "which documents cite this capability", "which documents may be stale because an element changed". These queries are application-specific; the module provides the data, not the queries. | | **Retention and lifecycle** | Retention schedules, approval workflows, signature capture, records classifications, any regulatory regime the adopter runs. None of this is the module's concern. | @@ -247,107 +329,63 @@ The module carries document **identity and traceability**. It does not carry doc The module answers the question "what model was rendered into this document?" — not "who may see it" or "when must it be deleted." -### 9.4 Data exchange format — run record schema - -The run record is the primary interchange artefact. Its structure is governed by [`document-renderer/README.md`](../../packages/document-renderer/README.md), emitted as JSON following this schema: - -```json -{ - "recipe": { - "id": "product.srs", - "version": "1.0" - }, - "repository": { - "commit": "a1b2c3d4…", - "baseline_tag": "release-2026-q3" - }, - "model": { - "id": null, - "methodology_version": "5.1.0" - }, - "rendered_at": "2026-09-02T14:30:00Z", - "profile": "strict", - "slots": [ - { - "slot_id": "market-size", - "question": "How large is the addressable market?", - "inputs": ["CAP-1", "REQ-14"], - "sufficient": true, - "verdict": "sufficient", - "produced_text": "The addressable market is $5B growing at 15% CAGR.", - "attributions": ["CAP-1"] - } - ], - "suspicion": { - "computed": false, - "reason": "not-computed-by-this-pass" - } -} -``` +### 9.4 Data exchange format — actual run record -**Snapshot manifest** (extracted from the run record and document, for efficiency in queries): +[`buildRunRecord`](../../packages/document-renderer/src/run-record.mjs) emits flat +fields, not the formerly illustrated nested `recipe` / `repository` / `model` +envelope. A synthetic output with no instruction slots is: ```json { - "document_id": "doc-srs-v2-1", - "document_hash": "sha256:a1b2c3…", - "rendered_at": "2026-09-02T14:30:00Z", - "recipe_id": "product.srs", + "recipe_id": "rp17", "recipe_version": "1.0", - "baseline_commit": "a1b2c3d4…", - "methodology_version": "5.1.0", - "elements_cited": [ - "CAPABILITY-V2", - "REQUIREMENT-sched-auth-1", - "CONSTRAINT-4" - ] -} -``` - -**Document identity** (metadata bound to the issued artefact): - -```json -{ - "id": "doc-srs-v2-1", - "type": "doct-requirements-1", - "version": "2.0", - "status": "issued", - "issued_at": "2026-09-02T14:30:00Z", - "issuer": "release-automation@example.com", - "content_hash": "sha256:a1b2c3…", - "source_uri": "resource://documents/srs-2026-q3/issue-1", - "baseline_tag": "release-2026-q3" + "repository_commit": "synthetic-base-b", + "model_id": null, + "run_timestamp": "2026-07-10T09:00:00Z", + "render_date": "2026-07-10", + "profile": "strict", + "slots": [] } ``` -All timestamps are ISO 8601 UTC, second-precision. Hashes use SHA256. A non-reference renderer must emit JSON carrying these fields; schema variations are acceptable if approved by the consuming DMS. - -### 9.5 Integration example — how a DMS consumes the data - -**Scenario:** The adopter runs Studio to render a recipe, capturing the run record and snapshot manifest. A webhook delivers them to the DMS integration layer. - -``` -1. Studio renders recipe -> PDF + run record + document identity -2. Metadata integration layer receives all three -3. DMS: - - Stores the PDF at the URI named in document identity - - Ingests snapshot manifest for traceability queries - - Logs the run record for audit trail - - Marks the document as "ready for review" (its own workflow) -4. On later model change (element modified/deleted): - - Snapshot query: "which documents cite this element?" - - Result: [doc-srs-v2-1] - - DMS flags document as "stale, re-render recommended" - - Adopter decides: re-render, or retire the document -``` - -The module provides the data. The adopter DMS provides the **decision**, the **action**, and the **workflow**. +Each slot carries `slot_id`, `question`, `inputs`, `sufficient`, `verdict`, +`reason`, `produced_text`, and `attributions`. `repository_commit` and `model_id` +may be null; the builder defaults `run_timestamp` to an ISO timestamp with +milliseconds. Do not confuse that render time with the event's second-precision +handoff time. The renderer does not emit `baseline_tag`, `methodology_version`, +`elements_cited`, `suspicion` or document identity. A run's recorded attribution +is not proof of complete input closure or actual generation from a baseline. + +The event points at the exact run bytes; it copies none of those fields. The +reader recognizes a flat run by string `recipe_id`, `recipe_version` and array +`slots`. For retained compatibility it also recognizes the old illustrative +nested `recipe.id`, `recipe.version` and `slots`; no conversion is performed. +When both representations exist, disagreeing recipe identity/version or +`repository_commit` versus `repository.commit` is a conflict. Other legacy or +partial formats remain unknown/unavailable, even if their byte hash matches. +Unknown fields in run evidence are preserved; they are not inferred as supported +claims. This compatibility does not promise that a legacy renderer emitted the +old illustrative snapshot/identity objects. + +### 9.5 Integration example — explicit handoff + +1. Render the recipe; retain output and the actual flat run record. +2. Retain baseline evidence through the adopter's existing process, and keep the + output at its external URI. Compute the pointer hashes from retained bytes. +3. Record the asserted act with issuer, recipient, edition and time using §8. + Rendering alone creates no issuance event. +4. Read and validate the event. An unavailable external store remains unavailable; + an authorized adapter may supply its bytes for comparison. Subsequent handoffs + create new rows and do not rewrite the historical act or referenced evidence. + +The adopter DMS supplies storage, decisions and workflow. The package has no +automatic submission, signing or timestamp-provider integration. ### 9.6 Out-of-scope list — what the adopter DMS must guarantee - **The adopter is responsible for:** - Storing the document bytes at the URI the module names - - Verifying the content hash matches what the module emitted + - Verifying the retained bytes match their recorded hashes - Implementing access control (who may read/download) - Enforcing retention schedules and lifecycle - Capturing and verifying signatures if regulations require them diff --git a/packages/documents-cli/README.md b/packages/documents-cli/README.md index ba9dfaf1..30e7c28d 100644 --- a/packages/documents-cli/README.md +++ b/packages/documents-cli/README.md @@ -1,6 +1,6 @@ # Documents validator -`@transitrix/documents-cli` validates the optional [documents package](../../notations/packages/documents.md). It reads document types and document records, reports DOCS-001–007 errors, and never writes model files or resolves citations against core. +`@transitrix/documents-cli` validates the optional [documents package](../../notations/packages/documents.md). Validation reads document types, documents and issuance events, reports structural and evidence findings, and never writes model files or resolves citations against core. Explicit record/read commands manage individual handoff rows. Requires Node.js 20 or later. Install from a source checkout into your adopter repository: @@ -23,7 +23,7 @@ For an explicit package-only check: npx --no-install transitrix-documents validate /path/to/adopter/documents ``` -Each finding includes severity, rule and relative filename. Exit codes are 0 for clean input, 1 for record findings, and 2 for invocation or directory-read errors. Invalid YAML or schema structure is reported as an `INPUT` error rather than assigned an unrelated DOCS rule. The validator accepts YAML maps and lists, quoted scalars and comments; duplicate mapping keys fail. +Each finding includes severity, rule and relative filename. Validation exit codes are 0 for input without errors (possibly with unavailable-evidence warnings), 1 for record errors, and 2 for invocation or directory-read errors. Invalid YAML or schema structure is reported as an `INPUT` error rather than assigned an unrelated DOCS rule. The validator accepts YAML maps and lists, quoted scalars and comments; duplicate mapping keys fail. Versions accept the documented `"1.0"` compatibility form and full SemVer such as `"2.1.3"` or `"2.1.3-rc.1+build.2"`. Timestamps must be real calendar dates at UTC second precision, for example `"2026-09-01T14:30:00Z"`. DOCS-004 checks field membership and required entries; it does not add datatype-value rules. Citations check core ID syntax, including capability addresses, without requiring the target to exist. @@ -37,3 +37,86 @@ python3 packages/documents-cli/tests/test_documents_integrity.py ``` Run these commands from the methodology checkout, with Python 3 and PyYAML installed. The test installs the packed CLI into a temporary adopter and needs npm registry access or a populated npm cache. It also runs the generic package and ReqIF regression tests. + +## Recording and reading handoffs + +A handoff is an explicit asserted act, separate from a render or a document's +status. The register adds no fields to repositories that do not use events. +Existing document records remain compatible. Commands operate on an explicitly +selected package folder; normal validator dispatch still requires declaration. + +Prepare an act YAML with the fields in [§8 of the package contract](../../notations/packages/documents.md#8-issuance-event-register). +This synthetic example uses placeholders for hashes; replace them with SHA-256 +of the exact retained bytes before recording it: + +```yaml +package: documents +kind: issuance-event +id: issue-rp17-b-1 +synthetic: true +document: doc-rp17-b-1 +edition: B +issued_at: "2026-07-10T10:00:00Z" +issuer: Synthetic Issuer +recipient: Synthetic Recipient +run_record: + uri: evidence/run-b.json + sha256: "sha256:<64 lowercase hex digits>" +baseline: + uri: evidence/baseline-b.txt + sha256: "sha256:<64 lowercase hex digits>" +resource: + uri: resource://documents/rp17/b.pdf + sha256: "sha256:<64 lowercase hex digits>" +``` + +```sh +npx --no-install transitrix-documents record ./documents ./act.yaml +npx --no-install transitrix-documents read ./documents issue-rp17-b-1 +npx --no-install transitrix-documents validate ./documents +``` + +`record` computes `issue_hash` when omitted, validates the input, and exclusively +creates `events/issue-rp17-b-1.yaml`. It refuses invalid/conflicting input and an +existing ID. It writes no evidence and never rewrites another row. `read` returns +the original row plus evidence states, without changing files. Both emit JSON. +A different handoff needs a different event ID, even for the same document/edition. +The edition label does not change the document's existing numeric version contract. + +Local run/baseline pointers resolve beneath `documents/`. Absolute URIs are never +fetched by the CLI. Unavailable pointers produce `incomplete` reports and validation +warnings, not fabricated evidence or failed structural validation. Mismatching +bytes produce `conflict` and validation errors. Unknown run formats remain +unavailable. Retain historical rows and evidence through your existing repository +and external storage controls; exclusive creation is not a retention service. + +For authorized integrations, the installed `src/events.mjs` exports `issueHash`, +`hashBytes`, `validateEvent` and `inspectEvent`. The latter accepts +`{ load: async pointer => bytesOrNull }`; the adapter owns access control and +external lookup. `src/register.mjs` exports `createEvent(folder, act)` and +`readEvent(folder, id)` with the same behavior as the CLI. These inspect a single +act, not a register-wide traceability query. + +Optional timestamp evidence has this envelope: + +```yaml +timestamp: + format: rfc3161 + issue_hash: "sha256:" + reference: + uri: evidence/external-token.tsr + sha256: "sha256:" +``` + +You may supply `token_base64` instead of, or alongside, `reference`; both must bind +the same bytes. Compute the act hash with `issueHash(act)` before requesting any +external evidence through your own process. The package never requests or creates +a token. It checks the envelope only, preserving supplied evidence and reporting +`timestamp_trust: not-verified`. A reference or base64 value is not proof of an +RFC 3161 message imprint, signature, certificate chain or trusted time. No timestamp +field is required when unused; no automatic signing or submission occurs. + +Validation exits 1 on structural or evidence-conflict findings, and 0 when structurally +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. diff --git a/packages/documents-cli/documents.mjs b/packages/documents-cli/documents.mjs index 68b8e776..a5b7608e 100644 --- a/packages/documents-cli/documents.mjs +++ b/packages/documents-cli/documents.mjs @@ -3,13 +3,15 @@ import { readdir, readFile, stat } from 'node:fs/promises'; import { join, resolve } from 'node:path'; import { parseDocument } from 'yaml'; import { validateRecords } from './src/validate.mjs'; +import { inspectEvent } from './src/events.mjs'; +import { createEvent, readEvent, localLoader, parseRecord } from './src/register.mjs'; async function validate(folder) { const root = resolve(folder); if (!(await stat(root)).isDirectory()) throw new Error('Expected a documents package directory.'); const records = []; const findings = []; - for (const [subdir, kind] of [['document-types', 'document-type'], ['documents', 'document']]) { + for (const [subdir, kind] of [['document-types', 'document-type'], ['documents', 'document'], ['events', 'issuance-event']]) { let entries; try { entries = await readdir(join(root, subdir), { withFileTypes: true }); } catch (error) { if (error.code === 'ENOENT') continue; throw error; } @@ -31,18 +33,37 @@ async function validate(folder) { } } findings.push(...validateRecords(records)); + for (const { file, value } of records.filter(r => r.value?.kind === 'issuance-event')) { + const report = await inspectEvent(value, { load: localLoader(root) }); + for (const e of report.evidence) { + if (e.status !== 'consistent') findings.push({ code: 'DOCS-EVIDENCE', + severity: e.status === 'conflict' ? 'error' : 'warning', file, + message: `${e.name}: ${e.status}${e.format ? ` (${e.format})` : ''}.` }); + } + if (value.timestamp) console.log(`documents timestamp ${file}: external evidence; trust not verified`); + } + const errors = findings.filter(f => f.severity === 'error').length; for (const f of findings) console.log(`${f.code} ${f.severity} ${f.file}: ${f.message}`); - console.log(`documents validate: ${records.length} record(s), ${findings.length} error(s)${findings.length ? '' : ' — clean'}`); - return findings.length ? 1 : 0; + console.log(`documents validate: ${records.length} record(s), ${errors} error(s), ${findings.length - errors} warning(s)`); + return errors ? 1 : 0; } -const [command, folder, ...extra] = process.argv.slice(2); -if (command !== 'validate' || !folder || extra.length) { - console.error('Usage: transitrix-documents validate '); +const [command, folder, arg, ...extra] = process.argv.slice(2); +if (!folder || extra.length || !['validate', 'record', 'read'].includes(command) + || (command === 'validate' ? !!arg : !arg)) { + console.error('Usage: transitrix-documents validate | record | read '); process.exitCode = 2; } else { - try { process.exitCode = await validate(folder); } - catch (error) { + try { + if (command === 'validate') process.exitCode = await validate(folder); + else { + const result = command === 'record' + ? await createEvent(folder, parseRecord(await readFile(arg, 'utf8'))) + : await readEvent(folder, arg); + console.log(JSON.stringify(result, null, 2)); + process.exitCode = ['invalid', 'conflict'].includes(result.status) ? 1 : 0; + } + } catch (error) { // Generic dispatch retains stdout, including failures to read package input. console.log(`INPUT error: ${error.message}`); process.exitCode = 2; diff --git a/packages/documents-cli/src/events.mjs b/packages/documents-cli/src/events.mjs new file mode 100644 index 00000000..c1194012 --- /dev/null +++ b/packages/documents-cli/src/events.mjs @@ -0,0 +1,101 @@ +// Stored handoff acts and read-only evidence checks. No provider or DMS calls. +import { createHash } from 'node:crypto'; + +const map = v => v !== null && typeof v === 'object' && !Array.isArray(v); +const text = v => typeof v === 'string' && v.trim().length > 0; +const digest = v => typeof v === 'string' && v.length === 71 && /^sha256:[a-f0-9]{64}$/.test(v); +export const hashBytes = bytes => `sha256:${createHash('sha256').update(bytes).digest('hex')}`; +const fields = new Set(['package', 'kind', 'id', 'document', 'edition', 'issued_at', 'issuer', 'recipient', + 'run_record', 'baseline', 'resource', 'issue_hash', 'timestamp', 'synthetic']); + +export function localPointer(uri) { + return typeof uri === 'string' && /^[A-Za-z0-9][A-Za-z0-9._/-]*$/.test(uri) + && uri.split('/').every(part => part !== '' && part !== '.' && part !== '..'); +} +function absoluteURI(uri) { + if (!text(uri) || /[\s\\]/.test(uri) || /%(?![a-f0-9]{2})/i.test(uri)) return false; + try { const u = new URL(uri); return !!u.protocol && !u.username && !u.password && uri.length > u.protocol.length; } + catch { return false; } +} +const pointer = (v, external = false) => map(v) && Object.keys(v).every(k => ['uri', 'sha256'].includes(k)) + && digest(v.sha256) && (absoluteURI(v.uri) || (!external && localPointer(v.uri))); +const canonical = v => Array.isArray(v) ? `[${v.map(canonical).join(',')}]` + : map(v) ? `{${Object.keys(v).sort().map(k => `${JSON.stringify(k)}:${canonical(v[k])}`).join(',')}}` + : JSON.stringify(v); + +// Timestamp evidence is excluded so a provider can bind to a precomputed act hash. +export function issueHash(row) { + const { issue_hash, timestamp, ...act } = row; + return hashBytes(canonical(act)); +} + +export function validateEvent(row, file = '') { + const findings = []; + const flag = (code, message) => findings.push({ code, severity: 'error', file, message }); + if (!map(row)) { flag('DOCS-EVENT', 'Expected an issuance-event mapping.'); return findings; } + if (row.package !== 'documents' || row.kind !== 'issuance-event' + || !text(row.id) || row.id.trim() !== row.id || !/^issue-[a-z0-9]+(?:-[a-z0-9]+)*-[1-9][0-9]*$/.test(row.id ?? '') + || !text(row.document) || row.document.trim() !== row.document || !/^doc-[a-z0-9]+(?:-[a-z0-9]+)*-[1-9][0-9]*$/.test(row.document ?? '') + || !['edition', 'issuer', 'recipient'].every(k => text(row[k]))) { + flag('DOCS-EVENT', 'Required act: package, kind, issue ID, document ID, edition, issuer and recipient.'); + } + const date = typeof row.issued_at === 'string' ? new Date(row.issued_at) : null; + if (!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/.test(row.issued_at ?? '') + || !Number.isFinite(date?.getTime()) || date.toISOString() !== row.issued_at.replace('Z', '.000Z')) { + flag('DOCS-EVENT', 'issued_at must be a real UTC second-precision timestamp.'); + } + if (Object.keys(row).some(k => !fields.has(k)) || ('synthetic' in row && typeof row.synthetic !== 'boolean')) { + flag('DOCS-EVENT', 'Unknown event field or non-boolean synthetic marker. Store derived facts in referenced evidence.'); + } + for (const k of ['run_record', 'baseline', 'resource']) { + if (!pointer(row[k], k === 'resource')) flag('DOCS-POINTER', `${k} requires uri and sha256; resource must be an absolute external URI.`); + } + if (!digest(row.issue_hash) || row.issue_hash !== issueHash(row)) flag('DOCS-HASH', 'issue_hash must match the canonical act and pointers.'); + if ('timestamp' in row) { + const t = row.timestamp; + const keys = ['format', 'issue_hash', 'token_base64', 'reference']; + const hasToken = map(t) && Object.hasOwn(t, 'token_base64'); + const hasRef = map(t) && Object.hasOwn(t, 'reference'); + const validToken = hasToken && text(t.token_base64) && /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(t.token_base64) + && Buffer.from(t.token_base64, 'base64').toString('base64') === t.token_base64; + if (!map(t) || Object.keys(t).some(k => !keys.includes(k)) || t.format !== 'rfc3161' + || t.issue_hash !== row.issue_hash || !digest(t.issue_hash) || (!hasToken && !hasRef) + || (hasToken && !validToken) || (hasRef && !pointer(t.reference)) + || (hasToken && hasRef && validToken && hashBytes(Buffer.from(t.token_base64, 'base64')) !== t.reference.sha256)) { + flag('DOCS-TIMESTAMP', 'Expected external rfc3161 evidence bound to issue_hash: canonical base64 token and/or hashed reference, with matching bytes when both are supplied.'); + } + } + return findings; +} + +// load receives a validated pointer and returns bytes or null. The CLI loads +// only retained local files; authorized adapters can supply external evidence. +export async function inspectEvent(row, { load = async () => null } = {}) { + const findings = validateEvent(row); + if (findings.length) return { status: 'invalid', findings, evidence: [], timestamp_trust: 'not-verified' }; + const evidence = []; + for (const [name, ref] of [['run_record', row.run_record], ['baseline', row.baseline], ['resource', row.resource], + ...(row.timestamp?.reference ? [['timestamp', row.timestamp.reference]] : [])]) { + let bytes; + try { bytes = await load(ref); } catch { bytes = null; } + let status = bytes instanceof Uint8Array ? hashBytes(bytes) === ref.sha256 ? 'consistent' : 'conflict' : 'unavailable'; + let format; + if (name === 'run_record' && status === 'consistent') { + let run; + try { run = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)); } catch { /* unknown format */ } + const flat = map(run) && text(run.recipe_id) && text(run.recipe_version) && Array.isArray(run.slots); + const legacy = map(run?.recipe) && text(run.recipe.id) && text(run.recipe.version) && Array.isArray(run.slots); + format = flat ? 'flat' : legacy ? 'legacy-nested' : 'unknown'; + for (const [flatKey, nested, key] of [['recipe_id', 'recipe', 'id'], + ['recipe_version', 'recipe', 'version'], ['repository_commit', 'repository', 'commit']]) { + if (map(run) && Object.hasOwn(run, flatKey) && map(run[nested]) + && Object.hasOwn(run[nested], key) && run[flatKey] !== run[nested][key]) status = 'conflict'; + } + if (format === 'unknown' && status !== 'conflict') status = 'unavailable'; + } + evidence.push({ name, status, ...(format ? { format } : {}) }); + } + return { status: evidence.some(e => e.status === 'conflict') ? 'conflict' + : evidence.some(e => e.status === 'unavailable') ? 'incomplete' : 'consistent', findings, evidence, + timestamp_trust: row.timestamp ? 'not-verified' : 'not-supplied' }; +} diff --git a/packages/documents-cli/src/register.mjs b/packages/documents-cli/src/register.mjs new file mode 100644 index 00000000..8a3b7a40 --- /dev/null +++ b/packages/documents-cli/src/register.mjs @@ -0,0 +1,56 @@ +import { lstat, mkdir, readFile, realpath, writeFile } from 'node:fs/promises'; +import { isAbsolute, relative, resolve } from 'node:path'; +import { parseDocument } from 'yaml'; +import { inspectEvent, issueHash, localPointer } from './events.mjs'; + +export function parseRecord(bytes) { + const parsed = parseDocument(String(bytes), { uniqueKeys: true }); + if (parsed.errors.length) throw new Error(parsed.errors.map(e => e.message).join('; ')); + return parsed.toJS({ maxAliasCount: 100 }); +} + +export function localLoader(folder) { + return async ({ uri }) => { + if (!localPointer(uri)) return null; + const root = await realpath(folder); + const path = await realpath(resolve(root, uri)); + const rel = relative(root, path); + if (rel === '..' || rel.startsWith('../') || isAbsolute(rel)) return null; + return readFile(path); + }; +} + +async function exists(path) { + try { await lstat(path); return true; } + catch (error) { if (error.code === 'ENOENT') return false; throw error; } +} + +export async function createEvent(folder, supplied) { + const row = structuredClone(supplied); + if (row && typeof row === 'object' && !Array.isArray(row) && !Object.hasOwn(row, 'issue_hash')) row.issue_hash = issueHash(row); + const report = await inspectEvent(row, { load: localLoader(folder) }); + if (report.status === 'invalid' || report.status === 'conflict') throw new Error(JSON.stringify(report)); + const root = await realpath(folder); + const dir = resolve(root, 'events'); + await mkdir(dir, { recursive: true }); + if (await realpath(dir) !== dir) throw new Error('events must be a local directory, not a symlink.'); + if (await exists(resolve(dir, `${row.id}.yml`))) throw new Error('Event already exists as .yml.'); + // Exclusive creation is intentional: another act gets another ID. Nothing + // updates historical rows or writes their referenced evidence. + await writeFile(resolve(dir, `${row.id}.yaml`), `${JSON.stringify(row, null, 2)}\n`, { flag: 'wx' }); + return { row, ...report }; +} + +export async function readEvent(folder, id) { + if (!/^issue-[a-z0-9]+(?:-[a-z0-9]+)*-[1-9][0-9]*$/.test(id)) throw new Error('Invalid issue ID.'); + const yamlExists = await exists(resolve(folder, 'events', `${id}.yaml`)); + const ymlExists = await exists(resolve(folder, 'events', `${id}.yml`)); + if (yamlExists && ymlExists) throw new Error('Duplicate event files.'); + const bytes = await localLoader(folder)({ uri: `events/${id}.${ymlExists ? 'yml' : 'yaml'}` }); + if (!bytes) throw new Error('Event unavailable.'); + const row = parseRecord(bytes); + const report = await inspectEvent(row, { load: localLoader(folder) }); + if (row?.id !== id) report.findings.push({ code: 'INPUT', severity: 'error', file: `events/${id}.yaml`, message: 'Filename must match id.' }); + if (report.findings.length) report.status = 'invalid'; + return { row, ...report }; +} diff --git a/packages/documents-cli/src/validate.mjs b/packages/documents-cli/src/validate.mjs index b6a962bc..00c8811e 100644 --- a/packages/documents-cli/src/validate.mjs +++ b/packages/documents-cli/src/validate.mjs @@ -1,6 +1,8 @@ // Package-internal checks from notations/packages/documents.md §4. // Citations are checked for syntax only; no core files are read. -const PREFIX = { 'document-type': 'doct', document: 'doc' }; +import { validateEvent } from './events.mjs'; + +const PREFIX = { 'document-type': 'doct', document: 'doc', 'issuance-event': 'issue' }; const CORE_ID = /^[A-Z][A-Z0-9_]*(?:-[A-Za-z0-9]+)*-[1-9][0-9]*$/; const CAPABILITY_ID = /^CAPABILITY-[VH][1-9][0-9]*(?:\.[1-9][0-9]*){0,2}$/; const VERSION = /^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(?:\.(0|[1-9][0-9]*)(?:-((?:0|[1-9][0-9]*|[0-9]*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9][0-9]*|[0-9]*[A-Za-z-][0-9A-Za-z-]*))*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?)?$/; @@ -24,7 +26,7 @@ export function validateRecords(records) { const types = new Map(); for (const { file, value: obj } of records) { if (!map(obj) || obj.package !== 'documents' || !Object.hasOwn(PREFIX, obj.kind)) { - flag('INPUT', file, 'Expected a mapping with package: documents and kind: document-type or document.'); + flag('INPUT', file, 'Expected a mapping with package: documents and kind: document-type, document or issuance-event.'); continue; } if (!text(obj.id) || !new RegExp(`^${PREFIX[obj.kind]}-[a-z0-9]+(?:-[a-z0-9]+)*-[1-9][0-9]*$`).test(obj.id)) { @@ -32,6 +34,7 @@ export function validateRecords(records) { } if (ids.has(obj.id)) flag('DOCS-002', file, `id ${JSON.stringify(obj.id)} is also used in ${ids.get(obj.id)}.`); else ids.set(obj.id, file); + if (obj.kind === 'issuance-event') findings.push(...validateEvent(obj, file)); if (obj.kind === 'document-type') { const fieldsValid = Array.isArray(obj.fields) && obj.fields.length > 0 && obj.fields.every(f => map(f) && text(f.key) && DATATYPES.has(f.datatype) && typeof f.required === 'boolean'); diff --git a/packages/documents-cli/tests/test_documents_integrity.py b/packages/documents-cli/tests/test_documents_integrity.py index dc9a7e74..f6e2d090 100644 --- a/packages/documents-cli/tests/test_documents_integrity.py +++ b/packages/documents-cli/tests/test_documents_integrity.py @@ -155,6 +155,8 @@ def main(): print("PASS malformed YAML/schema: actionable input failure through dispatch") write(docpath, doc) + print(success("node", PACKAGE / "tests/test_events.mjs", root)) + canon_before = snapshot(root / "canon") shutil.rmtree(root / "documents") (root / "transitrix.yaml").write_text(manifest) @@ -172,6 +174,7 @@ def main(): silent = temp / "never-declared" shutil.copytree(root, silent) write(silent / "documents/documents/doc-invalid-1.yaml", {"package": "documents", "kind": "document", "id": "invalid"}) + write(silent / "documents/events/issue-invalid-1.yaml", {"package": "documents", "kind": "issuance-event", "id": "invalid"}) before = snapshot(silent) core_validate(silent) output = success("node", INGEST, "check-packages", silent) diff --git a/packages/documents-cli/tests/test_events.mjs b/packages/documents-cli/tests/test_events.mjs new file mode 100644 index 00000000..71c81e0e --- /dev/null +++ b/packages/documents-cli/tests/test_events.mjs @@ -0,0 +1,179 @@ +// Synthetic handoff acceptance through the packed CLI and normal dispatch. +import assert from 'node:assert/strict'; +import { mkdtemp, mkdir, readFile, writeFile, rm, symlink } from 'node:fs/promises'; +import { join, resolve } from 'node:path'; +import { pathToFileURL } from 'node:url'; +import { execFileSync, spawnSync } from 'node:child_process'; +import { tmpdir } from 'node:os'; +import { buildRunRecord, serializeRunRecord } from '../../document-renderer/src/run-record.mjs'; + +const root = resolve(process.argv[2]); +const folder = join(root, 'documents'); +const installed = join(root, 'node_modules/@transitrix/documents-cli'); +const cli = join(installed, 'documents.mjs'); +const { hashBytes, issueHash, inspectEvent, validateEvent } = await import(pathToFileURL(join(installed, 'src/events.mjs'))); +const { createEvent, readEvent } = await import(pathToFileURL(join(installed, 'src/register.mjs'))); +const dispatch = () => spawnSync(process.execPath, ['packages/ingest-cli/ingest.mjs', 'check-packages', root], { encoding: 'utf8' }); +const run = Buffer.from(serializeRunRecord(buildRunRecord({ + header: { recipe_id: 'rp17', recipe_version: '1.0' }, repositoryCommit: 'synthetic-base-b', + runTimestamp: '2026-07-10T09:00:00Z', renderDate: '2026-07-10', profile: 'strict', slotResults: [], +}))); +const baseline = Buffer.from('Synthetic retained baseline-b; repository commit synthetic-base-b\n'); +const output = Buffer.from('Synthetic RP-17 B output; no actual issuance or submission\n'); +await mkdir(join(folder, 'evidence')); +await writeFile(join(folder, 'evidence/run-b.json'), run); +await writeFile(join(folder, 'evidence/baseline-b.txt'), baseline); +const act = { + package: 'documents', kind: 'issuance-event', id: 'issue-rp17-b-1', synthetic: true, + document: 'doc-rp17-b-1', edition: 'B', 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.txt', sha256: hashBytes(baseline) }, + resource: { uri: 'resource://documents/rp17/b.pdf', sha256: hashBytes(output) }, +}; +const temp = await mkdtemp(join(tmpdir(), 'documents-events-')); +try { + const outputPath = join(temp, 'b.pdf'); + await writeFile(outputPath, output); + const input = join(temp, 'act.yaml'); + await writeFile(input, JSON.stringify(act)); + const receipt = JSON.parse(execFileSync(process.execPath, [cli, 'record', folder, input], { encoding: 'utf8' })); + const row = receipt.row; + assert.equal(receipt.status, 'incomplete'); + assert.equal(receipt.timestamp_trust, 'not-supplied'); + assert.deepEqual(receipt.evidence.map(e => e.status), ['consistent', 'consistent', 'unavailable']); + assert.equal(receipt.evidence[0].format, 'flat'); + assert(!Object.hasOwn(row, 'timestamp')); + const read = JSON.parse(execFileSync(process.execPath, [cli, 'read', folder, row.id], { encoding: 'utf8' })); + assert.deepEqual(read.row, row); + assert.equal(dispatch().status, 0); + const historicalPath = join(folder, `events/${row.id}.yaml`); + const historicalBytes = await readFile(historicalPath); + await assert.rejects(createEvent(folder, act), /EEXIST/); + assert.deepEqual(await readFile(historicalPath), historicalBytes); + + const retained = new Map([[row.run_record.uri, run], [row.baseline.uri, baseline], [row.resource.uri, output]]); + const complete = await inspectEvent(row, { load: async ref => retained.get(ref.uri) }); + assert.equal(complete.status, 'consistent'); + // A structurally accepted synthetic token is not a trusted RFC 3161 assertion. + const token = Buffer.from('Synthetic timestamp evidence, not a DER timestamp token'); + const second = { ...act, id: 'issue-rp17-b-2', recipient: 'Synthetic Second Recipient' }; + second.issue_hash = issueHash(second); + second.timestamp = { format: 'rfc3161', issue_hash: second.issue_hash, + token_base64: token.toString('base64'), reference: { uri: 'evidence/timestamp.tsr', sha256: hashBytes(token) } }; + await writeFile(join(folder, 'evidence/timestamp.tsr'), token); + const supplied = await createEvent(folder, second); + assert.equal(supplied.timestamp_trust, 'not-verified'); + assert.deepEqual(supplied.row.timestamp, second.timestamp); + assert.deepEqual(await readFile(historicalPath), historicalBytes); + assert.deepEqual(await readFile(outputPath), output); + assert.deepEqual(await readFile(join(folder, act.run_record.uri)), run); + assert.deepEqual(await readFile(join(folder, act.baseline.uri)), baseline); + const externalToken = structuredClone(second); + delete externalToken.timestamp.token_base64; + externalToken.timestamp.reference.uri = 'https://example.invalid/synthetic.tsr'; + assert.equal((await inspectEvent(externalToken)).status, 'incomplete'); + assert.equal(validateEvent(externalToken).length, 0); + const tokenOnly = structuredClone(second); + delete tokenOnly.timestamp.reference; + assert.equal(validateEvent(tokenOnly).length, 0); + + const cases = []; + for (const key of ['document', 'edition', 'issued_at', 'issuer', 'recipient']) { + cases.push(['DOCS-EVENT', `missing ${key}`, r => { delete r[key]; }]); + } + for (const key of ['run_record', 'baseline', 'resource']) { + cases.push(['DOCS-POINTER', `missing ${key}`, r => { delete r[key]; }]); + cases.push(['DOCS-POINTER', `malformed ${key}`, r => { r[key].uri = '../escape'; }]); + cases.push(['DOCS-POINTER', `malformed ${key} hash`, r => { r[key].sha256 = 'sha256:abc'; }]); + } + for (const uri of ['https://example.invalid/bad uri', 'https://user:secret@example.invalid/file', + 'https://example.invalid/%QQ', '/absolute/local', 'evidence//run.json', 'evidence/./run.json']) { + cases.push(['DOCS-POINTER', 'malformed URI', r => { r.run_record.uri = uri; }]); + } + cases.push( + ['DOCS-EVENT', 'invalid calendar date', r => { r.issued_at = '2026-02-30T10:00:00Z'; }], + ['DOCS-EVENT', 'derived facts rejected', r => { r.elements_cited = ['GOAL-synthetic-1']; }], + ['DOCS-TIMESTAMP', 'bad token', r => { r.timestamp = { format: 'rfc3161', issue_hash: r.issue_hash, token_base64: '?' }; }], + ['DOCS-TIMESTAMP', 'conflicting association', r => { r.timestamp = { ...second.timestamp }; }], + ['DOCS-TIMESTAMP', 'conflicting token/reference', r => { r.timestamp = { ...second.timestamp, issue_hash: r.issue_hash, token_base64: Buffer.from('other').toString('base64') }; }], + ['DOCS-TIMESTAMP', 'empty evidence', r => { r.timestamp = { format: 'rfc3161', issue_hash: r.issue_hash }; }], + ['DOCS-TIMESTAMP', 'malformed reference', r => { r.timestamp = { format: 'rfc3161', issue_hash: r.issue_hash, reference: { uri: 'bad uri', sha256: hashBytes(token) } }; }], + ); + for (const [code, name, mutate] of cases) { + const bad = structuredClone(row); + mutate(bad); + bad.issue_hash = issueHash(bad); + await writeFile(historicalPath, JSON.stringify(bad)); + const result = dispatch(); + assert.equal(result.status, 1, `${name}: ${result.stdout}`); + assert(result.stdout.includes(`${code} error events/${row.id}.yaml`), `${name}: ${result.stdout}`); + } + const ymlPath = join(folder, 'events/issue-legacy-file-1.yml'); + const yml = { ...act, id: 'issue-legacy-file-1' }; + yml.issue_hash = issueHash(yml); + await writeFile(ymlPath, JSON.stringify(yml)); + assert.deepEqual((await readEvent(folder, yml.id)).row, yml); + await assert.rejects(createEvent(folder, yml), /already exists/); + await rm(ymlPath); + const reordered = Object.fromEntries(Object.entries(row).reverse()); + assert.equal(issueHash(reordered), row.issue_hash); + const invalidNew = { ...act, id: 'issue-invalid-1', issuer: '' }; + await assert.rejects(createEvent(folder, invalidNew), /DOCS-EVENT/); + await assert.rejects(readFile(join(folder, 'events/issue-invalid-1.yaml')), /ENOENT/); + await writeFile(historicalPath, historicalBytes); + const duplicatePath = join(folder, 'events/issue-duplicate-1.yaml'); + await writeFile(duplicatePath, historicalBytes); + assert.equal(dispatch().status, 1); + assert.match(dispatch().stdout, /DOCS-002 error/); + await rm(duplicatePath); + await writeFile(join(folder, 'evidence/timestamp.tsr'), 'different token'); + assert.match(dispatch().stdout, /timestamp: conflict/); + await writeFile(join(folder, 'evidence/timestamp.tsr'), token); + const tampered = { ...row, recipient: 'Synthetic Tamper' }; + await writeFile(historicalPath, JSON.stringify(tampered)); + assert.match(dispatch().stdout, /DOCS-HASH error/); + await writeFile(historicalPath, historicalBytes); + await writeFile(join(folder, act.run_record.uri), 'Changed run bytes'); + assert.equal(dispatch().status, 1); + assert.match(dispatch().stdout, /run_record: conflict/); + await writeFile(join(folder, act.run_record.uri), run); + await rm(join(folder, act.baseline.uri)); + const missing = await readEvent(folder, row.id); + assert.equal(missing.evidence.find(e => e.name === 'baseline').status, 'unavailable'); + assert.equal(dispatch().status, 0); + await writeFile(join(folder, act.baseline.uri), baseline); + + const inspectRun = async value => { + const bytes = Buffer.from(JSON.stringify(value)); + const r = structuredClone(row); + r.run_record.sha256 = hashBytes(bytes); + r.issue_hash = issueHash(r); + return inspectEvent(r, { load: async ref => ref.uri === r.run_record.uri ? bytes : retained.get(ref.uri) }); + }; + const flat = JSON.parse(run); + const legacy = { recipe: { id: flat.recipe_id, version: flat.recipe_version }, repository: { commit: flat.repository_commit }, slots: [] }; + assert.equal((await inspectRun(legacy)).evidence[0].format, 'legacy-nested'); + assert.equal((await inspectRun({})).status, 'incomplete'); + assert.equal((await inspectRun({ ...flat, ...legacy, recipe: { id: 'conflict', version: '1.0' } })).status, 'conflict'); + assert.equal((await inspectRun({ ...flat, repository: { commit: 'other' } })).status, 'conflict'); + assert.equal((await inspectRun({ ...flat, recipe: { version: 'other' } })).status, 'conflict'); + assert.equal((await inspectRun({ repository_commit: 'one', repository: { commit: 'two' } })).status, 'conflict'); + const denied = await inspectEvent(row, { load: async () => { throw new Error('unavailable'); } }); + assert.equal(denied.status, 'incomplete'); + const outside = join(temp, 'outside.json'); + await writeFile(outside, run); + await symlink(outside, join(folder, 'evidence/outside.json')); + const escaped = { ...act, id: 'issue-symlink-1', run_record: { uri: 'evidence/outside.json', sha256: hashBytes(run) } }; + const escapedReport = await createEvent(folder, escaped); + assert.equal(escapedReport.evidence[0].status, 'unavailable'); + await rm(join(folder, 'events/issue-symlink-1.yaml')); + await rm(join(folder, 'evidence/outside.json')); + assert.equal(dispatch().status, 0); + assert.deepEqual(await readFile(historicalPath), historicalBytes); + assert.deepEqual(await readFile(outputPath), output); + assert.deepEqual(await readFile(join(folder, act.run_record.uri)), run); + assert.deepEqual(await readFile(join(folder, act.baseline.uri)), baseline); + console.log(`PASS issuance: ${cases.length} dispatched invalid acts/pointers/timestamps; hash/byte conflicts fail; missing evidence explicit; legacy and unknown runs; no external fetch; history retained`); + console.log(`SYNTHETIC HANDOFF RECEIPT ${JSON.stringify({ ...receipt, supplied_bundle: complete.status, supplied_timestamp: supplied.timestamp_trust })}`); +} finally { await rm(temp, { recursive: true, force: true }); } From a51a84a3f071b08c848e26448a28faa479bce90d Mon Sep 17 00:00:00 2001 From: "transitrix-foundry[bot]" <326145071+transitrix-foundry[bot]@users.noreply.github.com> Date: Fri, 2 Oct 2026 08:07:07 +0400 Subject: [PATCH 2/2] Query issued documents using retained baselines and Git changes (#631) * Add read-only issued-document queries over retained evidence Signed-off-by: transitrix * Keep document review unknown when retained Git blobs are missing Signed-off-by: transitrix --------- Signed-off-by: transitrix Co-authored-by: transitrix --- notations/packages/documents.md | 265 +++++------------- packages/documents-cli/README.md | 125 +++++++++ packages/documents-cli/package-lock.json | 8 + packages/documents-cli/package.json | 8 + packages/documents-cli/src/queries.mjs | 195 +++++++++++++ .../tests/test_documents_integrity.py | 5 +- packages/documents-cli/tests/test_queries.mjs | 208 ++++++++++++++ 7 files changed, 623 insertions(+), 191 deletions(-) create mode 100644 packages/documents-cli/src/queries.mjs create mode 100644 packages/documents-cli/tests/test_queries.mjs 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 }); }