diff --git a/packages/dsw-document-worker/CHANGELOG.md b/packages/dsw-document-worker/CHANGELOG.md index ad192d05..54e0d9b7 100644 --- a/packages/dsw-document-worker/CHANGELOG.md +++ b/packages/dsw-document-worker/CHANGELOG.md @@ -7,6 +7,11 @@ to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [Unreleased] +### Changed + +- Document context metamodel 19.1; contexts of 19.0 are still rendered, newer minor versions are + rejected + ## [5.1.0] diff --git a/packages/dsw-document-worker/dsw/document_worker/worker.py b/packages/dsw-document-worker/dsw/document_worker/worker.py index 85add265..aa0b000c 100644 --- a/packages/dsw-document-worker/dsw/document_worker/worker.py +++ b/packages/dsw-document-worker/dsw/document_worker/worker.py @@ -231,7 +231,8 @@ def check_compliance(self): raise JobError( job_id=self.doc_uuid, msg=(f'Unsupported document context metamodel version {shown}, expected ' - f'{DOCUMENT_TEMPLATE_METAMODEL_VERSION.major}.x. Regenerate the document.'), + f'{DOCUMENT_TEMPLATE_METAMODEL_VERSION.major}.0 to ' + f'{DOCUMENT_TEMPLATE_METAMODEL_VERSION}. Regenerate the document.'), skip_reporting=True, ) from e diff --git a/packages/dsw-document-worker/tests/test_check_compliance.py b/packages/dsw-document-worker/tests/test_check_compliance.py index 142cdc54..14550a7d 100644 --- a/packages/dsw-document-worker/tests/test_check_compliance.py +++ b/packages/dsw-document-worker/tests/test_check_compliance.py @@ -20,7 +20,7 @@ def make_job(doc_context: dict, project_uuid: str | None = None, db=None) -> Job return job -@pytest.mark.parametrize('version', ['19.0', '19', '19.4']) +@pytest.mark.parametrize('version', ['19.0', '19', '19.1']) def test_current_metamodel_is_accepted(version): make_job({'metamodelVersion': version}).check_compliance() @@ -28,6 +28,7 @@ def test_current_metamodel_is_accepted(version): @pytest.mark.parametrize(('version', 'shown'), [ ('18.3', '18.3'), ('17', '17.0'), + ('19.2', '19.2'), ('20.0', '20.0'), (None, 'missing'), ('x.y', 'missing'), @@ -38,7 +39,7 @@ def test_other_metamodel_asks_for_regeneration(version, shown): make_job(context).check_compliance() # exactly what ends up in the document's worker_log assert error.value.db_message() == ( - f'Unsupported document context metamodel version {shown}, expected 19.x. ' + f'Unsupported document context metamodel version {shown}, expected 19.0 to 19.1. ' 'Regenerate the document.') assert error.value.skip_reporting # an expected condition, not a bug to report diff --git a/packages/dsw-document-worker/tests/test_metamodel_version.py b/packages/dsw-document-worker/tests/test_metamodel_version.py index aa445e99..09339183 100644 --- a/packages/dsw-document-worker/tests/test_metamodel_version.py +++ b/packages/dsw-document-worker/tests/test_metamodel_version.py @@ -8,12 +8,14 @@ from dsw.models.document_context.graph import check_metamodel_version -@pytest.mark.parametrize('version', ['19.0', '19', '19.9', '19.10']) +@pytest.mark.parametrize('version', ['19.0', '19', '19.1']) def test_accepted(version): check_metamodel_version(version) @pytest.mark.parametrize(('version', 'message'), [ + ('19.2', 'expected at most 1 minor version'), + ('19.10', 'expected at most 1 minor version'), ('18.3', 'expected major version 19'), ('17.9', 'expected major version 19'), ('20.0', 'expected major version 19'), diff --git a/packages/dsw-models/CHANGELOG.md b/packages/dsw-models/CHANGELOG.md index 8ee80d3a..c5c7f24d 100644 --- a/packages/dsw-models/CHANGELOG.md +++ b/packages/dsw-models/CHANGELOG.md @@ -7,6 +7,23 @@ to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [Unreleased] +### Added + +- Knowledge model metamodel 21: optional `prefill` of questions (`QuestionPrefill`) in the flat + model, tree, events, compiler, squash and diff, `prefill_source` in the graph, and the + migration from 20 +- Provenance of project events and replies (`PrefillProvenance`) +- `DeleteItemEvent` in project events, changes and compiled project content +- `Question.prefill` and `Reply.provenance` in the document context object model + +### Changed + +- `KM_METAMODEL_VERSION` is `21`: bundles of version 20 have to be upgraded with `migrate_bundle` + before they are loaded +- `DOCUMENT_TEMPLATE_METAMODEL_VERSION` is `19.1` +- `check_metamodel_version` accepts every minor version up to the current one, so contexts made + before an upgrade still render, and rejects newer ones + ## [5.1.0] diff --git a/packages/dsw-models/README.md b/packages/dsw-models/README.md index 8742c7a6..ae4d5827 100644 --- a/packages/dsw-models/README.md +++ b/packages/dsw-models/README.md @@ -39,11 +39,12 @@ keys unless asked otherwise: ```python import json +from dsw.models.knowledge_model.migrations import migrate_bundle from dsw.models.knowledge_model.package import KnowledgeModelBundle from dsw.models.strictness import UnknownKeys, load with open('dsw_root_2.8.1.km') as file: - bundle = load(KnowledgeModelBundle, json.load(file)) # strict + bundle = load(KnowledgeModelBundle, migrate_bundle(json.load(file))) # strict # load(KnowledgeModelBundle, data, unknown_keys=UnknownKeys.IGNORE) drops unknown keys data = bundle.to_json_data() # JSON-compatible data as the server writes it diff --git a/packages/dsw-models/dsw/models/document_context/graph.py b/packages/dsw-models/dsw/models/document_context/graph.py index 07971a4c..b8b0b2fe 100644 --- a/packages/dsw-models/dsw/models/document_context/graph.py +++ b/packages/dsw-models/dsw/models/document_context/graph.py @@ -24,7 +24,7 @@ def check_metamodel_version(metamodel_version: str): - """Accept the same major version and at least the current minor version.""" + """Accept the same major version up to the current minor version.""" current = DOCUMENT_TEMPLATE_METAMODEL_VERSION try: version = MetamodelVersion.parse(metamodel_version) @@ -33,9 +33,9 @@ def check_metamodel_version(metamodel_version: str): if version.major != current.major: raise ValueError(f'Unsupported metamodel version: {metamodel_version} ' f'(expected major version {current.major})') - if version.minor < current.minor: + if version.minor > current.minor: raise ValueError(f'Unsupported metamodel version: {metamodel_version} ' - f'(expected at least {current.minor} minor version)') + f'(expected at most {current.minor} minor version)') def render_markdown(md_text: str, sanitize: bool = True): @@ -609,6 +609,24 @@ def load(data: dict, **options): ) +class ReplyProvenance: + + def __init__(self, *, provenance_type: str, source_path: str, integration_uuid: str): + self.type = provenance_type + self.source_path = source_path + self.integration_uuid = integration_uuid + + @staticmethod + def load(data: dict | None, **options): + if data is None: + return None + return ReplyProvenance( + provenance_type=data['type'], + source_path=data['sourcePath'], + integration_uuid=data['integrationUuid'], + ) + + class Reply(abc.ABC): def __init__(self, *, path: str, created_at: datetime, @@ -617,6 +635,7 @@ def __init__(self, *, path: str, created_at: datetime, self.created_at = created_at self.created_by = created_by self.type = reply_type + self.provenance: ReplyProvenance | None = None self.question: Question | None = None self.fragments: list[str] = path.split('.') @@ -1023,6 +1042,24 @@ def load(data: dict, **options): ) +class QuestionPrefill: + + def __init__(self, *, source_question_uuid: str, template: str, integration_only: bool): + self.source_question_uuid = source_question_uuid + self.template = template + self.integration_only = integration_only + + @staticmethod + def load(data: dict | None, **options): + if data is None: + return None + return QuestionPrefill( + source_question_uuid=data['sourceQuestionUuid'], + template=data['template'], + integration_only=data['integrationOnly'], + ) + + class Question(abc.ABC): def __init__(self, *, uuid: str, q_type: str, title: str, text: str | None, @@ -1038,6 +1075,7 @@ def __init__(self, *, uuid: str, q_type: str, title: str, text: str | None, self.expert_uuids = expert_uuids self.required_phase_uuid = required_phase_uuid self.annotations = annotations + self.prefill: QuestionPrefill | None = None self.is_required: bool | None = None self.parent: Chapter | ListQuestion | Answer | None = None @@ -1562,7 +1600,9 @@ def _load_question(data: dict, **options): question_class = _QUESTION_TYPES.get(question_type) if question_class is None: raise ValueError(f'Unknown question type: {question_type}') - return question_class.load(data, **options) + question = question_class.load(data, **options) + question.prefill = QuestionPrefill.load(data.get('prefill'), **options) # missing in 19.0 + return question def _load_reference(data: dict, **options): @@ -1586,7 +1626,9 @@ def _load_reply(path: str, data: dict, **options): reply_class = _REPLY_TYPES.get(reply_type) if reply_class is None: raise ValueError(f'Unknown reply type: {reply_type}') - return reply_class.load(path, data, **options) + reply = reply_class.load(path, data, **options) + reply.provenance = ReplyProvenance.load(data.get('provenance'), **options) # missing in 19.0 + return reply class KnowledgeModelEntities: diff --git a/packages/dsw-models/dsw/models/document_context/wire.py b/packages/dsw-models/dsw/models/document_context/wire.py index bf7ba5de..83577598 100644 --- a/packages/dsw-models/dsw/models/document_context/wire.py +++ b/packages/dsw-models/dsw/models/document_context/wire.py @@ -1,4 +1,4 @@ -"""Document context (metamodel 19.0) as the backend sends it. +"""Document context (metamodel 19.1) as the backend sends it. The same shape is the body of the ``generateDocument`` persistent command (with ``document``) and the response of the document context endpoints (``document`` is ``null``). Exactly one of diff --git a/packages/dsw-models/dsw/models/document_template/migrations.py b/packages/dsw-models/dsw/models/document_template/migrations.py index 5b42d5e6..1005488c 100644 --- a/packages/dsw-models/dsw/models/document_template/migrations.py +++ b/packages/dsw-models/dsw/models/document_template/migrations.py @@ -11,6 +11,7 @@ 17.0 ``metamodelVersion`` became a ``"major.minor"`` string 18.3 ``language`` added (default ``"en"``) 19.0 no descriptor change (single ``id``, see below); the document context was restructured +19.1 no descriptor change; questions have ``prefill`` and replies ``provenance`` in the context ======== ============================================================================= Whatever the version, the identity is upgraded to the single ``id`` of Wizard 5.0, as the diff --git a/packages/dsw-models/dsw/models/knowledge_model/common.py b/packages/dsw-models/dsw/models/knowledge_model/common.py index e91206e0..5c16bcc8 100644 --- a/packages/dsw-models/dsw/models/knowledge_model/common.py +++ b/packages/dsw-models/dsw/models/knowledge_model/common.py @@ -15,6 +15,16 @@ class MetricMeasure(BaseModel): weight: float +class QuestionPrefill(BaseModel): + """The question is prefilled from the item picked in the source question.""" + + source_question_uuid: UUID + #: Jinja template, its only variable is ``item`` + template: str + #: read-only in the questionnaire, always follows its source + integration_only: bool + + QuestionValueType = typing.Literal[ 'StringQuestionValueType', 'NumberQuestionValueType', diff --git a/packages/dsw-models/dsw/models/knowledge_model/compiler.py b/packages/dsw-models/dsw/models/knowledge_model/compiler.py index 2cdae446..0a397373 100644 --- a/packages/dsw-models/dsw/models/knowledge_model/compiler.py +++ b/packages/dsw-models/dsw/models/knowledge_model/compiler.py @@ -495,6 +495,8 @@ def convert_entity(entity: typing.Any, target_type: type) -> typing.Any: """Change the type of a question, reference or integration like the backend does.""" if issubclass(target_type, flat.QuestionBase): data = {name: getattr(entity, name) for name in _QUESTION_SHARED_FIELDS} + if target_type not in (flat.ItemSelectQuestion, flat.FileQuestion): + data['prefill'] = entity.prefill # the other two cannot be prefilled if target_type is flat.IntegrationQuestion: data['integration_uuid'] = NULL_UUID return target_type(uuid=entity.uuid, **data) diff --git a/packages/dsw-models/dsw/models/knowledge_model/events.py b/packages/dsw-models/dsw/models/knowledge_model/events.py index c30ccf4c..327e355a 100644 --- a/packages/dsw-models/dsw/models/knowledge_model/events.py +++ b/packages/dsw-models/dsw/models/knowledge_model/events.py @@ -7,7 +7,13 @@ import pydantic from ..common import Annotations, BaseModel, JsonValue, KeyValue, Timestamp -from .common import MetricMeasure, QuestionValidation, QuestionValueType, TypeHintExchange +from .common import ( + MetricMeasure, + QuestionPrefill, + QuestionValidation, + QuestionValueType, + TypeHintExchange, +) class EditEventField[T](BaseModel): @@ -116,6 +122,7 @@ class AddQuestionEventContentBase(EventContent): required_phase_uuid: UUID | None = None annotations: Annotations tag_uuids: list[UUID] + prefill: QuestionPrefill | None = None class AddOptionsQuestionEventContent(AddQuestionEventContentBase): @@ -174,6 +181,7 @@ class EditQuestionEventContentBase(EventContent): tag_uuids: EditEventField[list[UUID]] expert_uuids: EditEventField[list[UUID]] reference_uuids: EditEventField[list[UUID]] + prefill: EditEventField[QuestionPrefill | None] class EditOptionsQuestionEventContent(EditQuestionEventContentBase): diff --git a/packages/dsw-models/dsw/models/knowledge_model/flat.py b/packages/dsw-models/dsw/models/knowledge_model/flat.py index 6a5e1b05..56d5b8e6 100644 --- a/packages/dsw-models/dsw/models/knowledge_model/flat.py +++ b/packages/dsw-models/dsw/models/knowledge_model/flat.py @@ -7,7 +7,13 @@ import pydantic from ..common import Annotations, BaseModel, JsonValue, KeyValue -from .common import MetricMeasure, QuestionValidation, QuestionValueType, TypeHintExchange +from .common import ( + MetricMeasure, + QuestionPrefill, + QuestionValidation, + QuestionValueType, + TypeHintExchange, +) class Entity(BaseModel): @@ -28,6 +34,7 @@ class QuestionBase(Entity): tag_uuids: list[UUID] = pydantic.Field(default_factory=list) expert_uuids: list[UUID] = pydantic.Field(default_factory=list) reference_uuids: list[UUID] = pydantic.Field(default_factory=list) + prefill: QuestionPrefill | None = None class OptionsQuestion(QuestionBase): diff --git a/packages/dsw-models/dsw/models/knowledge_model/graph.py b/packages/dsw-models/dsw/models/knowledge_model/graph.py index 73a6bb99..1c3d85b9 100644 --- a/packages/dsw-models/dsw/models/knowledge_model/graph.py +++ b/packages/dsw-models/dsw/models/knowledge_model/graph.py @@ -138,7 +138,7 @@ def children(self) -> list[Node]: class Question(Node): - __slots__ = ('experts', 'references', 'required_phase', 'tags') + __slots__ = ('experts', 'prefill_source', 'references', 'required_phase', 'tags') kind = 'question' entity: flat.QuestionBase @@ -150,6 +150,9 @@ def _link(self) -> None: 'expertUuids', self.entity.expert_uuids, Expert) self.references: list[Reference] = self._resolve( 'referenceUuids', self.entity.reference_uuids, Reference) + prefill = self.entity.prefill + self.prefill_source: Question | None = self._resolve_optional( + 'prefill', prefill.source_question_uuid if prefill else None, Question) @property def question_type(self) -> str: diff --git a/packages/dsw-models/dsw/models/knowledge_model/migrations/steps.py b/packages/dsw-models/dsw/models/knowledge_model/migrations/steps.py index 3dc2f7e8..f61b0148 100644 --- a/packages/dsw-models/dsw/models/knowledge_model/migrations/steps.py +++ b/packages/dsw-models/dsw/models/knowledge_model/migrations/steps.py @@ -381,8 +381,21 @@ def step_19(event: typing.Any, ctx: MigrationContext) -> list[typing.Any]: return [{**event, 'content': content}] +# 20 → 21: prefill of questions +def step_20(event: typing.Any, ctx: MigrationContext) -> list[typing.Any]: + if not isinstance(event, dict): + return [event] + content = event.get('content', {}) + event_type = _event_type(content) + if event_type in ('AddQuestionEvent', 'EditQuestionEvent'): + prefill = None if event_type == 'AddQuestionEvent' else _unchanged() + event = {**event, 'content': {**content, 'prefill': prefill}} + return [event] + + STEPS: dict[int, Step] = { 1: step_01, 2: step_02, 3: step_03, 4: step_noop, 5: step_noop, 6: step_06, 7: step_07, 8: step_08, 9: step_09, 10: step_10, 11: step_11, 12: step_noop, 13: step_noop, 14: step_14, 15: step_noop, 16: step_16, 17: step_17, 18: step_18, 19: step_19, + 20: step_20, } diff --git a/packages/dsw-models/dsw/models/knowledge_model/squash.py b/packages/dsw-models/dsw/models/knowledge_model/squash.py index 88d88375..868e4e8c 100644 --- a/packages/dsw-models/dsw/models/knowledge_model/squash.py +++ b/packages/dsw-models/dsw/models/knowledge_model/squash.py @@ -42,7 +42,8 @@ class _Rules(typing.NamedTuple): reorder: typing.Literal['never', 'same_entity', 'always'] -_QUESTION_BLOCKING = ('required_phase_uuid', 'tag_uuids', 'expert_uuids', 'reference_uuids') +_QUESTION_BLOCKING = ('required_phase_uuid', 'tag_uuids', 'expert_uuids', 'reference_uuids', + 'prefill') _QUESTION_SAME_ENTITY = ('tag_uuids', 'expert_uuids', 'reference_uuids') _NONE: frozenset[str] = frozenset() diff --git a/packages/dsw-models/dsw/models/knowledge_model/tree.py b/packages/dsw-models/dsw/models/knowledge_model/tree.py index f22666de..d313b9b6 100644 --- a/packages/dsw-models/dsw/models/knowledge_model/tree.py +++ b/packages/dsw-models/dsw/models/knowledge_model/tree.py @@ -15,7 +15,7 @@ from ..common import Annotations, BaseModel from . import flat -from .common import MetricMeasure, QuestionValidation, QuestionValueType +from .common import MetricMeasure, QuestionPrefill, QuestionValidation, QuestionValueType class Entity(BaseModel): @@ -52,6 +52,7 @@ class QuestionBase(Entity): tag_uuids: list[UUID] = pydantic.Field(default_factory=list) experts: list[Expert] = pydantic.Field(default_factory=list) references: list[Reference] = pydantic.Field(default_factory=list) + prefill: QuestionPrefill | None = None class Answer(Entity): diff --git a/packages/dsw-models/dsw/models/project/changes.py b/packages/dsw-models/dsw/models/project/changes.py index f6e57734..2859683b 100644 --- a/packages/dsw-models/dsw/models/project/changes.py +++ b/packages/dsw-models/dsw/models/project/changes.py @@ -7,7 +7,7 @@ import pydantic from ..common import BaseModel, UserSuggestion -from .replies import ReplyValue +from .replies import ProjectEventProvenance, ReplyValue class ChangeBase(BaseModel): @@ -22,20 +22,33 @@ class PathChangeBase(ChangeBase): class SetReplyEvent(PathChangeBase): type: typing.Literal['SetReplyEvent'] = 'SetReplyEvent' value: ReplyValue + provenance: ProjectEventProvenance | None = None class ClearReplyEvent(PathChangeBase): type: typing.Literal['ClearReplyEvent'] = 'ClearReplyEvent' + provenance: ProjectEventProvenance | None = None class SetPhaseEvent(ChangeBase): type: typing.Literal['SetPhaseEvent'] = 'SetPhaseEvent' phase_uuid: UUID | None = None + provenance: ProjectEventProvenance | None = None class SetLabelsEvent(PathChangeBase): type: typing.Literal['SetLabelsEvent'] = 'SetLabelsEvent' value: list[UUID] + provenance: ProjectEventProvenance | None = None + + +class DeleteItemEvent(PathChangeBase): + """Removes an item of the list question at ``path`` with everything answered in it.""" + + type: typing.Literal['DeleteItemEvent'] = 'DeleteItemEvent' + item_uuid: UUID + item_title: str | None = None + provenance: ProjectEventProvenance | None = None class ResolveCommentThreadEvent(PathChangeBase): @@ -94,6 +107,7 @@ class DeleteCommentEvent(PathChangeBase): | ClearReplyEvent | SetPhaseEvent | SetLabelsEvent + | DeleteItemEvent | ResolveCommentThreadEvent | ReopenCommentThreadEvent | AssignCommentThreadEvent diff --git a/packages/dsw-models/dsw/models/project/content.py b/packages/dsw-models/dsw/models/project/content.py index 0c235b83..fe84e8bd 100644 --- a/packages/dsw-models/dsw/models/project/content.py +++ b/packages/dsw-models/dsw/models/project/content.py @@ -10,8 +10,15 @@ import pydantic from ..common import BaseModel -from .events import ClearReplyEvent, SetLabelsEvent, SetPhaseEvent, SetReplyEvent -from .replies import Reply +from .common import PATH_SEPARATOR +from .events import ( + ClearReplyEvent, + DeleteItemEvent, + SetLabelsEvent, + SetPhaseEvent, + SetReplyEvent, +) +from .replies import ItemListReplyValue, Reply if typing.TYPE_CHECKING: @@ -36,7 +43,8 @@ def compile_project_events( for event in events: if isinstance(event, SetReplyEvent): content.replies[event.path] = Reply( - value=event.value, created_by=event.created_by, created_at=event.created_at) + value=event.value, created_by=event.created_by, created_at=event.created_at, + provenance=event.provenance) elif isinstance(event, ClearReplyEvent): content.replies.pop(event.path, None) elif isinstance(event, SetPhaseEvent): @@ -46,6 +54,24 @@ def compile_project_events( content.labels[event.path] = list(event.value) else: content.labels.pop(event.path, None) + elif isinstance(event, DeleteItemEvent): + _delete_item(content, event) if until is not None and event.uuid == until: break return content + + +def _delete_item(content: ProjectContent, event: DeleteItemEvent) -> None: + prefix = PATH_SEPARATOR.join((event.path, str(event.item_uuid), '')) + for entries in (content.replies, content.labels): + for path in [path for path in entries if path.startswith(prefix)]: + del entries[path] + reply = content.replies.get(event.path) + if reply is None: + return + value = reply.value + if isinstance(value, ItemListReplyValue): + value = ItemListReplyValue(value=[uuid for uuid in value.value if uuid != event.item_uuid]) + content.replies[event.path] = Reply( + value=value, created_by=event.created_by, created_at=event.created_at, + provenance=event.provenance) diff --git a/packages/dsw-models/dsw/models/project/events.py b/packages/dsw-models/dsw/models/project/events.py index fce2badb..b64665f3 100644 --- a/packages/dsw-models/dsw/models/project/events.py +++ b/packages/dsw-models/dsw/models/project/events.py @@ -11,7 +11,7 @@ from ..common import BaseModel, Timestamp, UserSuggestion from .common import PATH_SEPARATOR -from .replies import ReplyValue +from .replies import ProjectEventProvenance, ReplyValue class ProjectEventBase(BaseModel): @@ -32,20 +32,33 @@ def path_parts(self) -> list[str]: class SetReplyEvent(PathEventBase): type: typing.Literal['SetReplyEvent'] = 'SetReplyEvent' value: ReplyValue + provenance: ProjectEventProvenance | None = None class ClearReplyEvent(PathEventBase): type: typing.Literal['ClearReplyEvent'] = 'ClearReplyEvent' + provenance: ProjectEventProvenance | None = None class SetPhaseEvent(ProjectEventBase): type: typing.Literal['SetPhaseEvent'] = 'SetPhaseEvent' phase_uuid: UUID | None = None + provenance: ProjectEventProvenance | None = None class SetLabelsEvent(PathEventBase): type: typing.Literal['SetLabelsEvent'] = 'SetLabelsEvent' value: list[UUID] + provenance: ProjectEventProvenance | None = None + + +class DeleteItemEvent(PathEventBase): + """Removes an item of the list question at ``path`` with everything answered in it.""" + + type: typing.Literal['DeleteItemEvent'] = 'DeleteItemEvent' + item_uuid: UUID + item_title: str | None = None + provenance: ProjectEventProvenance | None = None class ResolveCommentThreadEvent(PathEventBase): @@ -96,7 +109,7 @@ class DeleteCommentEvent(PathEventBase): #: Events that change project content; the only ones the backend stores. ProjectEvent = typing.Annotated[ - SetReplyEvent | ClearReplyEvent | SetPhaseEvent | SetLabelsEvent, + SetReplyEvent | ClearReplyEvent | SetPhaseEvent | SetLabelsEvent | DeleteItemEvent, pydantic.Field(discriminator='type'), ] @@ -106,6 +119,7 @@ class DeleteCommentEvent(PathEventBase): | ClearReplyEvent | SetPhaseEvent | SetLabelsEvent + | DeleteItemEvent | ResolveCommentThreadEvent | ReopenCommentThreadEvent | AssignCommentThreadEvent diff --git a/packages/dsw-models/dsw/models/project/replies.py b/packages/dsw-models/dsw/models/project/replies.py index 5075d1a1..6c69c435 100644 --- a/packages/dsw-models/dsw/models/project/replies.py +++ b/packages/dsw-models/dsw/models/project/replies.py @@ -73,10 +73,22 @@ class FileReplyValue(BaseModel): ] +class PrefillProvenance(BaseModel): + type: typing.Literal['PrefillProvenanceType'] = 'PrefillProvenanceType' + #: path of the originating integration question + source_path: str + integration_uuid: UUID + + +#: Where a project event comes from; the backend plans more variants. +ProjectEventProvenance = PrefillProvenance + + class Reply(BaseModel): value: ReplyValue created_by: UserSuggestion | None = None created_at: Timestamp + provenance: ProjectEventProvenance | None = None Replies = dict[str, Reply] diff --git a/packages/dsw-models/dsw/models/versions.py b/packages/dsw-models/dsw/models/versions.py index 92ffc12c..531b11a2 100644 --- a/packages/dsw-models/dsw/models/versions.py +++ b/packages/dsw-models/dsw/models/versions.py @@ -31,5 +31,5 @@ def __str__(self) -> str: return f'{self.major}.{self.minor}' -KM_METAMODEL_VERSION = 20 -DOCUMENT_TEMPLATE_METAMODEL_VERSION = MetamodelVersion(19, 0) +KM_METAMODEL_VERSION = 21 +DOCUMENT_TEMPLATE_METAMODEL_VERSION = MetamodelVersion(19, 1) diff --git a/packages/dsw-models/examples/diff_kms.py b/packages/dsw-models/examples/diff_kms.py index cd467bf1..9310db34 100644 --- a/packages/dsw-models/examples/diff_kms.py +++ b/packages/dsw-models/examples/diff_kms.py @@ -20,6 +20,7 @@ from dsw.models.knowledge_model.convert import prune_unreachable from dsw.models.knowledge_model.diff import diff from dsw.models.knowledge_model.events import EditEventField, Event +from dsw.models.knowledge_model.migrations import migrate_bundle from dsw.models.knowledge_model.package import KnowledgeModelBundle from dsw.models.knowledge_model.squash import squash from dsw.models.knowledge_model.validation import location @@ -52,7 +53,8 @@ def bundle_versions(path: pathlib.Path, old_reference: str, new_reference: str | None) -> tuple[flat.KnowledgeModel, flat.KnowledgeModel]: opener = gzip.open if path.suffix == '.gz' else open with opener(path, 'rt', encoding='utf-8') as file: - bundle = load(KnowledgeModelBundle, json.load(file), unknown_keys=UnknownKeys.IGNORE) + bundle = load(KnowledgeModelBundle, migrate_bundle(json.load(file)), + unknown_keys=UnknownKeys.IGNORE) # compiled knowledge models keep entities orphaned by deletions, as the server does; they # are not part of either version, so leave them out rather than diff them away return (prune_unreachable(compile_bundle(bundle, old_reference)), diff --git a/packages/dsw-models/tests/conftest.py b/packages/dsw-models/tests/conftest.py index d5c5b8db..5bfe7412 100644 --- a/packages/dsw-models/tests/conftest.py +++ b/packages/dsw-models/tests/conftest.py @@ -4,6 +4,8 @@ import pytest +from dsw.models.knowledge_model.migrations import migrate_bundle + FIXTURES_DIR = pathlib.Path(__file__).parent / 'fixtures' REFERENCE_DIR = FIXTURES_DIR / 'reference' @@ -12,11 +14,16 @@ REFERENCE_BUNDLES = sorted(path.name for path in REFERENCE_DIR.glob('*.km.gz')) -def load_reference(name: str): +def load_raw_reference(name: str): with gzip.open(REFERENCE_DIR / name, 'rt', encoding='utf-8') as file: return json.load(file) +def load_reference(name: str): + """The bundle upgraded to the current metamodel version.""" + return migrate_bundle(load_raw_reference(name)) + + def load_synthetic(name: str): return json.loads((SYNTHETIC_DIR / name).read_text(encoding='utf-8')) diff --git a/packages/dsw-models/tests/fixtures/synthetic/document_context.json b/packages/dsw-models/tests/fixtures/synthetic/document_context.json index 006d6f74..f76b0275 100644 --- a/packages/dsw-models/tests/fixtures/synthetic/document_context.json +++ b/packages/dsw-models/tests/fixtures/synthetic/document_context.json @@ -1,6 +1,6 @@ { - "metamodelVersion": "19.0", - "hash": "sha256:45f63ec9da12ca4b33e74dceda9949d376979a90d7e6db2c8b66393ee76f527c", + "metamodelVersion": "19.1", + "hash": "sha256:b93a3289ce7293cb6da523c7b76aa1327bccd8ae742dcfd7b16683dca8318fdd", "workspace": { "uuid": "90000000-0000-0000-0000-000000000001", "name": "Faculty of Science", @@ -99,7 +99,8 @@ "imageUrl": null, "affiliation": "Example University" }, - "createdAt": "2026-09-14T10:00:00Z" + "createdAt": "2026-09-14T10:00:00Z", + "provenance": null }, "00000000-0000-0000-0000-000000000101.00000000-0000-0000-0000-000000000201.00000000-0000-0000-0000-000000000301.00000000-0000-0000-0000-000000000208": { "value": { @@ -107,7 +108,12 @@ "value": "42" }, "createdBy": null, - "createdAt": "2026-09-14T10:00:01Z" + "createdAt": "2026-09-14T10:00:01Z", + "provenance": { + "type": "PrefillProvenanceType", + "sourcePath": "00000000-0000-0000-0000-000000000101.00000000-0000-0000-0000-000000000205", + "integrationUuid": "00000000-0000-0000-0000-000000000701" + } }, "00000000-0000-0000-0000-000000000101.00000000-0000-0000-0000-000000000203": { "value": { @@ -118,7 +124,8 @@ ] }, "createdBy": null, - "createdAt": "2026-09-14T10:00:03Z" + "createdAt": "2026-09-14T10:00:03Z", + "provenance": null }, "00000000-0000-0000-0000-000000000101.00000000-0000-0000-0000-000000000205": { "value": { @@ -129,7 +136,8 @@ } }, "createdBy": null, - "createdAt": "2026-09-14T10:00:05Z" + "createdAt": "2026-09-14T10:00:05Z", + "provenance": null }, "00000000-0000-0000-0000-000000000101.00000000-0000-0000-0000-000000000206": { "value": { @@ -137,7 +145,8 @@ "value": "50000000-0000-0000-0000-000000000001" }, "createdBy": null, - "createdAt": "2026-09-14T10:00:06Z" + "createdAt": "2026-09-14T10:00:06Z", + "provenance": null }, "00000000-0000-0000-0000-000000000101.00000000-0000-0000-0000-000000000207": { "value": { @@ -145,7 +154,8 @@ "value": "60000000-0000-0000-0000-000000000001" }, "createdBy": null, - "createdAt": "2026-09-14T10:00:07Z" + "createdAt": "2026-09-14T10:00:07Z", + "provenance": null }, "00000000-0000-0000-0000-000000000101.00000000-0000-0000-0000-000000000203.50000000-0000-0000-0000-000000000001.00000000-0000-0000-0000-000000000204": { "value": { @@ -153,7 +163,8 @@ "value": "first item" }, "createdBy": null, - "createdAt": "2026-09-14T10:01:00Z" + "createdAt": "2026-09-14T10:01:00Z", + "provenance": null }, "00000000-0000-0000-0000-000000000101.00000000-0000-0000-0000-000000000203.50000000-0000-0000-0000-000000000002.00000000-0000-0000-0000-000000000204": { "value": { @@ -161,7 +172,8 @@ "value": "second item" }, "createdBy": null, - "createdAt": "2026-09-14T10:01:01Z" + "createdAt": "2026-09-14T10:01:01Z", + "provenance": null } }, "labels": { @@ -342,6 +354,7 @@ "00000000-0000-0000-0000-000000000502", "00000000-0000-0000-0000-000000000503" ], + "prefill": null, "answerUuids": [ "00000000-0000-0000-0000-000000000301", "00000000-0000-0000-0000-000000000302" @@ -357,6 +370,7 @@ "tagUuids": [], "expertUuids": [], "referenceUuids": [], + "prefill": null, "choiceUuids": [ "00000000-0000-0000-0000-000000000601" ] @@ -371,6 +385,7 @@ "tagUuids": [], "expertUuids": [], "referenceUuids": [], + "prefill": null, "itemTemplateQuestionUuids": [ "00000000-0000-0000-0000-000000000204" ] @@ -385,6 +400,7 @@ "tagUuids": [], "expertUuids": [], "referenceUuids": [], + "prefill": null, "valueType": "StringQuestionValueType", "validations": [ { @@ -453,6 +469,7 @@ "tagUuids": [], "expertUuids": [], "referenceUuids": [], + "prefill": null, "integrationUuid": "00000000-0000-0000-0000-000000000701", "variables": { "domain": "biology" @@ -468,6 +485,7 @@ "tagUuids": [], "expertUuids": [], "referenceUuids": [], + "prefill": null, "listQuestionUuid": "00000000-0000-0000-0000-000000000203" }, "00000000-0000-0000-0000-000000000207": { @@ -480,6 +498,7 @@ "tagUuids": [], "expertUuids": [], "referenceUuids": [], + "prefill": null, "maxSize": 1048576, "fileTypes": "application/pdf" }, @@ -493,6 +512,11 @@ "tagUuids": [], "expertUuids": [], "referenceUuids": [], + "prefill": { + "sourceQuestionUuid": "00000000-0000-0000-0000-000000000205", + "template": "{{ item.name }}", + "integrationOnly": true + }, "valueType": "NumberQuestionValueType", "validations": [] } diff --git a/packages/dsw-models/tests/fixtures/synthetic/document_context_km_editor.json b/packages/dsw-models/tests/fixtures/synthetic/document_context_km_editor.json index 73851e2a..fd70e47c 100644 --- a/packages/dsw-models/tests/fixtures/synthetic/document_context_km_editor.json +++ b/packages/dsw-models/tests/fixtures/synthetic/document_context_km_editor.json @@ -1,6 +1,6 @@ { - "metamodelVersion": "19.0", - "hash": "sha256:2373fe054e0937403afa3c2cc63c0c47bf86a9c743330d28cef92b0e93a2a33b", + "metamodelVersion": "19.1", + "hash": "sha256:3acbb298d08c95580994303b20a89485971cece10542eb3b2c80206911a2ad6b", "workspace": { "uuid": "90000000-0000-0000-0000-000000000001", "name": "Faculty of Science", @@ -48,7 +48,8 @@ "imageUrl": null, "affiliation": "Example University" }, - "createdAt": "2026-09-14T10:00:00Z" + "createdAt": "2026-09-14T10:00:00Z", + "provenance": null }, "00000000-0000-0000-0000-000000000101.00000000-0000-0000-0000-000000000201.00000000-0000-0000-0000-000000000301.00000000-0000-0000-0000-000000000208": { "value": { @@ -56,7 +57,12 @@ "value": "42" }, "createdBy": null, - "createdAt": "2026-09-14T10:00:01Z" + "createdAt": "2026-09-14T10:00:01Z", + "provenance": { + "type": "PrefillProvenanceType", + "sourcePath": "00000000-0000-0000-0000-000000000101.00000000-0000-0000-0000-000000000205", + "integrationUuid": "00000000-0000-0000-0000-000000000701" + } }, "00000000-0000-0000-0000-000000000101.00000000-0000-0000-0000-000000000203": { "value": { @@ -67,7 +73,8 @@ ] }, "createdBy": null, - "createdAt": "2026-09-14T10:00:03Z" + "createdAt": "2026-09-14T10:00:03Z", + "provenance": null }, "00000000-0000-0000-0000-000000000101.00000000-0000-0000-0000-000000000205": { "value": { @@ -78,7 +85,8 @@ } }, "createdBy": null, - "createdAt": "2026-09-14T10:00:05Z" + "createdAt": "2026-09-14T10:00:05Z", + "provenance": null }, "00000000-0000-0000-0000-000000000101.00000000-0000-0000-0000-000000000206": { "value": { @@ -86,7 +94,8 @@ "value": "50000000-0000-0000-0000-000000000001" }, "createdBy": null, - "createdAt": "2026-09-14T10:00:06Z" + "createdAt": "2026-09-14T10:00:06Z", + "provenance": null }, "00000000-0000-0000-0000-000000000101.00000000-0000-0000-0000-000000000203.50000000-0000-0000-0000-000000000001.00000000-0000-0000-0000-000000000204": { "value": { @@ -94,7 +103,8 @@ "value": "first item" }, "createdBy": null, - "createdAt": "2026-09-14T10:01:00Z" + "createdAt": "2026-09-14T10:01:00Z", + "provenance": null }, "00000000-0000-0000-0000-000000000101.00000000-0000-0000-0000-000000000203.50000000-0000-0000-0000-000000000002.00000000-0000-0000-0000-000000000204": { "value": { @@ -102,7 +112,8 @@ "value": "second item" }, "createdBy": null, - "createdAt": "2026-09-14T10:01:01Z" + "createdAt": "2026-09-14T10:01:01Z", + "provenance": null } }, "labels": {}, @@ -255,6 +266,7 @@ "00000000-0000-0000-0000-000000000502", "00000000-0000-0000-0000-000000000503" ], + "prefill": null, "answerUuids": [ "00000000-0000-0000-0000-000000000301", "00000000-0000-0000-0000-000000000302" @@ -270,6 +282,7 @@ "tagUuids": [], "expertUuids": [], "referenceUuids": [], + "prefill": null, "choiceUuids": [ "00000000-0000-0000-0000-000000000601" ] @@ -284,6 +297,7 @@ "tagUuids": [], "expertUuids": [], "referenceUuids": [], + "prefill": null, "itemTemplateQuestionUuids": [ "00000000-0000-0000-0000-000000000204" ] @@ -298,6 +312,7 @@ "tagUuids": [], "expertUuids": [], "referenceUuids": [], + "prefill": null, "valueType": "StringQuestionValueType", "validations": [ { @@ -366,6 +381,7 @@ "tagUuids": [], "expertUuids": [], "referenceUuids": [], + "prefill": null, "integrationUuid": "00000000-0000-0000-0000-000000000701", "variables": { "domain": "biology" @@ -381,6 +397,7 @@ "tagUuids": [], "expertUuids": [], "referenceUuids": [], + "prefill": null, "listQuestionUuid": "00000000-0000-0000-0000-000000000203" }, "00000000-0000-0000-0000-000000000207": { @@ -393,6 +410,7 @@ "tagUuids": [], "expertUuids": [], "referenceUuids": [], + "prefill": null, "maxSize": 1048576, "fileTypes": "application/pdf" }, @@ -406,6 +424,11 @@ "tagUuids": [], "expertUuids": [], "referenceUuids": [], + "prefill": { + "sourceQuestionUuid": "00000000-0000-0000-0000-000000000205", + "template": "{{ item.name }}", + "integrationOnly": true + }, "valueType": "NumberQuestionValueType", "validations": [] } diff --git a/packages/dsw-models/tests/fixtures/synthetic/km_events.json b/packages/dsw-models/tests/fixtures/synthetic/km_events.json index bbdc573f..8253205e 100644 --- a/packages/dsw-models/tests/fixtures/synthetic/km_events.json +++ b/packages/dsw-models/tests/fixtures/synthetic/km_events.json @@ -11,7 +11,8 @@ "text": null, "requiredPhaseUuid": null, "annotations": [], - "tagUuids": [] + "tagUuids": [], + "prefill": null } }, { @@ -27,6 +28,7 @@ "requiredPhaseUuid": null, "annotations": [], "tagUuids": [], + "prefill": null, "listQuestionUuid": null } }, @@ -43,6 +45,7 @@ "requiredPhaseUuid": null, "annotations": [], "tagUuids": [], + "prefill": null, "maxSize": null, "fileTypes": null } diff --git a/packages/dsw-models/tests/fixtures/synthetic/knowledge_model.json b/packages/dsw-models/tests/fixtures/synthetic/knowledge_model.json index d22505cc..1e30f83e 100644 --- a/packages/dsw-models/tests/fixtures/synthetic/knowledge_model.json +++ b/packages/dsw-models/tests/fixtures/synthetic/knowledge_model.json @@ -39,6 +39,7 @@ "00000000-0000-0000-0000-000000000502", "00000000-0000-0000-0000-000000000503" ], + "prefill": null, "answerUuids": ["00000000-0000-0000-0000-000000000301", "00000000-0000-0000-0000-000000000302"] }, "00000000-0000-0000-0000-000000000202": { @@ -51,6 +52,7 @@ "tagUuids": [], "expertUuids": [], "referenceUuids": [], + "prefill": null, "choiceUuids": ["00000000-0000-0000-0000-000000000601"] }, "00000000-0000-0000-0000-000000000203": { @@ -63,6 +65,7 @@ "tagUuids": [], "expertUuids": [], "referenceUuids": [], + "prefill": null, "itemTemplateQuestionUuids": ["00000000-0000-0000-0000-000000000204"] }, "00000000-0000-0000-0000-000000000204": { @@ -75,6 +78,7 @@ "tagUuids": [], "expertUuids": [], "referenceUuids": [], + "prefill": null, "valueType": "StringQuestionValueType", "validations": [ {"type": "MinLengthQuestionValidation", "value": 1}, @@ -103,6 +107,7 @@ "tagUuids": [], "expertUuids": [], "referenceUuids": [], + "prefill": null, "integrationUuid": "00000000-0000-0000-0000-000000000701", "variables": {"domain": "biology"} }, @@ -116,6 +121,7 @@ "tagUuids": [], "expertUuids": [], "referenceUuids": [], + "prefill": null, "listQuestionUuid": "00000000-0000-0000-0000-000000000203" }, "00000000-0000-0000-0000-000000000207": { @@ -128,6 +134,7 @@ "tagUuids": [], "expertUuids": [], "referenceUuids": [], + "prefill": null, "maxSize": 1048576, "fileTypes": "application/pdf" }, @@ -141,6 +148,11 @@ "tagUuids": [], "expertUuids": [], "referenceUuids": [], + "prefill": { + "sourceQuestionUuid": "00000000-0000-0000-0000-000000000205", + "template": "{{ item.name }}", + "integrationOnly": true + }, "valueType": "NumberQuestionValueType", "validations": [] } diff --git a/packages/dsw-models/tests/fixtures/synthetic/project_events.json b/packages/dsw-models/tests/fixtures/synthetic/project_events.json index 95104827..ff9069b3 100644 --- a/packages/dsw-models/tests/fixtures/synthetic/project_events.json +++ b/packages/dsw-models/tests/fixtures/synthetic/project_events.json @@ -1,21 +1,22 @@ [ - {"type": "SetReplyEvent", "uuid": "30000000-0000-0000-0000-000000000001", "path": "00000000-0000-0000-0000-000000000101.00000000-0000-0000-0000-000000000201", "value": {"type": "AnswerReply", "value": "00000000-0000-0000-0000-000000000301"}, "createdBy": {"uuid": "40000000-0000-0000-0000-000000000001", "firstName": "Jane", "lastName": "Doe", "gravatarHash": "abc", "imageUrl": null, "affiliation": "Example University"}, "createdAt": "2026-09-14T10:00:00Z"}, - {"type": "SetReplyEvent", "uuid": "30000000-0000-0000-0000-000000000002", "path": "00000000-0000-0000-0000-000000000101.00000000-0000-0000-0000-000000000201.00000000-0000-0000-0000-000000000301.00000000-0000-0000-0000-000000000208", "value": {"type": "StringReply", "value": "42"}, "createdBy": null, "createdAt": "2026-09-14T10:00:01Z"}, - {"type": "SetReplyEvent", "uuid": "30000000-0000-0000-0000-000000000003", "path": "00000000-0000-0000-0000-000000000101.00000000-0000-0000-0000-000000000202", "value": {"type": "MultiChoiceReply", "value": ["00000000-0000-0000-0000-000000000601"]}, "createdBy": null, "createdAt": "2026-09-14T10:00:02Z"}, - {"type": "SetReplyEvent", "uuid": "30000000-0000-0000-0000-000000000004", "path": "00000000-0000-0000-0000-000000000101.00000000-0000-0000-0000-000000000203", "value": {"type": "ItemListReply", "value": ["50000000-0000-0000-0000-000000000001", "50000000-0000-0000-0000-000000000002"]}, "createdBy": null, "createdAt": "2026-09-14T10:00:03Z"}, - {"type": "SetReplyEvent", "uuid": "30000000-0000-0000-0000-000000000005", "path": "00000000-0000-0000-0000-000000000101.00000000-0000-0000-0000-000000000205", "value": {"type": "IntegrationReply", "value": {"type": "IntegrationType", "value": "Biology", "raw": {"id": "bio", "tags": ["a", 1, null]}}}, "createdBy": null, "createdAt": "2026-09-14T10:00:04Z"}, - {"type": "SetReplyEvent", "uuid": "30000000-0000-0000-0000-000000000006", "path": "00000000-0000-0000-0000-000000000101.00000000-0000-0000-0000-000000000205", "value": {"type": "IntegrationReply", "value": {"type": "PlainType", "value": "Custom"}}, "createdBy": null, "createdAt": "2026-09-14T10:00:05Z"}, - {"type": "SetReplyEvent", "uuid": "30000000-0000-0000-0000-000000000007", "path": "00000000-0000-0000-0000-000000000101.00000000-0000-0000-0000-000000000206", "value": {"type": "ItemSelectReply", "value": "50000000-0000-0000-0000-000000000001"}, "createdBy": null, "createdAt": "2026-09-14T10:00:06Z"}, - {"type": "SetReplyEvent", "uuid": "30000000-0000-0000-0000-000000000008", "path": "00000000-0000-0000-0000-000000000101.00000000-0000-0000-0000-000000000207", "value": {"type": "FileReply", "value": "60000000-0000-0000-0000-000000000001"}, "createdBy": null, "createdAt": "2026-09-14T10:00:07Z"}, - {"type": "ClearReplyEvent", "uuid": "30000000-0000-0000-0000-000000000009", "path": "00000000-0000-0000-0000-000000000101.00000000-0000-0000-0000-000000000202", "createdBy": null, "createdAt": "2026-09-14T10:00:08Z"}, - {"type": "SetPhaseEvent", "uuid": "30000000-0000-0000-0000-000000000010", "phaseUuid": "00000000-0000-0000-0000-000000000a01", "createdBy": null, "createdAt": "2026-09-14T10:00:09Z"}, - {"type": "SetPhaseEvent", "uuid": "30000000-0000-0000-0000-000000000011", "phaseUuid": null, "createdBy": null, "createdAt": "2026-09-14T10:00:10Z"}, - {"type": "SetLabelsEvent", "uuid": "30000000-0000-0000-0000-000000000012", "path": "00000000-0000-0000-0000-000000000101.00000000-0000-0000-0000-000000000201", "value": ["615b9028-5e3f-414f-b245-12d2ae2eeb20"], "createdBy": null, "createdAt": "2026-09-14T10:00:11Z"}, + {"type": "SetReplyEvent", "uuid": "30000000-0000-0000-0000-000000000001", "path": "00000000-0000-0000-0000-000000000101.00000000-0000-0000-0000-000000000201", "value": {"type": "AnswerReply", "value": "00000000-0000-0000-0000-000000000301"}, "provenance": null, "createdBy": {"uuid": "40000000-0000-0000-0000-000000000001", "firstName": "Jane", "lastName": "Doe", "gravatarHash": "abc", "imageUrl": null, "affiliation": "Example University"}, "createdAt": "2026-09-14T10:00:00Z"}, + {"type": "SetReplyEvent", "uuid": "30000000-0000-0000-0000-000000000002", "path": "00000000-0000-0000-0000-000000000101.00000000-0000-0000-0000-000000000201.00000000-0000-0000-0000-000000000301.00000000-0000-0000-0000-000000000208", "value": {"type": "StringReply", "value": "42"}, "provenance": null, "createdBy": null, "createdAt": "2026-09-14T10:00:01Z"}, + {"type": "SetReplyEvent", "uuid": "30000000-0000-0000-0000-000000000003", "path": "00000000-0000-0000-0000-000000000101.00000000-0000-0000-0000-000000000202", "value": {"type": "MultiChoiceReply", "value": ["00000000-0000-0000-0000-000000000601"]}, "provenance": null, "createdBy": null, "createdAt": "2026-09-14T10:00:02Z"}, + {"type": "SetReplyEvent", "uuid": "30000000-0000-0000-0000-000000000004", "path": "00000000-0000-0000-0000-000000000101.00000000-0000-0000-0000-000000000203", "value": {"type": "ItemListReply", "value": ["50000000-0000-0000-0000-000000000001", "50000000-0000-0000-0000-000000000002"]}, "provenance": null, "createdBy": null, "createdAt": "2026-09-14T10:00:03Z"}, + {"type": "SetReplyEvent", "uuid": "30000000-0000-0000-0000-000000000005", "path": "00000000-0000-0000-0000-000000000101.00000000-0000-0000-0000-000000000205", "value": {"type": "IntegrationReply", "value": {"type": "IntegrationType", "value": "Biology", "raw": {"id": "bio", "tags": ["a", 1, null]}}}, "provenance": null, "createdBy": null, "createdAt": "2026-09-14T10:00:04Z"}, + {"type": "SetReplyEvent", "uuid": "30000000-0000-0000-0000-000000000006", "path": "00000000-0000-0000-0000-000000000101.00000000-0000-0000-0000-000000000205", "value": {"type": "IntegrationReply", "value": {"type": "PlainType", "value": "Custom"}}, "provenance": null, "createdBy": null, "createdAt": "2026-09-14T10:00:05Z"}, + {"type": "SetReplyEvent", "uuid": "30000000-0000-0000-0000-000000000007", "path": "00000000-0000-0000-0000-000000000101.00000000-0000-0000-0000-000000000206", "value": {"type": "ItemSelectReply", "value": "50000000-0000-0000-0000-000000000001"}, "provenance": null, "createdBy": null, "createdAt": "2026-09-14T10:00:06Z"}, + {"type": "SetReplyEvent", "uuid": "30000000-0000-0000-0000-000000000008", "path": "00000000-0000-0000-0000-000000000101.00000000-0000-0000-0000-000000000207", "value": {"type": "FileReply", "value": "60000000-0000-0000-0000-000000000001"}, "provenance": null, "createdBy": null, "createdAt": "2026-09-14T10:00:07Z"}, + {"type": "ClearReplyEvent", "uuid": "30000000-0000-0000-0000-000000000009", "path": "00000000-0000-0000-0000-000000000101.00000000-0000-0000-0000-000000000202", "provenance": {"type": "PrefillProvenanceType", "sourcePath": "00000000-0000-0000-0000-000000000101.00000000-0000-0000-0000-000000000205", "integrationUuid": "00000000-0000-0000-0000-000000000701"}, "createdBy": null, "createdAt": "2026-09-14T10:00:08Z"}, + {"type": "SetPhaseEvent", "uuid": "30000000-0000-0000-0000-000000000010", "phaseUuid": "00000000-0000-0000-0000-000000000a01", "provenance": null, "createdBy": null, "createdAt": "2026-09-14T10:00:09Z"}, + {"type": "SetPhaseEvent", "uuid": "30000000-0000-0000-0000-000000000011", "phaseUuid": null, "provenance": null, "createdBy": null, "createdAt": "2026-09-14T10:00:10Z"}, + {"type": "SetLabelsEvent", "uuid": "30000000-0000-0000-0000-000000000012", "path": "00000000-0000-0000-0000-000000000101.00000000-0000-0000-0000-000000000201", "value": ["615b9028-5e3f-414f-b245-12d2ae2eeb20"], "provenance": null, "createdBy": null, "createdAt": "2026-09-14T10:00:11Z"}, {"type": "AddCommentEvent", "uuid": "30000000-0000-0000-0000-000000000013", "path": "00000000-0000-0000-0000-000000000101.00000000-0000-0000-0000-000000000201", "threadUuid": "70000000-0000-0000-0000-000000000001", "commentUuid": "70000000-0000-0000-0000-000000000002", "text": "Why?", "private": false, "newThread": true, "createdBy": null, "createdAt": "2026-09-14T10:00:12Z"}, {"type": "EditCommentEvent", "uuid": "30000000-0000-0000-0000-000000000014", "path": "00000000-0000-0000-0000-000000000101.00000000-0000-0000-0000-000000000201", "threadUuid": "70000000-0000-0000-0000-000000000001", "commentUuid": "70000000-0000-0000-0000-000000000002", "text": "Why not?", "createdBy": null, "createdAt": "2026-09-14T10:00:13Z"}, {"type": "DeleteCommentEvent", "uuid": "30000000-0000-0000-0000-000000000015", "path": "00000000-0000-0000-0000-000000000101.00000000-0000-0000-0000-000000000201", "threadUuid": "70000000-0000-0000-0000-000000000001", "commentUuid": "70000000-0000-0000-0000-000000000002", "createdBy": null, "createdAt": "2026-09-14T10:00:14Z"}, {"type": "AssignCommentThreadEvent", "uuid": "30000000-0000-0000-0000-000000000016", "path": "00000000-0000-0000-0000-000000000101.00000000-0000-0000-0000-000000000201", "threadUuid": "70000000-0000-0000-0000-000000000001", "private": true, "assignedTo": {"uuid": "40000000-0000-0000-0000-000000000001", "firstName": "Jane", "lastName": "Doe", "gravatarHash": "abc", "imageUrl": "https://example.org/jane.png", "affiliation": null}, "createdBy": null, "createdAt": "2026-09-14T10:00:15Z"}, {"type": "ResolveCommentThreadEvent", "uuid": "30000000-0000-0000-0000-000000000017", "path": "00000000-0000-0000-0000-000000000101.00000000-0000-0000-0000-000000000201", "threadUuid": "70000000-0000-0000-0000-000000000001", "commentCount": 1, "createdBy": null, "createdAt": "2026-09-14T10:00:16Z"}, {"type": "ReopenCommentThreadEvent", "uuid": "30000000-0000-0000-0000-000000000018", "path": "00000000-0000-0000-0000-000000000101.00000000-0000-0000-0000-000000000201", "threadUuid": "70000000-0000-0000-0000-000000000001", "commentCount": 1, "createdBy": null, "createdAt": "2026-09-14T10:00:17Z"}, - {"type": "DeleteCommentThreadEvent", "uuid": "30000000-0000-0000-0000-000000000019", "path": "00000000-0000-0000-0000-000000000101.00000000-0000-0000-0000-000000000201", "threadUuid": "70000000-0000-0000-0000-000000000001", "createdBy": null, "createdAt": "2026-09-14T10:00:18Z"} + {"type": "DeleteCommentThreadEvent", "uuid": "30000000-0000-0000-0000-000000000019", "path": "00000000-0000-0000-0000-000000000101.00000000-0000-0000-0000-000000000201", "threadUuid": "70000000-0000-0000-0000-000000000001", "createdBy": null, "createdAt": "2026-09-14T10:00:18Z"}, + {"type": "DeleteItemEvent", "uuid": "30000000-0000-0000-0000-000000000020", "path": "00000000-0000-0000-0000-000000000101.00000000-0000-0000-0000-000000000203", "itemUuid": "50000000-0000-0000-0000-000000000001", "itemTitle": null, "provenance": {"type": "PrefillProvenanceType", "sourcePath": "00000000-0000-0000-0000-000000000101.00000000-0000-0000-0000-000000000205", "integrationUuid": "00000000-0000-0000-0000-000000000701"}, "createdBy": null, "createdAt": "2026-09-14T10:00:19Z"} ] diff --git a/packages/dsw-models/tests/fixtures/synthetic/template_bundle.json b/packages/dsw-models/tests/fixtures/synthetic/template_bundle.json index b814932e..f9a75004 100644 --- a/packages/dsw-models/tests/fixtures/synthetic/template_bundle.json +++ b/packages/dsw-models/tests/fixtures/synthetic/template_bundle.json @@ -2,7 +2,7 @@ "id": "example.my-template", "name": "My Template", "version": "1.0.0", - "metamodelVersion": "19.0", + "metamodelVersion": "19.1", "description": "Synthetic template", "readme": "# My Template", "license": "Apache-2.0", diff --git a/packages/dsw-models/tests/strategies.py b/packages/dsw-models/tests/strategies.py index 56ff208f..6bf48936 100644 --- a/packages/dsw-models/tests/strategies.py +++ b/packages/dsw-models/tests/strategies.py @@ -70,6 +70,8 @@ def _question(leaves, depth): common_fields = { 'title': TEXT, 'text': OPTIONAL_TEXT, 'required_phase_uuid': phase, 'tag_uuids': tag_uuids, 'annotations': ANNOTATIONS, 'references': references, + 'prefill': st.none() | model(common.QuestionPrefill, source_question_uuid=UUIDS, template=TEXT, + integration_only=st.booleans()), 'experts': st.lists(model(tree.Expert, name=TEXT, email=TEXT), max_size=1), } nested = st.lists(_question(leaves, depth - 1), max_size=2) if depth > 0 else st.just([]) diff --git a/packages/dsw-models/tests/test_document_context_graph.py b/packages/dsw-models/tests/test_document_context_graph.py index 0c2487a2..af34fd31 100644 --- a/packages/dsw-models/tests/test_document_context_graph.py +++ b/packages/dsw-models/tests/test_document_context_graph.py @@ -111,3 +111,28 @@ def test_markdown(): created_by=None) assert str(reply.markdown_html) == '

bold

\n' assert reply.markdown_plain.startswith('bold') # raw HTML text is kept, as in the worker + + +def test_prefill_and_provenance(dc): + question = dc.km.entities.questions['00000000-0000-0000-0000-000000000208'] + assert question.prefill.source_question_uuid == '00000000-0000-0000-0000-000000000205' + assert question.prefill.integration_only + [reply] = question.replies.values() + assert reply.provenance.type == 'PrefillProvenanceType' + assert reply.provenance.source_path.endswith('.00000000-0000-0000-0000-000000000205') + assert reply.provenance.integration_uuid == '00000000-0000-0000-0000-000000000701' + others = [r for r in dc.questionnaire.replies.values() if r is not reply] + assert others and all(r.provenance is None for r in others) + + +def test_context_queued_before_19_1_still_loads(): + ctx = enriched() + ctx['metamodelVersion'] = '19.0' + for question in ctx['knowledgeModel']['entities']['questions'].values(): + del question['prefill'] + for reply in ctx['questionnaire']['replies'].values(): + del reply['provenance'] + context = graph.DocumentContext(ctx=ctx) + context.resolve_links() + assert all(q.prefill is None for q in context.km.entities.questions.values()) + assert all(r.provenance is None for r in context.questionnaire.replies.values()) diff --git a/packages/dsw-models/tests/test_document_template_migrations.py b/packages/dsw-models/tests/test_document_template_migrations.py index 3d6895dd..0e739c04 100644 --- a/packages/dsw-models/tests/test_document_template_migrations.py +++ b/packages/dsw-models/tests/test_document_template_migrations.py @@ -46,7 +46,7 @@ def test_current_descriptors_gain_language_and_single_id(path): assert len(result.warnings) == 1 assert 'written for the document context of 18.x' in result.warnings[0] assert result.changed - assert result.data == {**as_5_0_identity(data), 'metamodelVersion': '19.0', 'language': 'en'} + assert result.data == {**as_5_0_identity(data), 'metamodelVersion': '19.1', 'language': 'en'} metadata = load(DocumentTemplateMetadata, result.data) assert metadata.reference == f"{data['organizationId']}.{data['templateId']}:{data['version']}" @@ -55,7 +55,7 @@ def test_v1_local_descriptor(): result = migrate_template_json(V1_DESCRIPTOR) metadata = load(DocumentTemplateMetadata, result.data) assert metadata.reference == 'dsw.questionnaire-report:1.0.0' - assert metadata.metamodel_version == '19.0' + assert metadata.metamodel_version == '19.1' assert result.data['formats'][0] == { 'uuid': 'd3e98eb6-344d-481f-8e37-6a67b6cd1ad2', 'name': 'HTML', 'icon': 'far fa-file-code', 'steps': [{'name': 'jinja', 'options': {'template': 'src/default.html.j2'}}]} @@ -92,7 +92,7 @@ def test_legacy_id_conflict_is_reported(extra, warning): @pytest.mark.parametrize(('version', 'message'), [ - ('19.1', 'newer than supported'), + ('19.2', 'newer than supported'), ('20.0', 'newer than supported'), ('x', 'Invalid metamodel version'), ]) diff --git a/packages/dsw-models/tests/test_knowledge_model_authoring.py b/packages/dsw-models/tests/test_knowledge_model_authoring.py index 6dcd0415..bbaa6c14 100644 --- a/packages/dsw-models/tests/test_knowledge_model_authoring.py +++ b/packages/dsw-models/tests/test_knowledge_model_authoring.py @@ -59,6 +59,8 @@ def build_synthetic() -> KnowledgeModelBuilder: chapter.file_question('File', uuid=u('207'), required_phase=u('a02'), max_size=1048576, file_types='application/pdf') yes.value_question('Follow-up', uuid=u('208'), value_type='NumberQuestionValueType') + b.km.entities.questions[u('208')].prefill = common.QuestionPrefill( + source_question_uuid=u('205'), template='{{ item.name }}', integration_only=True) return b diff --git a/packages/dsw-models/tests/test_knowledge_model_compiler.py b/packages/dsw-models/tests/test_knowledge_model_compiler.py index d5490b6f..d6c9c45e 100644 --- a/packages/dsw-models/tests/test_knowledge_model_compiler.py +++ b/packages/dsw-models/tests/test_knowledge_model_compiler.py @@ -14,7 +14,8 @@ events_of_chain, package_chain, ) -from dsw.models.knowledge_model.compiler import compile_events +from dsw.models.knowledge_model.common import QuestionPrefill +from dsw.models.knowledge_model.compiler import compile_events, convert_entity from dsw.models.knowledge_model.package import KnowledgeModelBundle from dsw.models.strictness import load @@ -375,3 +376,11 @@ def test_package_chain(): bundle.packages = bundle.packages[1:] with pytest.raises(PackageChainError, match='not in the bundle'): package_chain(bundle) + + +def test_prefill_survives_type_changes_except_to_unsupported_targets(): + prefill = QuestionPrefill(source_question_uuid=u(31), template='{{ item.x }}', integration_only=False) + question = flat.ValueQuestion(uuid=u(30), title='Q', prefill=prefill) + assert convert_entity(question, flat.ListQuestion).prefill == prefill + assert convert_entity(question, flat.ItemSelectQuestion).prefill is None + assert convert_entity(question, flat.FileQuestion).prefill is None diff --git a/packages/dsw-models/tests/test_knowledge_model_graph.py b/packages/dsw-models/tests/test_knowledge_model_graph.py index ffbc8dd8..daf0dcf4 100644 --- a/packages/dsw-models/tests/test_knowledge_model_graph.py +++ b/packages/dsw-models/tests/test_knowledge_model_graph.py @@ -183,7 +183,19 @@ def test_generated_models_are_consistent(tree_km): km = convert.tree_to_flat(tree_km, uuid_factory=deterministic_uuids()) assert convert.tree_to_flat(convert.flat_to_tree(km)) == km km_graph = convert.flat_to_graph(km) - assert km_graph.dangling == [] + assert {d.field for d in km_graph.dangling} <= {'prefill'} # random sources assert km_graph.shared == [] assert km_graph.unreachable == [] assert len(list(visitor.iter_nodes(km_graph))) == len(km_graph) + + +def test_prefill_source(): + data = load_synthetic('knowledge_model.json') + prefilled = '00000000-0000-0000-0000-000000000208' + km = graph.KnowledgeModel(load(flat.KnowledgeModel, data)) + assert km[UUID(prefilled)].prefill_source is km[UUID('00000000-0000-0000-0000-000000000205')] + assert km.dangling == [] + data['entities']['questions'][prefilled]['prefill']['sourceQuestionUuid'] = str(UUID(int=99)) + km = graph.KnowledgeModel(load(flat.KnowledgeModel, data)) + assert km[UUID(prefilled)].prefill_source is None + assert [(d.field, d.target_uuid) for d in km.dangling] == [('prefill', UUID(int=99))] diff --git a/packages/dsw-models/tests/test_knowledge_model_migrations.py b/packages/dsw-models/tests/test_knowledge_model_migrations.py index 43d1612e..57486e3a 100644 --- a/packages/dsw-models/tests/test_knowledge_model_migrations.py +++ b/packages/dsw-models/tests/test_knowledge_model_migrations.py @@ -2,7 +2,7 @@ from uuid import UUID import pytest -from conftest import REFERENCE_BUNDLES, load_reference +from conftest import REFERENCE_BUNDLES, load_raw_reference, load_reference from dsw.models.errors import MigrationError from dsw.models.knowledge_model import flat @@ -65,9 +65,9 @@ def test_migrate_v1_bundle(): snapshot = copy.deepcopy(bundle) migrated = migrate_bundle(bundle) assert bundle == snapshot # input untouched - assert migrated['metamodelVersion'] == 20 + assert migrated['metamodelVersion'] == 21 package = migrated['packages'][0] - assert package['metamodelVersion'] == 20 + assert package['metamodelVersion'] == 21 assert all(set(event) == {'uuid', 'parentUuid', 'entityUuid', 'createdAt', 'content'} for event in package['events']) assert {event['createdAt'] for event in package['events']} == {'2018-01-01T12:00:00.5Z'} @@ -160,7 +160,7 @@ def test_parent_package_id_fills_links(): @pytest.mark.parametrize(('package', 'message'), [ - ({'metamodelVersion': 21, 'createdAt': 'x', 'events': []}, 'only up to 20'), + ({'metamodelVersion': 22, 'createdAt': 'x', 'events': []}, 'only up to 21'), ({'metamodelVersion': 0, 'createdAt': '2020-01-01T00:00:00Z', 'events': []}, 'Unsupported metamodel version 0'), ({'metamodelVersion': 5, 'events': []}, 'no createdAt'), ({'createdAt': 'x', 'events': []}, 'no valid metamodelVersion'), @@ -178,3 +178,24 @@ def test_current_bundles_are_unchanged(name): for link in ('previousPackageId', 'forkOfPackageId', 'mergeCheckpointPackageId'): original.setdefault(link, None) assert package == original + + +def test_step_20_adds_prefill_to_questions(): + def wrap(content): + return {'uuid': e(1), 'entityUuid': VALUE, 'content': content} + + add = {'eventType': 'AddQuestionEvent', 'questionType': 'ValueQuestion'} + edit = {'eventType': 'EditQuestionEvent', 'questionType': 'IntegrationQuestion'} + assert steps.step_20(wrap(add), CTX) == [wrap({**add, 'prefill': None})] + assert steps.step_20(wrap(edit), CTX) == [wrap({**edit, 'prefill': {'changed': False}})] + for other in ({'eventType': 'AddChapterEvent'}, {'eventType': 'DeleteQuestionEvent'}): + assert steps.step_20(wrap(other), CTX) == [wrap(other)] + + +@pytest.mark.parametrize('name', REFERENCE_BUNDLES) +def test_v20_bundles_gain_empty_prefill(name): + raw = load_raw_reference(name) + assert raw['metamodelVersion'] == 20 + km = compile_bundle(load(KnowledgeModelBundle, migrate_bundle(raw))) + assert km.entities.questions + assert all(question.prefill is None for question in km.entities.questions.values()) diff --git a/packages/dsw-models/tests/test_knowledge_model_wire.py b/packages/dsw-models/tests/test_knowledge_model_wire.py index 32257319..ad9a5f55 100644 --- a/packages/dsw-models/tests/test_knowledge_model_wire.py +++ b/packages/dsw-models/tests/test_knowledge_model_wire.py @@ -32,7 +32,7 @@ def package(item): def test_reference_bundle_round_trip(name): data = load_reference(name) bundle = load(KnowledgeModelBundle, data) - assert bundle.metamodel_version == 20 + assert bundle.metamodel_version == 21 exported = as_5_0_export(data) assert_same_json(exported, bundle.to_json_data()) assert_same_json(exported, load(KnowledgeModelBundle, exported).to_json_data()) diff --git a/packages/dsw-models/tests/test_project_analysis.py b/packages/dsw-models/tests/test_project_analysis.py index 8519d1e4..9d3a84ce 100644 --- a/packages/dsw-models/tests/test_project_analysis.py +++ b/packages/dsw-models/tests/test_project_analysis.py @@ -154,3 +154,36 @@ def test_report_options_question_with_unexpected_reply_counts_twice(): answers = {f'{chapter.uuid}.{options.uuid}': _reply(replies.StringReplyValue(value='x'))} _, answered = generate_report(km, answers).total_report.indications assert (answered.answered_questions, answered.unanswered_questions) == (1, 1) + + +# prefill +PROVENANCE = replies.PrefillProvenance(source_path='c.person', integration_uuid=UUID(int=9)) + + +def test_manual_answer_drops_provenance(): + prefilled = set_reply('c.q', 'Jane').model_copy(update={'provenance': PROVENANCE}) + assert compile_project_events([prefilled]).replies['c.q'].provenance == PROVENANCE + assert compile_project_events([prefilled, set_reply('c.q', 'X')]).replies['c.q'].provenance is None + + +def test_delete_item_removes_everything_in_it(): + kept, deleted = UUID(int=1), UUID(int=2) + label = UUID(int=3) + stream = [ + events.SetReplyEvent(uuid=_ids(), path='c.l', created_at=at(0), created_by=JANE, + value=replies.ItemListReplyValue(value=[kept, deleted])), + set_reply(f'c.l.{kept}.q', 'kept'), + set_reply(f'c.l.{deleted}.q', 'deleted'), + events.SetLabelsEvent(uuid=_ids(), path=f'c.l.{kept}.q', value=[label], created_at=at(1)), + events.SetLabelsEvent(uuid=_ids(), path=f'c.l.{deleted}.q', value=[label], created_at=at(1)), + events.DeleteItemEvent(uuid=_ids(), path='c.l', item_uuid=deleted, created_at=at(2), + created_by=JOHN, provenance=PROVENANCE), + ] + content = compile_project_events(stream) + assert set(content.replies) == {'c.l', f'c.l.{kept}.q'} + assert set(content.labels) == {f'c.l.{kept}.q'} + items = content.replies['c.l'] + assert items.value.value == [kept] + assert (items.created_by, items.created_at, items.provenance) == (JOHN, at(2), PROVENANCE) + # an item of a list without a reply + assert compile_project_events(stream[-1:]).replies == {} diff --git a/packages/dsw-models/tests/test_project_wire.py b/packages/dsw-models/tests/test_project_wire.py index 24e3193d..ad3213fd 100644 --- a/packages/dsw-models/tests/test_project_wire.py +++ b/packages/dsw-models/tests/test_project_wire.py @@ -18,7 +18,7 @@ def _dump(adapter, value): def test_all_events_round_trip(): data = load_synthetic('project_events.json') parsed = ANY_EVENTS.validate_python(data) - assert len({type(event) for event in parsed}) == 11 + assert len({type(event) for event in parsed}) == 12 assert_same_json(data, _dump(ANY_EVENTS, parsed)) diff --git a/packages/dsw-models/tests/test_versions.py b/packages/dsw-models/tests/test_versions.py index 2b0f119b..887e0a2c 100644 --- a/packages/dsw-models/tests/test_versions.py +++ b/packages/dsw-models/tests/test_versions.py @@ -21,12 +21,13 @@ def test_parse_invalid(value): def test_str(): - assert str(DOCUMENT_TEMPLATE_METAMODEL_VERSION) == '19.0' + assert str(DOCUMENT_TEMPLATE_METAMODEL_VERSION) == '19.1' @pytest.mark.parametrize(('other', 'supported'), [ ('19.0', True), - ('19.1', False), + ('19.1', True), + ('19.2', False), ('18.3', False), ('20.0', False), ]) diff --git a/packages/dsw-tdk/CHANGELOG.md b/packages/dsw-tdk/CHANGELOG.md index 3b90f06e..f567d281 100644 --- a/packages/dsw-tdk/CHANGELOG.md +++ b/packages/dsw-tdk/CHANGELOG.md @@ -7,6 +7,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Changed + +- Document template metamodel 19.1 and knowledge model metamodel 21; generated contexts have + `prefill` and `provenance` + ## [5.1.0] diff --git a/packages/dsw-tdk/README.md b/packages/dsw-tdk/README.md index cbdaa1ab..6a1eb734 100644 --- a/packages/dsw-tdk/README.md +++ b/packages/dsw-tdk/README.md @@ -62,12 +62,12 @@ For further information, visit our [documentation](https://docs.ds-wizard.org). - `pot` = create a POT file with translatable strings of the local template project - `get-context` = download the document context of a project (`--project UUID`, optionally `--event UUID`) or a knowledge model editor (`--km-editor UUID`), as the server sends it; it prints the ETag, which is the context's `hash` - `generate-context` = generate plausible document contexts from a knowledge model: `--sample` (shipped with the TDK), `--km-bundle FILE`, `--km-package UUID` (from the server) or `--from FILE` (keeps its knowledge model, package, config and workspace); `--profile empty|minimal|typical|full|edge` (repeatable) sets how much is filled in, `--count N` the variants per profile, `--source project|km-editor` the kind of context, `--seed` makes the output reproducible and `-D KEY=VALUE` sets `config` values. With `--from`, `--mutate` perturbs the context at the rate of each profile and `--anonymize` replaces its personal data and free text with deterministic placeholders (both can be combined). Every generated context passes `validate-context` -- `validate-context` = check document context files against the 19.0 schema and their own knowledge model (reply paths and values, files, labels, phase, version, hash); it prints errors and warnings and exits with `1` on any error, and `--fix-hash` rewrites a hash that does not match the content +- `validate-context` = check document context files against the 19.x schema and their own knowledge model (reply paths and values, files, labels, phase, version, hash); it prints errors and warnings and exits with `1` on any error, and `--fix-hash` rewrites a hash that does not match the content - `render` = render documents from the local template project and document contexts (no DSW instance needed) ### Rendering documents locally -`render` uses the same engine as the DSW document worker ([dsw-templating](../dsw-templating)). You need a document context (metamodel 19.0) as a JSON file, from `get-context` or `generate-context`: +`render` uses the same engine as the DSW document worker ([dsw-templating](../dsw-templating)). You need a document context (metamodel 19.x) as a JSON file, from `get-context` or `generate-context`: ```shell script $ dsw-tdk render --context context.json --format "HTML Document" --output document.html @@ -75,7 +75,7 @@ $ dsw-tdk render -c context.json -F "PDF Document" --po cs.po -l cs --project-fi ``` - `--format` accepts the UUID or name of a format (it can be omitted if the template has only one) -- The context must be a complete, valid 19.0 context; otherwise `render` fails with the file, the JSON path and the problem. A context whose `hash` does not match its content (edited by hand) is rendered with a warning +- The context must be a complete, valid 19.x context; otherwise `render` fails with the file, the JSON path and the problem. A context whose `hash` does not match its content (edited by hand) is rendered with a warning - `render` fills `document` as the document worker would: `documentTemplate` (`id` and `version` from `template.json`) and `format` are always those being rendered (with a warning if the context names others); the rest is kept from the context, or, for `document: null`, is a preview named after the project or KM editor, without a language, created now - `-l/--language`, `--preview/--final`, `--event UUID` and `--document-name NAME` set `document.language` (and resets `document.locale`), `preview`, `eventUuid` and `name` - `--po` renders with translations from a PO file (e.g. a translated `dsw-tdk pot` output), in `document.language`; with `-l`, `document.locale` is filled for that language diff --git a/packages/dsw-tdk/dsw/tdk/cli.py b/packages/dsw-tdk/dsw/tdk/cli.py index 40ae4387..80f8fb28 100644 --- a/packages/dsw-tdk/dsw/tdk/cli.py +++ b/packages/dsw-tdk/dsw/tdk/cli.py @@ -872,7 +872,7 @@ def _print_render_failure(message: str): @main.command(help='Render documents from the local template and document contexts (metamodel ' - '19.0). With more than one context or format, every combination is rendered ' + '19.x). With more than one context or format, every combination is rendered ' 'into the output directory, with a summary.json.', name='render') @click.argument('TEMPLATE-DIR', type=DIR_TYPE, default=CURRENT_DIR, required=False) diff --git a/packages/dsw-tdk/dsw/tdk/context/document.py b/packages/dsw-tdk/dsw/tdk/context/document.py index 3fc58f96..8526f60e 100644 --- a/packages/dsw-tdk/dsw/tdk/context/document.py +++ b/packages/dsw-tdk/dsw/tdk/context/document.py @@ -1,4 +1,4 @@ -"""`render` fills ``document`` of a 19.0 context (WEP 24, "render fills document"). +"""`render` fills ``document`` of a 19.x context (WEP 24, "render fills document"). `get-context` and `generate-context` write ``document: null``; the document worker fills it from the document being generated. Locally there is no document, so it is made up from the template @@ -47,7 +47,7 @@ class InvalidContextError(RuntimeError): def load_context(path: pathlib.Path) -> dict: - """Parse and validate a 19.0 context; partial contexts are rejected.""" + """Parse and validate a 19.x context; partial contexts are rejected.""" try: context = json.loads(path.read_text(encoding='utf-8')) except json.JSONDecodeError as e: @@ -58,7 +58,7 @@ def load_context(path: pathlib.Path) -> dict: problems = '\n'.join(f' {pointer(*error["loc"]) or "/"}: {error["msg"]}' for error in e.errors()) raise InvalidContextError(f'{path}: not a valid document context ' - f'(metamodel 19.0):\n{problems}') from e + f'(metamodel 19.x):\n{problems}') from e return context diff --git a/packages/dsw-tdk/dsw/tdk/context/generate.py b/packages/dsw-tdk/dsw/tdk/context/generate.py index a49f9250..329192ab 100644 --- a/packages/dsw-tdk/dsw/tdk/context/generate.py +++ b/packages/dsw-tdk/dsw/tdk/context/generate.py @@ -1,4 +1,4 @@ -"""Plausible document contexts (metamodel 19.0) for a knowledge model (`dsw-tdk generate-context`). +"""Plausible document contexts (metamodel 19.1) for a knowledge model (`dsw-tdk generate-context`). Rules from WEP 24, Appendix D: only visible questions are answered (chapter questions, the follow-ups of the chosen answers and the item questions of each generated item), in two passes so @@ -345,7 +345,8 @@ def _labels(self) -> dict: # replies def _reply(self, path: str, value: dict) -> None: self.replies[path] = {'value': value, 'createdBy': self._creator(), - 'createdAt': self.time(self.rng.randint(0, 100))} + 'createdAt': self.time(self.rng.randint(0, 100)), + 'provenance': None} def _answer_chapters(self) -> None: for chapter in self.km.chapters: diff --git a/packages/dsw-tdk/dsw/tdk/core.py b/packages/dsw-tdk/dsw/tdk/core.py index c7b02e87..a447c75f 100644 --- a/packages/dsw-tdk/dsw/tdk/core.py +++ b/packages/dsw-tdk/dsw/tdk/core.py @@ -518,7 +518,7 @@ def render_batch(self, *, context_files: list[pathlib.Path], formats: list[Forma def _prepare_context(self, context_file: pathlib.Path, format_spec: Format, options: DocumentOptions) -> dict: - """The valid 19.0 context of the file, with its ``document`` filled.""" + """The valid 19.x context of the file, with its ``document`` filled.""" self.logger.debug('Loading document context: %s', context_file.as_posix()) context = load_context(context_file) expected = compute_context_hash(context) diff --git a/packages/dsw-tdk/dsw/tdk/samples/sample-km.json b/packages/dsw-tdk/dsw/tdk/samples/sample-km.json index c86a9bc1..d7f470e8 100644 --- a/packages/dsw-tdk/dsw/tdk/samples/sample-km.json +++ b/packages/dsw-tdk/dsw/tdk/samples/sample-km.json @@ -2,14 +2,14 @@ "id": "tdk.sample", "name": "TDK Sample Knowledge Model", "version": "1.0.0", - "metamodelVersion": 20, + "metamodelVersion": 21, "packages": [ { "id": "tdk.sample", "name": "TDK Sample Knowledge Model", "version": "1.0.0", "phase": "ReleasedKnowledgeModelPackagePhase", - "metamodelVersion": 20, + "metamodelVersion": 21, "description": "Covers every question and value type for generating document contexts", "readme": "", "license": "CC0-1.0", @@ -50,6 +50,7 @@ "tagUuids": [ "6599f977-6d7f-517a-a3af-7852ec7f22a5" ], + "prefill": null, "questionType": "OptionsQuestion" }, "createdAt": "2025-01-01T00:00:00Z" @@ -89,6 +90,7 @@ "requiredPhaseUuid": null, "annotations": [], "tagUuids": [], + "prefill": null, "questionType": "ValueQuestion", "valueType": "TextQuestionValueType", "validations": [] @@ -106,6 +108,7 @@ "requiredPhaseUuid": null, "annotations": [], "tagUuids": [], + "prefill": null, "questionType": "OptionsQuestion" }, "createdAt": "2025-01-01T00:00:00Z" @@ -153,6 +156,7 @@ "requiredPhaseUuid": "26f02d26-28f8-540c-a082-9c383423f80b", "annotations": [], "tagUuids": [], + "prefill": null, "questionType": "ValueQuestion", "valueType": "StringQuestionValueType", "validations": [] @@ -228,6 +232,7 @@ "tagUuids": [ "989cfbb0-0feb-5ae0-a7c0-599d8e9abb85" ], + "prefill": null, "questionType": "MultiChoiceQuestion" }, "createdAt": "2025-01-01T00:00:00Z" @@ -287,6 +292,7 @@ "requiredPhaseUuid": null, "annotations": [], "tagUuids": [], + "prefill": null, "questionType": "OptionsQuestion" }, "createdAt": "2025-01-01T00:00:00Z" @@ -327,6 +333,7 @@ "requiredPhaseUuid": null, "annotations": [], "tagUuids": [], + "prefill": null, "questionType": "ValueQuestion", "valueType": "StringQuestionValueType", "validations": [ @@ -353,6 +360,7 @@ "requiredPhaseUuid": null, "annotations": [], "tagUuids": [], + "prefill": null, "questionType": "ValueQuestion", "valueType": "TextQuestionValueType", "validations": [] @@ -370,6 +378,7 @@ "requiredPhaseUuid": null, "annotations": [], "tagUuids": [], + "prefill": null, "questionType": "ValueQuestion", "valueType": "NumberQuestionValueType", "validations": [ @@ -396,6 +405,7 @@ "requiredPhaseUuid": null, "annotations": [], "tagUuids": [], + "prefill": null, "questionType": "ValueQuestion", "valueType": "DateQuestionValueType", "validations": [ @@ -422,6 +432,7 @@ "requiredPhaseUuid": null, "annotations": [], "tagUuids": [], + "prefill": null, "questionType": "ValueQuestion", "valueType": "DateTimeQuestionValueType", "validations": [ @@ -448,6 +459,7 @@ "requiredPhaseUuid": null, "annotations": [], "tagUuids": [], + "prefill": null, "questionType": "ValueQuestion", "valueType": "TimeQuestionValueType", "validations": [ @@ -474,6 +486,7 @@ "requiredPhaseUuid": null, "annotations": [], "tagUuids": [], + "prefill": null, "questionType": "ValueQuestion", "valueType": "EmailQuestionValueType", "validations": [] @@ -491,6 +504,7 @@ "requiredPhaseUuid": null, "annotations": [], "tagUuids": [], + "prefill": null, "questionType": "ValueQuestion", "valueType": "UrlQuestionValueType", "validations": [ @@ -513,6 +527,7 @@ "requiredPhaseUuid": null, "annotations": [], "tagUuids": [], + "prefill": null, "questionType": "ValueQuestion", "valueType": "ColorQuestionValueType", "validations": [] @@ -530,6 +545,7 @@ "requiredPhaseUuid": null, "annotations": [], "tagUuids": [], + "prefill": null, "questionType": "ValueQuestion", "valueType": "StringQuestionValueType", "validations": [ @@ -551,6 +567,7 @@ "requiredPhaseUuid": null, "annotations": [], "tagUuids": [], + "prefill": null, "questionType": "ValueQuestion", "valueType": "StringQuestionValueType", "validations": [ @@ -572,6 +589,7 @@ "requiredPhaseUuid": null, "annotations": [], "tagUuids": [], + "prefill": null, "questionType": "ValueQuestion", "valueType": "StringQuestionValueType", "validations": [ @@ -594,6 +612,7 @@ "requiredPhaseUuid": null, "annotations": [], "tagUuids": [], + "prefill": null, "questionType": "ValueQuestion", "valueType": "StringQuestionValueType", "validations": [ @@ -616,6 +635,7 @@ "requiredPhaseUuid": null, "annotations": [], "tagUuids": [], + "prefill": null, "questionType": "IntegrationQuestion", "integrationUuid": "bec30123-6ae9-5625-b4e2-166539e2911f", "variables": {} @@ -645,6 +665,7 @@ "requiredPhaseUuid": "45f253b6-bfa1-5ecc-8bf5-7db804a5a7ee", "annotations": [], "tagUuids": [], + "prefill": null, "questionType": "ListQuestion" }, "createdAt": "2025-01-01T00:00:00Z" @@ -660,6 +681,7 @@ "requiredPhaseUuid": "45f253b6-bfa1-5ecc-8bf5-7db804a5a7ee", "annotations": [], "tagUuids": [], + "prefill": null, "questionType": "ValueQuestion", "valueType": "StringQuestionValueType", "validations": [] @@ -677,6 +699,7 @@ "requiredPhaseUuid": null, "annotations": [], "tagUuids": [], + "prefill": null, "questionType": "ValueQuestion", "valueType": "NumberQuestionValueType", "validations": [] @@ -696,6 +719,7 @@ "tagUuids": [ "989cfbb0-0feb-5ae0-a7c0-599d8e9abb85" ], + "prefill": null, "questionType": "OptionsQuestion" }, "createdAt": "2025-01-01T00:00:00Z" @@ -737,6 +761,7 @@ "requiredPhaseUuid": null, "annotations": [], "tagUuids": [], + "prefill": null, "questionType": "FileQuestion", "maxSize": 1000000, "fileTypes": "application/pdf" @@ -754,6 +779,7 @@ "requiredPhaseUuid": null, "annotations": [], "tagUuids": [], + "prefill": null, "questionType": "ListQuestion" }, "createdAt": "2025-01-01T00:00:00Z" @@ -769,6 +795,7 @@ "requiredPhaseUuid": null, "annotations": [], "tagUuids": [], + "prefill": null, "questionType": "ValueQuestion", "valueType": "StringQuestionValueType", "validations": [] @@ -786,6 +813,7 @@ "requiredPhaseUuid": null, "annotations": [], "tagUuids": [], + "prefill": null, "questionType": "ListQuestion" }, "createdAt": "2025-01-01T00:00:00Z" @@ -801,6 +829,7 @@ "requiredPhaseUuid": null, "annotations": [], "tagUuids": [], + "prefill": null, "questionType": "ValueQuestion", "valueType": "StringQuestionValueType", "validations": [] @@ -818,6 +847,7 @@ "requiredPhaseUuid": null, "annotations": [], "tagUuids": [], + "prefill": null, "questionType": "ItemSelectQuestion", "listQuestionUuid": "c8a0722d-dd85-55aa-bd3e-84fceb37b715" }, @@ -834,6 +864,7 @@ "requiredPhaseUuid": null, "annotations": [], "tagUuids": [], + "prefill": null, "questionType": "FileQuestion", "maxSize": 5000000, "fileTypes": "application/pdf, application/vnd.oasis.opendocument.text" @@ -851,6 +882,7 @@ "requiredPhaseUuid": null, "annotations": [], "tagUuids": [], + "prefill": null, "questionType": "FileQuestion", "maxSize": null, "fileTypes": null diff --git a/packages/dsw-tdk/tests/cassettes/test_cmd_context/test_get_context_of_km_editor.yaml b/packages/dsw-tdk/tests/cassettes/test_cmd_context/test_get_context_of_km_editor.yaml index aea09e44..69060cb5 100644 --- a/packages/dsw-tdk/tests/cassettes/test_cmd_context/test_get_context_of_km_editor.yaml +++ b/packages/dsw-tdk/tests/cassettes/test_cmd_context/test_get_context_of_km_editor.yaml @@ -12,7 +12,7 @@ interactions: body: string: '{"builtAt":"2026-10-14T14:11:04Z","components":[{"builtAt":"2026-10-14T18:24:20Z","createdAt":"2026-10-14T16:58:40.476791Z","name":"Document Worker","updatedAt":"2026-10-14T17:25:03.455715Z","version":"update/fw5~87566ae"}],"metamodelVersions":[{"name":"Knowledge - Model","version":"20"},{"name":"Document Template","version":"19.0"}],"name":"Admin + Model","version":"20"},{"name":"Document Template","version":"19.1"}],"name":"Admin Server","version":"main~4e7d05995"}' headers: Access-Control-Allow-Credential: diff --git a/packages/dsw-tdk/tests/cassettes/test_cmd_context/test_get_context_of_project.yaml b/packages/dsw-tdk/tests/cassettes/test_cmd_context/test_get_context_of_project.yaml index d19d3bbf..5028c784 100644 --- a/packages/dsw-tdk/tests/cassettes/test_cmd_context/test_get_context_of_project.yaml +++ b/packages/dsw-tdk/tests/cassettes/test_cmd_context/test_get_context_of_project.yaml @@ -12,7 +12,7 @@ interactions: body: string: '{"builtAt":"2026-10-14T14:11:04Z","components":[{"builtAt":"2026-10-14T18:24:20Z","createdAt":"2026-10-14T16:58:40.476791Z","name":"Document Worker","updatedAt":"2026-10-14T17:25:03.455715Z","version":"update/fw5~87566ae"}],"metamodelVersions":[{"name":"Knowledge - Model","version":"20"},{"name":"Document Template","version":"19.0"}],"name":"Admin + Model","version":"20"},{"name":"Document Template","version":"19.1"}],"name":"Admin Server","version":"main~4e7d05995"}' headers: Access-Control-Allow-Credential: diff --git a/packages/dsw-tdk/tests/cassettes/test_cmd_context/test_get_context_of_unknown_event.yaml b/packages/dsw-tdk/tests/cassettes/test_cmd_context/test_get_context_of_unknown_event.yaml index eaee78f5..45e774a2 100644 --- a/packages/dsw-tdk/tests/cassettes/test_cmd_context/test_get_context_of_unknown_event.yaml +++ b/packages/dsw-tdk/tests/cassettes/test_cmd_context/test_get_context_of_unknown_event.yaml @@ -12,7 +12,7 @@ interactions: body: string: '{"builtAt":"2026-10-14T14:11:04Z","components":[{"builtAt":"2026-10-14T18:24:20Z","createdAt":"2026-10-14T16:58:40.476791Z","name":"Document Worker","updatedAt":"2026-10-14T17:25:03.455715Z","version":"update/fw5~87566ae"}],"metamodelVersions":[{"name":"Knowledge - Model","version":"20"},{"name":"Document Template","version":"19.0"}],"name":"Admin + Model","version":"20"},{"name":"Document Template","version":"19.1"}],"name":"Admin Server","version":"main~4e7d05995"}' headers: Access-Control-Allow-Credential: diff --git a/packages/dsw-templating/CHANGELOG.md b/packages/dsw-templating/CHANGELOG.md index 3bc6a4b9..d3bdc407 100644 --- a/packages/dsw-templating/CHANGELOG.md +++ b/packages/dsw-templating/CHANGELOG.md @@ -7,6 +7,10 @@ to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [Unreleased] +### Added + +- `prefill` of questions and `provenance` of replies in the document context (metamodel 19.1) + ## [5.1.0] diff --git a/packages/dsw-templating/support/DocumentContext.md b/packages/dsw-templating/support/DocumentContext.md index 37ac1e89..193f955b 100644 --- a/packages/dsw-templating/support/DocumentContext.md +++ b/packages/dsw-templating/support/DocumentContext.md @@ -1,6 +1,6 @@ # Document Context -This document describes the document context (metamodel **19.0**) that the document worker provides to Jinja templates. The raw JSON is available as `ctx`; the object model described here is created like this: +This document describes the document context (metamodel **19.1**) that the document worker provides to Jinja templates. The raw JSON is available as `ctx`; the object model described here is created like this: ```jinja {%- set x = ctx|to_context_obj -%} @@ -320,6 +320,7 @@ Superclass with common attributes for all types of questions. You always get a m * `tags` (`list[`[`Tag`](#tag)`]`) * `parent` (`Union[`[`Chapter`](#chapter)`,`[`ListQuestion`](#listquestion)`,`[`Answer`](#answer)`]`) * `annotations` (`dict[str,str]`) +* `prefill` (`Optional[`[`QuestionPrefill`](#questionprefill)`]`) - since 19.1 Aliases: @@ -328,6 +329,14 @@ Aliases: :bulb: Parent of a question can be of multiple kinds, you may use the `of_type` test to check what it is if needed. +##### QuestionPrefill + +How the question is prefilled from the item picked in an integration question. + +* `source_question_uuid` (`str`) +* `template` (`str`) - Jinja template over the picked `item` +* `integration_only` (`bool`) - the question can be answered only from the integration + ##### ValueQuestion * `value_type` (`str`) - type of value, use alias @@ -478,6 +487,13 @@ Superclass with common attributes for all types of replies. You always get a mor * `created_at` (`datetime`) * `created_by` ([`SimpleAuthor`](#simpleauthor)) * `question` ([`Question`](#question)) - you can assume more specific type of `Question` based on a type of `Reply` +* `provenance` (`Optional[`[`ReplyProvenance`](#replyprovenance)`]`) - where the reply comes from, `None` when it was answered by hand; since 19.1 + +#### ReplyProvenance + +* `type` (`str`) - `PrefillProvenanceType`, more types may be added +* `source_path` (`str`) - path of the reply to the originating integration question +* `integration_uuid` (`str`) #### AnswerReply @@ -545,4 +561,4 @@ Aliases: * The variable `ctx` is the raw JSON document context; its shape is the `DocumentContext` model in [`dsw-models`](../../dsw-models/dsw/models/document_context/wire.py). * If you think that something useful is missing in the context or its documentation, please let us know. -This document has been last revised for **document context metamodel 19.0**. +This document has been last revised for **document context metamodel 19.1**. diff --git a/packages/dsw-templating/tests/test_context_reference.py b/packages/dsw-templating/tests/test_context_reference.py index e634ccc3..a2557902 100644 --- a/packages/dsw-templating/tests/test_context_reference.py +++ b/packages/dsw-templating/tests/test_context_reference.py @@ -14,6 +14,7 @@ from dsw.templating.filters import to_context_obj from dsw.models.knowledge_model import graph as km_graph from dsw.models.knowledge_model.bundle import compile_bundle +from dsw.models.knowledge_model.migrations import migrate_bundle from dsw.models.knowledge_model.package import KnowledgeModelBundle from dsw.models.project.report import generate_report from dsw.models.strictness import load @@ -43,7 +44,7 @@ def generated_context() -> dict: """The synthetic context with the compiled Czech NRP knowledge model and replies to every question.""" base = json.loads(SYNTHETIC_CONTEXT.read_text(encoding='utf-8')) with gzip.open(REFERENCE_BUNDLE, 'rt', encoding='utf-8') as file: - km = compile_bundle(load(KnowledgeModelBundle, json.load(file))) + km = compile_bundle(load(KnowledgeModelBundle, migrate_bundle(json.load(file)))) graph = km_graph.KnowledgeModel(km) file_uuid = base['questionnaire']['files'][0]['uuid'] counter = iter(range(1, 1_000_000)) @@ -104,7 +105,7 @@ def visit(question, prefix: str, depth: int) -> None: questionnaire['report'] = {key: report[key] for key in ('totalReport', 'chapterReports', 'chapters', 'metrics')} ctx['hash'] = compute_context_hash(ctx) - load(WireDocumentContext, ctx) # still a valid 19.0 context + load(WireDocumentContext, ctx) # still a valid 19.x context return ctx