From b80e2d00b07f2b73a22cbd6cacc70cc44dbf9273 Mon Sep 17 00:00:00 2001 From: qingpeng Date: Mon, 23 Nov 2026 16:29:30 -0800 Subject: [PATCH 1/8] [feat] contracts: define generation dependency impact queries ## summary Add bounded read-only impact contracts and derive dependency edges from current follow bindings, including hidden and unresolved sources. Keep pinned assets, retained subject slots and overrides distinct from live generation dependencies. ## validation 94 Python tests passed; generated contracts and staged static checks pass. Refs: #355 --- .../application/creation_impact.py | 48 + .../opendirector/domain/creation/commands.py | 14 +- .../opendirector/domain/creation/impact.py | 73 ++ .../opendirector/domain/creation/schema.py | 2 + scripts/generate_contracts.py | 2 +- src/contracts/creation.schema.json | 1148 ++++++++++++++++- src/contracts/generated.ts | 128 +- tests/test_generation_impact.py | 154 +++ 8 files changed, 1514 insertions(+), 55 deletions(-) create mode 100644 packages/core/src/opendirector/application/creation_impact.py create mode 100644 packages/core/src/opendirector/domain/creation/impact.py create mode 100644 tests/test_generation_impact.py diff --git a/packages/core/src/opendirector/application/creation_impact.py b/packages/core/src/opendirector/application/creation_impact.py new file mode 100644 index 000000000..2eaec2ebd --- /dev/null +++ b/packages/core/src/opendirector/application/creation_impact.py @@ -0,0 +1,48 @@ +"""Read current business bindings and adopted execution evidence without mutations.""" +from collections.abc import Mapping +from uuid import UUID + +from opendirector.domain.creation.generation import ResolvedReference +from opendirector.domain.creation.impact import ImpactDependency +from opendirector.domain.creation.project import ProjectSnapshot +from opendirector.domain.creation.validation import ContractError + +MAX_IMPACT_EDGES = 20000 + + +def build_generation_dependencies( + snapshot: ProjectSnapshot, + resolved_by_spec: Mapping[UUID, tuple[ResolvedReference, ...] | None], +) -> tuple[ImpactDependency, ...]: + """Only current follow bindings propagate; content identity is not source identity.""" + items = {item.id: item for item in snapshot.canvasItems} + resolved = {spec_id: None if values is None else _by_reference(values) + for spec_id, values in resolved_by_spec.items()} + edges = [] + for reference in snapshot.references: + if not reference.active or reference.binding != 'follow_current': + continue + source = items.get(reference.source.id) + source_spec = (source.binding.objectRef.id if source is not None + and source.binding.role == 'generation' and source.binding.materialOverride is None else None) + by_ref = resolved.get(reference.targetSpecId) + values = by_ref.get(reference.id) if by_ref is not None else None + # A missing resolution is explicit uncertainty, never "no dependencies". + for value in values or (None,): + if value is not None and value.transmission == 'context_only': + continue + edges.append(ImpactDependency(sourceSpecId=source_spec, sourceItemId=reference.source.id, + targetSpecId=reference.targetSpecId, referenceId=reference.id, + role=value.role if value else reference.role, assetId=value.asset.assetId if value else None, + documentId=value.documentVersion.id if value and value.documentVersion else None, + inputConfirmed=value is not None)) + if len(edges) > MAX_IMPACT_EDGES: + raise ContractError('impact_scope_exceeded', '依赖分析超出节点或参考数量上限。') + return tuple(edges) + + +def _by_reference(values): + grouped = {} + for value in values: + grouped.setdefault(value.referenceId, []).append(value) + return grouped diff --git a/packages/core/src/opendirector/domain/creation/commands.py b/packages/core/src/opendirector/domain/creation/commands.py index e79902c46..a6bb31ab4 100644 --- a/packages/core/src/opendirector/domain/creation/commands.py +++ b/packages/core/src/opendirector/domain/creation/commands.py @@ -408,6 +408,7 @@ def command_fingerprint(command: Command) -> str: from opendirector.domain.timeline_errors import TimelineIssueCode IssueCode = Literal[TimelineIssueCode, 'invalid_input', 'revision_conflict', 'role_restricted', 'missing_object', 'reference_invalid', 'image_quality_unsupported', + 'impact_scope_exceeded', 'bigmodel_video_model', 'bigmodel_video_output', 'bigmodel_video_image', 'bigmodel_video_frames', 'bigmodel_video_prompt', 'bigmodel_video_cancel', 'kling_model', 'kling_mode', 'kling_image', 'kling_frames', 'kling_prompt', 'kling_aspect', 'kling_output', 'kling_cancel', @@ -461,6 +462,17 @@ class QueryBase(Contract): projectId: UUID = Field(description='Owning project ID.') +class GenerationImpactQuery(QueryBase): + type: Literal['generation.impact'] = Field(description='Read adopted-result reuse and dependency impact; never submits, adopts or edits. Limited to 20000 reference edges.') + rootSpecIds: tuple[UUID, ...] = Field(min_length=1, max_length=100, description='Unique generation configuration roots belonging to this project.') + maxNodes: int = Field(default=2000, strict=True, ge=1, le=10000, description='Maximum project generation configurations to analyze; overflow fails without a partial report.') + + @model_validator(mode='after') + def roots(self): + unique(self.rootSpecIds, 'impact roots') + return self + + class ProjectQuery(QueryBase): type: Literal['project.get'] = Field(description='Read the current project.') @@ -502,7 +514,7 @@ class AssetPreviewQuery(QueryBase): Query = Annotated[ProjectQuery | ObjectQuery | VersionsQuery | AssetSearchQuery | AssetUsageQuery | - CanvasStatusQuery | AssetPreviewQuery, Field(discriminator='type')] + CanvasStatusQuery | AssetPreviewQuery | GenerationImpactQuery, Field(discriminator='type')] class ChangedObject(Contract): diff --git a/packages/core/src/opendirector/domain/creation/impact.py b/packages/core/src/opendirector/domain/creation/impact.py new file mode 100644 index 000000000..fc9a29b91 --- /dev/null +++ b/packages/core/src/opendirector/domain/creation/impact.py @@ -0,0 +1,73 @@ +"""Reconstructible, read-only dependency and adopted-result reuse evidence.""" +from typing import Literal +from uuid import UUID + +from pydantic import Field, model_validator + +from .base import Contract, Digest, Identifier, ObjectVersion, Revision, unique + + +class ImpactReason(Contract): + code: Literal['inputs_changed', 'upstream_pending', 'output_unavailable', 'baseline_missing', + 'input_unresolved', 'model_unresolved', 'dependency_unresolved', 'execution_basis_incomplete', + 'dependency_cycle'] = Field(description='Stable explanation code, localized only by the display layer.') + objectId: UUID | None = Field(default=None, description='Related business object identity, when known.') + referenceId: UUID | None = Field(default=None, description='Related current reference identity, when known.') + fieldPaths: tuple[Literal['spec.prompt', 'spec.promptContent', 'spec.parameters', 'model', 'references'], ...] = Field( + default=(), description='Allowlisted changed input sections; no user content or connection details.') + + +class ImpactDependency(Contract): + sourceSpecId: UUID | None = Field(default=None, description='Generation source followed by this binding, if any; retained subject assets and overrides do not follow a spec.') + sourceItemId: UUID = Field(description='Logical source canvas identity, including hidden sources.') + targetSpecId: UUID = Field(description='Consumer generation configuration identity.') + referenceId: UUID = Field(description='Current follow_current reference identity; historical and pinned usages are excluded.') + role: Literal['reference', 'first_frame', 'last_frame', 'continuation'] = Field(description='Resolved reference purpose.') + assetId: UUID | None = Field(default=None, description='Actual resolved input asset, absent when unresolved.') + documentId: UUID | None = Field(default=None, description='Retained subject document supplying this asset.') + inputConfirmed: bool = Field(description='Whether the current resolver confirmed this transmitted input. False is uncertainty, not an empty dependency.') + + +class TimelineImpactConsumer(Contract): + editorDocumentId: UUID = Field(description='Current timeline document identity.') + revision: Revision = Field(description='Timeline document revision read by this report.') + clipId: Identifier = Field(description='Retained timeline clip identity.') + assetId: UUID = Field(description='Asset currently retained in this clip; the query never replaces it.') + specIds: tuple[UUID, ...] = Field(description='Related generation specs from exact result or source identities.') + association: Literal['asset', 'source', 'asset_and_source'] = Field(description='Exact retained result asset, explicit input connection, or both; none implies automatic replacement.') + sourceItemId: UUID | None = Field(default=None, description='Source item from the document input connection, when relevant.') + + +class GenerationImpactItem(Contract): + specId: UUID = Field(description='Generation configuration identity.') + specRevision: Revision = Field(description='Configuration revision read by this report.') + currentResultId: UUID | None = Field(default=None, description='Currently adopted result, never an unadopted candidate.') + baselineJobId: UUID | None = Field(default=None, description='Successful job owning the adopted result.') + baselineInputFingerprint: Digest | None = Field(default=None, description='Verified adopted job input fingerprint.') + currentInputFingerprint: Digest | None = Field(default=None, description='Reconstructed current input fingerprint using the acceptance rules.') + inputState: Literal['equal', 'changed', 'unresolved', 'no_baseline'] = Field(description='Current effective inputs compared with the adopted job.') + reuseState: Literal['reusable', 'stale', 'pending_upstream', 'unavailable', 'unknown', 'no_result'] = Field(description='Result reuse evidence, independent of creative approval and remote cache availability.') + relation: Literal['root', 'downstream', 'independent'] = Field(description='Relationship to requested roots, not an invalidation decision.') + upstreamSpecIds: tuple[UUID, ...] = Field(default=(), description='Direct current generation dependencies only; no enumeration of all paths.') + activeJobIds: tuple[UUID, ...] = Field(default=(), description='Active or unresolved job identities; inspect the original jobs before deciding any action.') + reasons: tuple[ImpactReason, ...] = Field(default=(), description='Bounded direct evidence for this decision.') + + +class GenerationImpactReport(Contract): + analysisVersion: Literal[1] = Field(default=1, description='Impact interpretation version.') + projectVersion: ObjectVersion = Field(description='Single authoritative project snapshot version used for this read, not authorization for later writes.') + eventCursor: int = Field(strict=True, ge=0, description='Event cursor from the same project snapshot.') + rootSpecIds: tuple[UUID, ...] = Field(min_length=1, max_length=100, description='Unique requested roots in this project.') + items: tuple[GenerationImpactItem, ...] = Field(max_length=10000, description='All project generation configurations, including independent branches.') + dependencies: tuple[ImpactDependency, ...] = Field(max_length=20000, description='Current effective follow bindings; scope overflow fails instead of truncating.') + timelineConsumers: tuple[TimelineImpactConsumer, ...] = Field(description='Current timeline usages requiring review, never automatic replacement instructions.') + + @model_validator(mode='after') + def identities(self): + unique(self.rootSpecIds, 'impact roots') + unique([item.specId for item in self.items], 'impact specs') + if not set(self.rootSpecIds).issubset(item.specId for item in self.items): + raise ValueError('Impact roots must belong to the reported specs') + if self.projectVersion.objectType != 'project': + raise ValueError('Impact report requires a project version') + return self diff --git a/packages/core/src/opendirector/domain/creation/schema.py b/packages/core/src/opendirector/domain/creation/schema.py index 2ef31826d..b1dd6bc11 100644 --- a/packages/core/src/opendirector/domain/creation/schema.py +++ b/packages/core/src/opendirector/domain/creation/schema.py @@ -7,6 +7,7 @@ from .commands import Command, CommandReceipt, ProjectEvent, Query from .editors import EditorDocument from .generation import ExecutionParameters, GenerationSpec, InputSnapshot, Job, PromptPart, Reference, ResultVersion +from .impact import GenerationImpactReport from .models import ModelConfigPublic, ModelConfigWrite, ModelKind, VideoMode from .project import ProjectSnapshot, ViewState from .timeline_packages import TimelinePackageManifest, TimelinePackageImportRequest, TimelinePackageImportReceipt @@ -21,6 +22,7 @@ class CreationContracts(Contract): command: Command = Field(description='Immutable command recorded in this commit.') receipt: CommandReceipt = Field(description='Immutable command execution receipt.') query: Query = Field(description='Read-only project query.') + generationImpact: GenerationImpactReport = Field(description='Read-only generation dependency and result reuse report.') event: ProjectEvent = Field(description='Project change event, if emitted.') job: Job = Field(description='Generation execution record.') result: ResultVersion = Field(description='Generated result schema.') diff --git a/scripts/generate_contracts.py b/scripts/generate_contracts.py index 20426da25..ba14be40b 100644 --- a/scripts/generate_contracts.py +++ b/scripts/generate_contracts.py @@ -17,7 +17,7 @@ from opendirector.domain.creation.schema import ALIASES, CreationContracts from opendirector.domain.rule_facts import typescript_module -MODULES = ('base', 'assets', 'models', 'generation', 'editors', 'canvas', 'project', 'commands', 'timeline_packages', 'schema') +MODULES = ('base', 'assets', 'models', 'generation', 'impact', 'editors', 'canvas', 'project', 'commands', 'timeline_packages', 'schema') def models(): diff --git a/src/contracts/creation.schema.json b/src/contracts/creation.schema.json index cd5f01137..e1f6732b5 100644 --- a/src/contracts/creation.schema.json +++ b/src/contracts/creation.schema.json @@ -3789,6 +3789,7 @@ "missing_object", "reference_invalid", "image_quality_unsupported", + "impact_scope_exceeded", "bigmodel_video_model", "bigmodel_video_output", "bigmodel_video_image", @@ -4233,6 +4234,7 @@ "asset.usage": "#/$defs/AssetUsageQuery", "canvas.status": "#/$defs/CanvasStatusQuery", "canvas.versions": "#/$defs/VersionsQuery", + "generation.impact": "#/$defs/GenerationImpactQuery", "generationSpec.versions": "#/$defs/VersionsQuery", "job.get": "#/$defs/ObjectQuery", "object.get": "#/$defs/ObjectQuery", @@ -4261,10 +4263,17 @@ }, { "$ref": "#/$defs/AssetPreviewQuery" + }, + { + "$ref": "#/$defs/GenerationImpactQuery" } ], "title": "Query" }, + "generationImpact": { + "$ref": "#/$defs/GenerationImpactReport", + "description": "Read-only generation dependency and result reuse report." + }, "event": { "$ref": "#/$defs/ProjectEvent", "description": "Project change event, if emitted." @@ -4369,6 +4378,7 @@ "command", "receipt", "query", + "generationImpact", "event", "job", "result", @@ -5628,6 +5638,270 @@ "title": "GenerationFailure", "type": "object" }, + "GenerationImpactItem": { + "additionalProperties": false, + "properties": { + "specId": { + "description": "Generation configuration identity.", + "format": "uuid", + "title": "Specid", + "type": "string" + }, + "specRevision": { + "description": "Configuration revision read by this report.", + "minimum": 1, + "title": "Specrevision", + "type": "integer" + }, + "currentResultId": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Currently adopted result, never an unadopted candidate.", + "title": "Currentresultid" + }, + "baselineJobId": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Successful job owning the adopted result.", + "title": "Baselinejobid" + }, + "baselineInputFingerprint": { + "anyOf": [ + { + "pattern": "^[0-9a-f]{64}$", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Verified adopted job input fingerprint.", + "title": "Baselineinputfingerprint" + }, + "currentInputFingerprint": { + "anyOf": [ + { + "pattern": "^[0-9a-f]{64}$", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Reconstructed current input fingerprint using the acceptance rules.", + "title": "Currentinputfingerprint" + }, + "inputState": { + "description": "Current effective inputs compared with the adopted job.", + "enum": [ + "equal", + "changed", + "unresolved", + "no_baseline" + ], + "title": "Inputstate", + "type": "string" + }, + "reuseState": { + "description": "Result reuse evidence, independent of creative approval and remote cache availability.", + "enum": [ + "reusable", + "stale", + "pending_upstream", + "unavailable", + "unknown", + "no_result" + ], + "title": "Reusestate", + "type": "string" + }, + "relation": { + "description": "Relationship to requested roots, not an invalidation decision.", + "enum": [ + "root", + "downstream", + "independent" + ], + "title": "Relation", + "type": "string" + }, + "upstreamSpecIds": { + "default": [], + "description": "Direct current generation dependencies only; no enumeration of all paths.", + "items": { + "format": "uuid", + "type": "string" + }, + "title": "Upstreamspecids", + "type": "array" + }, + "activeJobIds": { + "default": [], + "description": "Active or unresolved job identities; inspect the original jobs before deciding any action.", + "items": { + "format": "uuid", + "type": "string" + }, + "title": "Activejobids", + "type": "array" + }, + "reasons": { + "default": [], + "description": "Bounded direct evidence for this decision.", + "items": { + "$ref": "#/$defs/ImpactReason" + }, + "title": "Reasons", + "type": "array" + } + }, + "required": [ + "specId", + "specRevision", + "inputState", + "reuseState", + "relation" + ], + "title": "GenerationImpactItem", + "type": "object" + }, + "GenerationImpactQuery": { + "additionalProperties": false, + "properties": { + "queryId": { + "description": "Caller-supplied query ID.", + "format": "uuid", + "title": "Queryid", + "type": "string" + }, + "projectId": { + "description": "Owning project ID.", + "format": "uuid", + "title": "Projectid", + "type": "string" + }, + "type": { + "const": "generation.impact", + "description": "Read adopted-result reuse and dependency impact; never submits, adopts or edits. Limited to 20000 reference edges.", + "title": "Type", + "type": "string" + }, + "rootSpecIds": { + "description": "Unique generation configuration roots belonging to this project.", + "items": { + "format": "uuid", + "type": "string" + }, + "maxItems": 100, + "minItems": 1, + "title": "Rootspecids", + "type": "array" + }, + "maxNodes": { + "default": 2000, + "description": "Maximum project generation configurations to analyze; overflow fails without a partial report.", + "maximum": 10000, + "minimum": 1, + "title": "Maxnodes", + "type": "integer" + } + }, + "required": [ + "queryId", + "projectId", + "type", + "rootSpecIds" + ], + "title": "GenerationImpactQuery", + "type": "object" + }, + "GenerationImpactReport": { + "additionalProperties": false, + "properties": { + "analysisVersion": { + "const": 1, + "default": 1, + "description": "Impact interpretation version.", + "title": "Analysisversion", + "type": "integer" + }, + "projectVersion": { + "$ref": "#/$defs/ObjectVersion", + "description": "Single authoritative project snapshot version used for this read, not authorization for later writes." + }, + "eventCursor": { + "description": "Event cursor from the same project snapshot.", + "minimum": 0, + "title": "Eventcursor", + "type": "integer" + }, + "rootSpecIds": { + "description": "Unique requested roots in this project.", + "items": { + "format": "uuid", + "type": "string" + }, + "maxItems": 100, + "minItems": 1, + "title": "Rootspecids", + "type": "array" + }, + "items": { + "description": "All project generation configurations, including independent branches.", + "items": { + "$ref": "#/$defs/GenerationImpactItem" + }, + "maxItems": 10000, + "title": "Items", + "type": "array" + }, + "dependencies": { + "description": "Current effective follow bindings; scope overflow fails instead of truncating.", + "items": { + "$ref": "#/$defs/ImpactDependency" + }, + "maxItems": 20000, + "title": "Dependencies", + "type": "array" + }, + "timelineConsumers": { + "description": "Current timeline usages requiring review, never automatic replacement instructions.", + "items": { + "$ref": "#/$defs/TimelineImpactConsumer" + }, + "title": "Timelineconsumers", + "type": "array" + } + }, + "required": [ + "projectVersion", + "eventCursor", + "rootSpecIds", + "items", + "dependencies", + "timelineConsumers" + ], + "title": "GenerationImpactReport", + "type": "object" + }, "GenerationSpecBase": { "additionalProperties": false, "properties": { @@ -6974,6 +7248,166 @@ "title": "ImageParameters", "type": "object" }, + "ImpactDependency": { + "additionalProperties": false, + "properties": { + "sourceSpecId": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Generation source followed by this binding, if any; retained subject assets and overrides do not follow a spec.", + "title": "Sourcespecid" + }, + "sourceItemId": { + "description": "Logical source canvas identity, including hidden sources.", + "format": "uuid", + "title": "Sourceitemid", + "type": "string" + }, + "targetSpecId": { + "description": "Consumer generation configuration identity.", + "format": "uuid", + "title": "Targetspecid", + "type": "string" + }, + "referenceId": { + "description": "Current follow_current reference identity; historical and pinned usages are excluded.", + "format": "uuid", + "title": "Referenceid", + "type": "string" + }, + "role": { + "description": "Resolved reference purpose.", + "enum": [ + "reference", + "first_frame", + "last_frame", + "continuation" + ], + "title": "Role", + "type": "string" + }, + "assetId": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Actual resolved input asset, absent when unresolved.", + "title": "Assetid" + }, + "documentId": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Retained subject document supplying this asset.", + "title": "Documentid" + }, + "inputConfirmed": { + "description": "Whether the current resolver confirmed this transmitted input. False is uncertainty, not an empty dependency.", + "title": "Inputconfirmed", + "type": "boolean" + } + }, + "required": [ + "sourceItemId", + "targetSpecId", + "referenceId", + "role", + "inputConfirmed" + ], + "title": "ImpactDependency", + "type": "object" + }, + "ImpactReason": { + "additionalProperties": false, + "properties": { + "code": { + "description": "Stable explanation code, localized only by the display layer.", + "enum": [ + "inputs_changed", + "upstream_pending", + "output_unavailable", + "baseline_missing", + "input_unresolved", + "model_unresolved", + "dependency_unresolved", + "execution_basis_incomplete", + "dependency_cycle" + ], + "title": "Code", + "type": "string" + }, + "objectId": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Related business object identity, when known.", + "title": "Objectid" + }, + "referenceId": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Related current reference identity, when known.", + "title": "Referenceid" + }, + "fieldPaths": { + "default": [], + "description": "Allowlisted changed input sections; no user content or connection details.", + "items": { + "enum": [ + "spec.prompt", + "spec.promptContent", + "spec.parameters", + "model", + "references" + ], + "type": "string" + }, + "title": "Fieldpaths", + "type": "array" + } + }, + "required": [ + "code" + ], + "title": "ImpactReason", + "type": "object" + }, "InputRules": { "additionalProperties": false, "properties": { @@ -13311,6 +13745,80 @@ "title": "TimelineFontResource", "type": "object" }, + "TimelineImpactConsumer": { + "additionalProperties": false, + "properties": { + "editorDocumentId": { + "description": "Current timeline document identity.", + "format": "uuid", + "title": "Editordocumentid", + "type": "string" + }, + "revision": { + "description": "Timeline document revision read by this report.", + "minimum": 1, + "title": "Revision", + "type": "integer" + }, + "clipId": { + "description": "Retained timeline clip identity.", + "maxLength": 100, + "minLength": 1, + "pattern": "\\S", + "title": "Clipid", + "type": "string" + }, + "assetId": { + "description": "Asset currently retained in this clip; the query never replaces it.", + "format": "uuid", + "title": "Assetid", + "type": "string" + }, + "specIds": { + "description": "Related generation specs from exact result or source identities.", + "items": { + "format": "uuid", + "type": "string" + }, + "title": "Specids", + "type": "array" + }, + "association": { + "description": "Exact retained result asset, explicit input connection, or both; none implies automatic replacement.", + "enum": [ + "asset", + "source", + "asset_and_source" + ], + "title": "Association", + "type": "string" + }, + "sourceItemId": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Source item from the document input connection, when relevant.", + "title": "Sourceitemid" + } + }, + "required": [ + "editorDocumentId", + "revision", + "clipId", + "assetId", + "specIds", + "association" + ], + "title": "TimelineImpactConsumer", + "type": "object" + }, "TimelinePackageExportFile": { "additionalProperties": false, "properties": { @@ -15821,6 +16329,7 @@ "asset.usage": "#/$defs/AssetUsageQuery", "canvas.status": "#/$defs/CanvasStatusQuery", "canvas.versions": "#/$defs/VersionsQuery", + "generation.impact": "#/$defs/GenerationImpactQuery", "generationSpec.versions": "#/$defs/VersionsQuery", "job.get": "#/$defs/ObjectQuery", "object.get": "#/$defs/ObjectQuery", @@ -15849,10 +16358,17 @@ }, { "$ref": "#/$defs/AssetPreviewQuery" + }, + { + "$ref": "#/$defs/GenerationImpactQuery" } ], "title": "Query" }, + "generationImpact": { + "$ref": "#/$defs/GenerationImpactReport", + "description": "Read-only generation dependency and result reuse report." + }, "event": { "$ref": "#/$defs/ProjectEvent", "description": "Project change event, if emitted." @@ -15957,6 +16473,7 @@ "command", "receipt", "query", + "generationImpact", "event", "job", "result", @@ -19881,6 +20398,7 @@ "missing_object", "reference_invalid", "image_quality_unsupported", + "impact_scope_exceeded", "bigmodel_video_model", "bigmodel_video_output", "bigmodel_video_image", @@ -20327,6 +20845,7 @@ "asset.usage": "#/$defs/AssetUsageQuery", "canvas.status": "#/$defs/CanvasStatusQuery", "canvas.versions": "#/$defs/VersionsQuery", + "generation.impact": "#/$defs/GenerationImpactQuery", "generationSpec.versions": "#/$defs/VersionsQuery", "job.get": "#/$defs/ObjectQuery", "object.get": "#/$defs/ObjectQuery", @@ -20355,10 +20874,17 @@ }, { "$ref": "#/$defs/AssetPreviewQuery" + }, + { + "$ref": "#/$defs/GenerationImpactQuery" } ], "title": "Query" }, + "generationImpact": { + "$ref": "#/$defs/GenerationImpactReport", + "description": "Read-only generation dependency and result reuse report." + }, "event": { "$ref": "#/$defs/ProjectEvent", "description": "Project change event, if emitted." @@ -20463,6 +20989,7 @@ "command", "receipt", "query", + "generationImpact", "event", "job", "result", @@ -21721,61 +22248,334 @@ "description": "Provider error code.", "title": "Providercode" }, - "requestId": { - "anyOf": [ - { - "maxLength": 200, - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Provider request ID.", - "title": "Requestid" + "requestId": { + "anyOf": [ + { + "maxLength": 200, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Provider request ID.", + "title": "Requestid" + }, + "httpStatus": { + "anyOf": [ + { + "maximum": 599, + "minimum": 100, + "type": "integer" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Provider HTTP response status.", + "title": "Httpstatus" + }, + "providerStatus": { + "anyOf": [ + { + "enum": [ + "failed", + "cancelled", + "expired" + ], + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Provider terminal task status.", + "title": "Providerstatus" + } + }, + "required": [ + "category", + "stage", + "message", + "suggestion" + ], + "title": "GenerationFailure", + "type": "object" + }, + "GenerationImpactItem": { + "additionalProperties": false, + "properties": { + "specId": { + "description": "Generation configuration identity.", + "format": "uuid", + "title": "Specid", + "type": "string" + }, + "specRevision": { + "description": "Configuration revision read by this report.", + "minimum": 1, + "title": "Specrevision", + "type": "integer" + }, + "currentResultId": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Currently adopted result, never an unadopted candidate.", + "title": "Currentresultid" + }, + "baselineJobId": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Successful job owning the adopted result.", + "title": "Baselinejobid" + }, + "baselineInputFingerprint": { + "anyOf": [ + { + "pattern": "^[0-9a-f]{64}$", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Verified adopted job input fingerprint.", + "title": "Baselineinputfingerprint" + }, + "currentInputFingerprint": { + "anyOf": [ + { + "pattern": "^[0-9a-f]{64}$", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Reconstructed current input fingerprint using the acceptance rules.", + "title": "Currentinputfingerprint" + }, + "inputState": { + "description": "Current effective inputs compared with the adopted job.", + "enum": [ + "equal", + "changed", + "unresolved", + "no_baseline" + ], + "title": "Inputstate", + "type": "string" + }, + "reuseState": { + "description": "Result reuse evidence, independent of creative approval and remote cache availability.", + "enum": [ + "reusable", + "stale", + "pending_upstream", + "unavailable", + "unknown", + "no_result" + ], + "title": "Reusestate", + "type": "string" + }, + "relation": { + "description": "Relationship to requested roots, not an invalidation decision.", + "enum": [ + "root", + "downstream", + "independent" + ], + "title": "Relation", + "type": "string" + }, + "upstreamSpecIds": { + "default": [], + "description": "Direct current generation dependencies only; no enumeration of all paths.", + "items": { + "format": "uuid", + "type": "string" + }, + "title": "Upstreamspecids", + "type": "array" + }, + "activeJobIds": { + "default": [], + "description": "Active or unresolved job identities; inspect the original jobs before deciding any action.", + "items": { + "format": "uuid", + "type": "string" + }, + "title": "Activejobids", + "type": "array" + }, + "reasons": { + "default": [], + "description": "Bounded direct evidence for this decision.", + "items": { + "$ref": "#/$defs/ImpactReason" + }, + "title": "Reasons", + "type": "array" + } + }, + "required": [ + "specId", + "specRevision", + "currentResultId", + "baselineJobId", + "baselineInputFingerprint", + "currentInputFingerprint", + "inputState", + "reuseState", + "relation", + "upstreamSpecIds", + "activeJobIds", + "reasons" + ], + "title": "GenerationImpactItem", + "type": "object" + }, + "GenerationImpactQuery": { + "additionalProperties": false, + "properties": { + "queryId": { + "description": "Caller-supplied query ID.", + "format": "uuid", + "title": "Queryid", + "type": "string" + }, + "projectId": { + "description": "Owning project ID.", + "format": "uuid", + "title": "Projectid", + "type": "string" + }, + "type": { + "const": "generation.impact", + "description": "Read adopted-result reuse and dependency impact; never submits, adopts or edits. Limited to 20000 reference edges.", + "title": "Type", + "type": "string" + }, + "rootSpecIds": { + "description": "Unique generation configuration roots belonging to this project.", + "items": { + "format": "uuid", + "type": "string" + }, + "maxItems": 100, + "minItems": 1, + "title": "Rootspecids", + "type": "array" + }, + "maxNodes": { + "default": 2000, + "description": "Maximum project generation configurations to analyze; overflow fails without a partial report.", + "maximum": 10000, + "minimum": 1, + "title": "Maxnodes", + "type": "integer" + } + }, + "required": [ + "queryId", + "projectId", + "type", + "rootSpecIds", + "maxNodes" + ], + "title": "GenerationImpactQuery", + "type": "object" + }, + "GenerationImpactReport": { + "additionalProperties": false, + "properties": { + "analysisVersion": { + "const": 1, + "default": 1, + "description": "Impact interpretation version.", + "title": "Analysisversion", + "type": "integer" + }, + "projectVersion": { + "$ref": "#/$defs/ObjectVersion", + "description": "Single authoritative project snapshot version used for this read, not authorization for later writes." }, - "httpStatus": { - "anyOf": [ - { - "maximum": 599, - "minimum": 100, - "type": "integer" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Provider HTTP response status.", - "title": "Httpstatus" + "eventCursor": { + "description": "Event cursor from the same project snapshot.", + "minimum": 0, + "title": "Eventcursor", + "type": "integer" }, - "providerStatus": { - "anyOf": [ - { - "enum": [ - "failed", - "cancelled", - "expired" - ], - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Provider terminal task status.", - "title": "Providerstatus" + "rootSpecIds": { + "description": "Unique requested roots in this project.", + "items": { + "format": "uuid", + "type": "string" + }, + "maxItems": 100, + "minItems": 1, + "title": "Rootspecids", + "type": "array" + }, + "items": { + "description": "All project generation configurations, including independent branches.", + "items": { + "$ref": "#/$defs/GenerationImpactItem" + }, + "maxItems": 10000, + "title": "Items", + "type": "array" + }, + "dependencies": { + "description": "Current effective follow bindings; scope overflow fails instead of truncating.", + "items": { + "$ref": "#/$defs/ImpactDependency" + }, + "maxItems": 20000, + "title": "Dependencies", + "type": "array" + }, + "timelineConsumers": { + "description": "Current timeline usages requiring review, never automatic replacement instructions.", + "items": { + "$ref": "#/$defs/TimelineImpactConsumer" + }, + "title": "Timelineconsumers", + "type": "array" } }, "required": [ - "category", - "stage", - "message", - "suggestion" + "analysisVersion", + "projectVersion", + "eventCursor", + "rootSpecIds", + "items", + "dependencies", + "timelineConsumers" ], - "title": "GenerationFailure", + "title": "GenerationImpactReport", "type": "object" }, "GenerationSpecBase": { @@ -23207,6 +24007,172 @@ "title": "ImageParameters", "type": "object" }, + "ImpactDependency": { + "additionalProperties": false, + "properties": { + "sourceSpecId": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Generation source followed by this binding, if any; retained subject assets and overrides do not follow a spec.", + "title": "Sourcespecid" + }, + "sourceItemId": { + "description": "Logical source canvas identity, including hidden sources.", + "format": "uuid", + "title": "Sourceitemid", + "type": "string" + }, + "targetSpecId": { + "description": "Consumer generation configuration identity.", + "format": "uuid", + "title": "Targetspecid", + "type": "string" + }, + "referenceId": { + "description": "Current follow_current reference identity; historical and pinned usages are excluded.", + "format": "uuid", + "title": "Referenceid", + "type": "string" + }, + "role": { + "description": "Resolved reference purpose.", + "enum": [ + "reference", + "first_frame", + "last_frame", + "continuation" + ], + "title": "Role", + "type": "string" + }, + "assetId": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Actual resolved input asset, absent when unresolved.", + "title": "Assetid" + }, + "documentId": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Retained subject document supplying this asset.", + "title": "Documentid" + }, + "inputConfirmed": { + "description": "Whether the current resolver confirmed this transmitted input. False is uncertainty, not an empty dependency.", + "title": "Inputconfirmed", + "type": "boolean" + } + }, + "required": [ + "sourceSpecId", + "sourceItemId", + "targetSpecId", + "referenceId", + "role", + "assetId", + "documentId", + "inputConfirmed" + ], + "title": "ImpactDependency", + "type": "object" + }, + "ImpactReason": { + "additionalProperties": false, + "properties": { + "code": { + "description": "Stable explanation code, localized only by the display layer.", + "enum": [ + "inputs_changed", + "upstream_pending", + "output_unavailable", + "baseline_missing", + "input_unresolved", + "model_unresolved", + "dependency_unresolved", + "execution_basis_incomplete", + "dependency_cycle" + ], + "title": "Code", + "type": "string" + }, + "objectId": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Related business object identity, when known.", + "title": "Objectid" + }, + "referenceId": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Related current reference identity, when known.", + "title": "Referenceid" + }, + "fieldPaths": { + "default": [], + "description": "Allowlisted changed input sections; no user content or connection details.", + "items": { + "enum": [ + "spec.prompt", + "spec.promptContent", + "spec.parameters", + "model", + "references" + ], + "type": "string" + }, + "title": "Fieldpaths", + "type": "array" + } + }, + "required": [ + "code", + "objectId", + "referenceId", + "fieldPaths" + ], + "title": "ImpactReason", + "type": "object" + }, "InputRules": { "additionalProperties": false, "properties": { @@ -29768,6 +30734,81 @@ "title": "TimelineFontResource", "type": "object" }, + "TimelineImpactConsumer": { + "additionalProperties": false, + "properties": { + "editorDocumentId": { + "description": "Current timeline document identity.", + "format": "uuid", + "title": "Editordocumentid", + "type": "string" + }, + "revision": { + "description": "Timeline document revision read by this report.", + "minimum": 1, + "title": "Revision", + "type": "integer" + }, + "clipId": { + "description": "Retained timeline clip identity.", + "maxLength": 100, + "minLength": 1, + "pattern": "\\S", + "title": "Clipid", + "type": "string" + }, + "assetId": { + "description": "Asset currently retained in this clip; the query never replaces it.", + "format": "uuid", + "title": "Assetid", + "type": "string" + }, + "specIds": { + "description": "Related generation specs from exact result or source identities.", + "items": { + "format": "uuid", + "type": "string" + }, + "title": "Specids", + "type": "array" + }, + "association": { + "description": "Exact retained result asset, explicit input connection, or both; none implies automatic replacement.", + "enum": [ + "asset", + "source", + "asset_and_source" + ], + "title": "Association", + "type": "string" + }, + "sourceItemId": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Source item from the document input connection, when relevant.", + "title": "Sourceitemid" + } + }, + "required": [ + "editorDocumentId", + "revision", + "clipId", + "assetId", + "specIds", + "association", + "sourceItemId" + ], + "title": "TimelineImpactConsumer", + "type": "object" + }, "TimelinePackageExportFile": { "additionalProperties": false, "properties": { @@ -32373,6 +33414,7 @@ "asset.usage": "#/$defs/AssetUsageQuery", "canvas.status": "#/$defs/CanvasStatusQuery", "canvas.versions": "#/$defs/VersionsQuery", + "generation.impact": "#/$defs/GenerationImpactQuery", "generationSpec.versions": "#/$defs/VersionsQuery", "job.get": "#/$defs/ObjectQuery", "object.get": "#/$defs/ObjectQuery", @@ -32401,10 +33443,17 @@ }, { "$ref": "#/$defs/AssetPreviewQuery" + }, + { + "$ref": "#/$defs/GenerationImpactQuery" } ], "title": "Query" }, + "generationImpact": { + "$ref": "#/$defs/GenerationImpactReport", + "description": "Read-only generation dependency and result reuse report." + }, "event": { "$ref": "#/$defs/ProjectEvent", "description": "Project change event, if emitted." @@ -32509,6 +33558,7 @@ "command", "receipt", "query", + "generationImpact", "event", "job", "result", diff --git a/src/contracts/generated.ts b/src/contracts/generated.ts index b50ffd4b4..95c31068a 100644 --- a/src/contracts/generated.ts +++ b/src/contracts/generated.ts @@ -421,7 +421,7 @@ export interface ContractInput { } export interface ContractIssueInput extends ContractInput { - readonly code: "timeline_package_invalid" | "timeline_package_too_large" | "timeline_revision_missing" | "timeline_import_missing" | "timeline_import_conflict" | "timeline_registration_rejected" | "timeline_font_too_large" | "timeline_font_unavailable" | "timeline_font_unsupported" | "timeline_font_invalid" | "timeline_font_fingerprint" | "timeline_font_coverage" | "timeline_font_total_bytes" | "timeline_font_unverified" | "timeline_font_mime" | "timeline_bundled_font_fingerprint" | "timeline_bundled_font_unavailable" | "invalid_input" | "revision_conflict" | "role_restricted" | "missing_object" | "reference_invalid" | "image_quality_unsupported" | "bigmodel_video_model" | "bigmodel_video_output" | "bigmodel_video_image" | "bigmodel_video_frames" | "bigmodel_video_prompt" | "bigmodel_video_cancel" | "kling_model" | "kling_mode" | "kling_image" | "kling_frames" | "kling_prompt" | "kling_aspect" | "kling_output" | "kling_cancel" | "capability_unavailable" | "capability_paused" | "capability_connection_changed" | "capability_unsupported" | "preview_expired" | "storage_unavailable" | "submission_unknown" | "provider_error" | "moss_speech_text" | "moss_speech_voice" | "moss_speech_reference" | "moss_prompt_limit" | "moss_image_size" | "moss_image_reference" | "moss_layout_reference" | "bigmodel_image_size" | "bigmodel_image_reference" | "bigmodel_image_prompt" | "minimax_image_reference" | "minimax_image_count" | "minimax_image_bytes" | "minimax_speech_text" | "minimax_speech_voice" | "minimax_speech_reference" | "minimax_speech_model" | "zhipu_speech_text" | "zhipu_speech_voice" | "zhipu_speech_reference" | "voice_library_unsupported" | "voice_connection_changed" | "voice_reference_required" | "voice_transcript_required" | "voice_transcript_too_long" | "voice_description_too_long" | "voice_not_found" | "voice_delete_unsupported" | "voice_consent_required" | "voice_name_invalid" | "voice_audio_invalid" | "voice_format" | "voice_size" | "voice_duration" | "voice_provider_protocol" | "voice_provider_error" | "voice_provider_timeout" | "voice_model_unsupported" | "voice_name_taken" | "voice_provider_quota"; + readonly code: "timeline_package_invalid" | "timeline_package_too_large" | "timeline_revision_missing" | "timeline_import_missing" | "timeline_import_conflict" | "timeline_registration_rejected" | "timeline_font_too_large" | "timeline_font_unavailable" | "timeline_font_unsupported" | "timeline_font_invalid" | "timeline_font_fingerprint" | "timeline_font_coverage" | "timeline_font_total_bytes" | "timeline_font_unverified" | "timeline_font_mime" | "timeline_bundled_font_fingerprint" | "timeline_bundled_font_unavailable" | "invalid_input" | "revision_conflict" | "role_restricted" | "missing_object" | "reference_invalid" | "image_quality_unsupported" | "impact_scope_exceeded" | "bigmodel_video_model" | "bigmodel_video_output" | "bigmodel_video_image" | "bigmodel_video_frames" | "bigmodel_video_prompt" | "bigmodel_video_cancel" | "kling_model" | "kling_mode" | "kling_image" | "kling_frames" | "kling_prompt" | "kling_aspect" | "kling_output" | "kling_cancel" | "capability_unavailable" | "capability_paused" | "capability_connection_changed" | "capability_unsupported" | "preview_expired" | "storage_unavailable" | "submission_unknown" | "provider_error" | "moss_speech_text" | "moss_speech_voice" | "moss_speech_reference" | "moss_prompt_limit" | "moss_image_size" | "moss_image_reference" | "moss_layout_reference" | "bigmodel_image_size" | "bigmodel_image_reference" | "bigmodel_image_prompt" | "minimax_image_reference" | "minimax_image_count" | "minimax_image_bytes" | "minimax_speech_text" | "minimax_speech_voice" | "minimax_speech_reference" | "minimax_speech_model" | "zhipu_speech_text" | "zhipu_speech_voice" | "zhipu_speech_reference" | "voice_library_unsupported" | "voice_connection_changed" | "voice_reference_required" | "voice_transcript_required" | "voice_transcript_too_long" | "voice_description_too_long" | "voice_not_found" | "voice_delete_unsupported" | "voice_consent_required" | "voice_name_invalid" | "voice_audio_invalid" | "voice_format" | "voice_size" | "voice_duration" | "voice_provider_protocol" | "voice_provider_error" | "voice_provider_timeout" | "voice_model_unsupported" | "voice_name_taken" | "voice_provider_quota"; readonly message: string; readonly objectId?: string | null; readonly field?: string | null; @@ -435,7 +435,8 @@ export interface CreationContractsInput extends ContractInput { readonly editorDocument: TimelineDocumentInput | SubjectDocumentInput | LayerDocumentInput | ImageCropDocumentInput | StackDocumentInput | ToolDocumentInput | DirectorDocumentInput | MediaEditDocumentInput; readonly command: ProjectCreateCommandInput | ProjectRenameCommandInput | ProjectTrashCommandInput | ProjectRestoreCommandInput | AssetImportCommandInput | ArtifactPublishCommandInput | AssetWriteTextCommandInput | AssetMetadataCommandInput | AssetDeleteCommandInput | CanvasCreateGenerationCommandInput | CanvasShowCommandInput | CanvasMoveCommandInput | CanvasUpdateCommandInput | CanvasHideCommandInput | CanvasMaterializeCommandInput | CanvasApplyEditCommandInput | CanvasPublishMediaCommandInput | TimelinePublishRenderCommandInput | NodeVersionApplyCommandInput | CanvasConfigureCommandInput | CanvasEditorAttachCommandInput | CanvasEditorDetachCommandInput | SpecCreateCommandInput | SpecUpdateCommandInput | SpecRestoreCommandInput | SpecPromptCommandInput | ReferenceAddCommandInput | ReferenceUpdateCommandInput | ReferenceRestoreCommandInput | ReferenceRemoveCommandInput | GenerationSubmitCommandInput | JobCancelCommandInput | JobRecoverCommandInput | JobCheckpointCommandInput | ResultSelectCommandInput | EditorCreateCommandInput | EditorSaveCommandInput | HistoryUndoCommandInput | HistoryRedoCommandInput | BatchCommandInput; readonly receipt: CommandReceiptInput; - readonly query: ProjectQueryInput | ObjectQueryInput | VersionsQueryInput | AssetSearchQueryInput | AssetUsageQueryInput | CanvasStatusQueryInput | AssetPreviewQueryInput; + readonly query: ProjectQueryInput | ObjectQueryInput | VersionsQueryInput | AssetSearchQueryInput | AssetUsageQueryInput | CanvasStatusQueryInput | AssetPreviewQueryInput | GenerationImpactQueryInput; + readonly generationImpact: GenerationImpactReportInput; readonly event: ProjectEventInput; readonly job: JobInput; readonly result: ResultVersionInput; @@ -569,6 +570,37 @@ export interface GenerationFailureInput { readonly providerStatus?: "failed" | "cancelled" | "expired" | null; } +export interface GenerationImpactItemInput extends ContractInput { + readonly specId: string; + readonly specRevision: number; + readonly currentResultId?: string | null; + readonly baselineJobId?: string | null; + readonly baselineInputFingerprint?: string | null; + readonly currentInputFingerprint?: string | null; + readonly inputState: "equal" | "changed" | "unresolved" | "no_baseline"; + readonly reuseState: "reusable" | "stale" | "pending_upstream" | "unavailable" | "unknown" | "no_result"; + readonly relation: "root" | "downstream" | "independent"; + readonly upstreamSpecIds?: ReadonlyArray; + readonly activeJobIds?: ReadonlyArray; + readonly reasons?: ReadonlyArray; +} + +export interface GenerationImpactQueryInput extends QueryBaseInput { + readonly type: "generation.impact"; + readonly rootSpecIds: ReadonlyArray; + readonly maxNodes?: number; +} + +export interface GenerationImpactReportInput extends ContractInput { + readonly analysisVersion?: 1; + readonly projectVersion: ObjectVersionInput; + readonly eventCursor: number; + readonly rootSpecIds: ReadonlyArray; + readonly items: ReadonlyArray; + readonly dependencies: ReadonlyArray; + readonly timelineConsumers: ReadonlyArray; +} + export interface GenerationSpecBaseInput extends ProjectEntityInput { readonly purpose?: "draft" | "generation"; readonly modelConfigId?: string | null; @@ -699,6 +731,24 @@ export interface ImageParametersInput extends ContractInput { readonly outputFormat?: "png"; } +export interface ImpactDependencyInput extends ContractInput { + readonly sourceSpecId?: string | null; + readonly sourceItemId: string; + readonly targetSpecId: string; + readonly referenceId: string; + readonly role: "reference" | "first_frame" | "last_frame" | "continuation"; + readonly assetId?: string | null; + readonly documentId?: string | null; + readonly inputConfirmed: boolean; +} + +export interface ImpactReasonInput extends ContractInput { + readonly code: "inputs_changed" | "upstream_pending" | "output_unavailable" | "baseline_missing" | "input_unresolved" | "model_unresolved" | "dependency_unresolved" | "execution_basis_incomplete" | "dependency_cycle"; + readonly objectId?: string | null; + readonly referenceId?: string | null; + readonly fieldPaths?: ReadonlyArray<"spec.prompt" | "spec.promptContent" | "spec.parameters" | "model" | "references">; +} + export interface InputRulesInput extends ContractInput { readonly fractionalDuration?: boolean; readonly profile: string; @@ -1371,6 +1421,16 @@ export interface TimelineFontResourceInput extends ContractInput { readonly asset: AssetRefInput; } +export interface TimelineImpactConsumerInput extends ContractInput { + readonly editorDocumentId: string; + readonly revision: number; + readonly clipId: string; + readonly assetId: string; + readonly specIds: ReadonlyArray; + readonly association: "asset" | "source" | "asset_and_source"; + readonly sourceItemId?: string | null; +} + export interface TimelinePackageExportFileInput extends ContractInput { readonly editorId: string; readonly revision: number; @@ -2070,7 +2130,7 @@ export interface Contract { } export interface ContractIssue extends Contract { - readonly code: "timeline_package_invalid" | "timeline_package_too_large" | "timeline_revision_missing" | "timeline_import_missing" | "timeline_import_conflict" | "timeline_registration_rejected" | "timeline_font_too_large" | "timeline_font_unavailable" | "timeline_font_unsupported" | "timeline_font_invalid" | "timeline_font_fingerprint" | "timeline_font_coverage" | "timeline_font_total_bytes" | "timeline_font_unverified" | "timeline_font_mime" | "timeline_bundled_font_fingerprint" | "timeline_bundled_font_unavailable" | "invalid_input" | "revision_conflict" | "role_restricted" | "missing_object" | "reference_invalid" | "image_quality_unsupported" | "bigmodel_video_model" | "bigmodel_video_output" | "bigmodel_video_image" | "bigmodel_video_frames" | "bigmodel_video_prompt" | "bigmodel_video_cancel" | "kling_model" | "kling_mode" | "kling_image" | "kling_frames" | "kling_prompt" | "kling_aspect" | "kling_output" | "kling_cancel" | "capability_unavailable" | "capability_paused" | "capability_connection_changed" | "capability_unsupported" | "preview_expired" | "storage_unavailable" | "submission_unknown" | "provider_error" | "moss_speech_text" | "moss_speech_voice" | "moss_speech_reference" | "moss_prompt_limit" | "moss_image_size" | "moss_image_reference" | "moss_layout_reference" | "bigmodel_image_size" | "bigmodel_image_reference" | "bigmodel_image_prompt" | "minimax_image_reference" | "minimax_image_count" | "minimax_image_bytes" | "minimax_speech_text" | "minimax_speech_voice" | "minimax_speech_reference" | "minimax_speech_model" | "zhipu_speech_text" | "zhipu_speech_voice" | "zhipu_speech_reference" | "voice_library_unsupported" | "voice_connection_changed" | "voice_reference_required" | "voice_transcript_required" | "voice_transcript_too_long" | "voice_description_too_long" | "voice_not_found" | "voice_delete_unsupported" | "voice_consent_required" | "voice_name_invalid" | "voice_audio_invalid" | "voice_format" | "voice_size" | "voice_duration" | "voice_provider_protocol" | "voice_provider_error" | "voice_provider_timeout" | "voice_model_unsupported" | "voice_name_taken" | "voice_provider_quota"; + readonly code: "timeline_package_invalid" | "timeline_package_too_large" | "timeline_revision_missing" | "timeline_import_missing" | "timeline_import_conflict" | "timeline_registration_rejected" | "timeline_font_too_large" | "timeline_font_unavailable" | "timeline_font_unsupported" | "timeline_font_invalid" | "timeline_font_fingerprint" | "timeline_font_coverage" | "timeline_font_total_bytes" | "timeline_font_unverified" | "timeline_font_mime" | "timeline_bundled_font_fingerprint" | "timeline_bundled_font_unavailable" | "invalid_input" | "revision_conflict" | "role_restricted" | "missing_object" | "reference_invalid" | "image_quality_unsupported" | "impact_scope_exceeded" | "bigmodel_video_model" | "bigmodel_video_output" | "bigmodel_video_image" | "bigmodel_video_frames" | "bigmodel_video_prompt" | "bigmodel_video_cancel" | "kling_model" | "kling_mode" | "kling_image" | "kling_frames" | "kling_prompt" | "kling_aspect" | "kling_output" | "kling_cancel" | "capability_unavailable" | "capability_paused" | "capability_connection_changed" | "capability_unsupported" | "preview_expired" | "storage_unavailable" | "submission_unknown" | "provider_error" | "moss_speech_text" | "moss_speech_voice" | "moss_speech_reference" | "moss_prompt_limit" | "moss_image_size" | "moss_image_reference" | "moss_layout_reference" | "bigmodel_image_size" | "bigmodel_image_reference" | "bigmodel_image_prompt" | "minimax_image_reference" | "minimax_image_count" | "minimax_image_bytes" | "minimax_speech_text" | "minimax_speech_voice" | "minimax_speech_reference" | "minimax_speech_model" | "zhipu_speech_text" | "zhipu_speech_voice" | "zhipu_speech_reference" | "voice_library_unsupported" | "voice_connection_changed" | "voice_reference_required" | "voice_transcript_required" | "voice_transcript_too_long" | "voice_description_too_long" | "voice_not_found" | "voice_delete_unsupported" | "voice_consent_required" | "voice_name_invalid" | "voice_audio_invalid" | "voice_format" | "voice_size" | "voice_duration" | "voice_provider_protocol" | "voice_provider_error" | "voice_provider_timeout" | "voice_model_unsupported" | "voice_name_taken" | "voice_provider_quota"; readonly message: string; readonly objectId: string | null; readonly field: string | null; @@ -2084,7 +2144,8 @@ export interface CreationContracts extends Contract { readonly editorDocument: TimelineDocument | SubjectDocument | LayerDocument | ImageCropDocument | StackDocument | ToolDocument | DirectorDocument | MediaEditDocument; readonly command: ProjectCreateCommand | ProjectRenameCommand | ProjectTrashCommand | ProjectRestoreCommand | AssetImportCommand | ArtifactPublishCommand | AssetWriteTextCommand | AssetMetadataCommand | AssetDeleteCommand | CanvasCreateGenerationCommand | CanvasShowCommand | CanvasMoveCommand | CanvasUpdateCommand | CanvasHideCommand | CanvasMaterializeCommand | CanvasApplyEditCommand | CanvasPublishMediaCommand | TimelinePublishRenderCommand | NodeVersionApplyCommand | CanvasConfigureCommand | CanvasEditorAttachCommand | CanvasEditorDetachCommand | SpecCreateCommand | SpecUpdateCommand | SpecRestoreCommand | SpecPromptCommand | ReferenceAddCommand | ReferenceUpdateCommand | ReferenceRestoreCommand | ReferenceRemoveCommand | GenerationSubmitCommand | JobCancelCommand | JobRecoverCommand | JobCheckpointCommand | ResultSelectCommand | EditorCreateCommand | EditorSaveCommand | HistoryUndoCommand | HistoryRedoCommand | BatchCommand; readonly receipt: CommandReceipt; - readonly query: ProjectQuery | ObjectQuery | VersionsQuery | AssetSearchQuery | AssetUsageQuery | CanvasStatusQuery | AssetPreviewQuery; + readonly query: ProjectQuery | ObjectQuery | VersionsQuery | AssetSearchQuery | AssetUsageQuery | CanvasStatusQuery | AssetPreviewQuery | GenerationImpactQuery; + readonly generationImpact: GenerationImpactReport; readonly event: ProjectEvent; readonly job: Job; readonly result: ResultVersion; @@ -2218,6 +2279,37 @@ export interface GenerationFailure { readonly providerStatus?: "failed" | "cancelled" | "expired" | null; } +export interface GenerationImpactItem extends Contract { + readonly specId: string; + readonly specRevision: number; + readonly currentResultId: string | null; + readonly baselineJobId: string | null; + readonly baselineInputFingerprint: string | null; + readonly currentInputFingerprint: string | null; + readonly inputState: "equal" | "changed" | "unresolved" | "no_baseline"; + readonly reuseState: "reusable" | "stale" | "pending_upstream" | "unavailable" | "unknown" | "no_result"; + readonly relation: "root" | "downstream" | "independent"; + readonly upstreamSpecIds: ReadonlyArray; + readonly activeJobIds: ReadonlyArray; + readonly reasons: ReadonlyArray; +} + +export interface GenerationImpactQuery extends QueryBase { + readonly type: "generation.impact"; + readonly rootSpecIds: ReadonlyArray; + readonly maxNodes: number; +} + +export interface GenerationImpactReport extends Contract { + readonly analysisVersion: 1; + readonly projectVersion: ObjectVersion; + readonly eventCursor: number; + readonly rootSpecIds: ReadonlyArray; + readonly items: ReadonlyArray; + readonly dependencies: ReadonlyArray; + readonly timelineConsumers: ReadonlyArray; +} + export interface GenerationSpecBase extends ProjectEntity { readonly purpose: "draft" | "generation"; readonly modelConfigId: string | null; @@ -2348,6 +2440,24 @@ export interface ImageParameters extends Contract { readonly outputFormat: "png"; } +export interface ImpactDependency extends Contract { + readonly sourceSpecId: string | null; + readonly sourceItemId: string; + readonly targetSpecId: string; + readonly referenceId: string; + readonly role: "reference" | "first_frame" | "last_frame" | "continuation"; + readonly assetId: string | null; + readonly documentId: string | null; + readonly inputConfirmed: boolean; +} + +export interface ImpactReason extends Contract { + readonly code: "inputs_changed" | "upstream_pending" | "output_unavailable" | "baseline_missing" | "input_unresolved" | "model_unresolved" | "dependency_unresolved" | "execution_basis_incomplete" | "dependency_cycle"; + readonly objectId: string | null; + readonly referenceId: string | null; + readonly fieldPaths: ReadonlyArray<"spec.prompt" | "spec.promptContent" | "spec.parameters" | "model" | "references">; +} + export interface InputRules extends Contract { readonly fractionalDuration?: boolean; readonly profile: string; @@ -3019,6 +3129,16 @@ export interface TimelineFontResource extends Contract { readonly asset: AssetRef; } +export interface TimelineImpactConsumer extends Contract { + readonly editorDocumentId: string; + readonly revision: number; + readonly clipId: string; + readonly assetId: string; + readonly specIds: ReadonlyArray; + readonly association: "asset" | "source" | "asset_and_source"; + readonly sourceItemId: string | null; +} + export interface TimelinePackageExportFile extends Contract { readonly editorId: string; readonly revision: number; diff --git a/tests/test_generation_impact.py b/tests/test_generation_impact.py new file mode 100644 index 000000000..37a48bd5c --- /dev/null +++ b/tests/test_generation_impact.py @@ -0,0 +1,154 @@ +"""Impact reports follow saved business bindings, never display or historical guesses.""" +from uuid import UUID + +import pytest +from pydantic import TypeAdapter, ValidationError + +from opendirector.application.creation_canvas import current_generation_inputs +from opendirector.application.creation_impact import build_generation_dependencies +from opendirector.domain.creation.commands import Query +from opendirector.domain.creation.generation import InputSnapshot, Job, ResultVersion +from opendirector.domain.creation.models import ModelSnapshot +from opendirector.domain.creation.project import ProjectSnapshot +from test_creation_contracts import asset, asset_ref, entity, model, PROJECT, uid + +pytestmark = pytest.mark.cpu + + +def impact_model(): + public = model() + return ModelSnapshot(modelConfigId=public.id, inputRules=public.inputRules, + **{key: getattr(public, key) for key in + ('kind', 'modelId', 'url', 'protocol', 'connectionType', 'proxyMode', 'videoAdapter')}) + + +def graph(): + """Four adopted image specs: A -> B -> C, with independent D.""" + data = dict(project=dict(id=PROJECT, name='Impact'), generationSpecs=[ + entity(100+i, kind='image', purpose='generation', modelConfigId=uid(20), prompt=f'Shot {i}') + for i in range(4)], canvasItems=[ + entity(200+i, kind='image', binding=dict(role='generation', objectRef=dict(id=uid(100+i)))) + for i in range(4)], assets=[], jobs=[], results=[], references=[]) + for i in range(4): + if i in (1, 2): + data['references'].append(entity(600+i, binding='follow_current', + targetSpecId=uid(100+i), source=dict(id=uid(199+i)))) + state = ProjectSnapshot.model_validate(data) + spec, refs = current_generation_inputs(state, state.generationSpecs[i], impact_model().inputRules) + frozen = InputSnapshot(spec=spec, model=impact_model(), references=refs) + output = asset(300+i, 'image') + job = Job(**entity(400+i, inputSnapshot=frozen, inputFingerprint=frozen.fingerprint(), + execution=dict(kind='image', size='2K'), status='succeeded', recovery='done', + phase='complete', asset=asset_ref(output))) + result = ResultVersion(**entity(500+i, specId=spec.id, jobId=job.id, + asset=job.asset, inputFingerprint=job.inputFingerprint)) + data['assets'].append(output) + data['jobs'].append(job) + data['results'].append(result) + data['generationSpecs'][i]['currentResultId'] = result.id + return ProjectSnapshot.model_validate(data) + + +def resolved(state): + return {s.id: current_generation_inputs(state, s, impact_model().inputRules)[1] + for s in state.generationSpecs} + + +def replace(state, collection, index, **updates): + data = state.model_dump() + data[collection] = list(data[collection]) + data[collection][index].update(updates) + return ProjectSnapshot.model_validate(data) + + +def test_dependency_edges_use_active_business_bindings(): + state = graph() + edges = build_generation_dependencies(state, resolved(state)) + assert [(e.sourceSpecId, e.targetSpecId, e.referenceId, e.inputConfirmed) for e in edges] == [ + (uid(100), uid(101), uid(601), True), (uid(101), uid(102), uid(602), True)] + moved = replace(state, 'canvasItems', 3, position=dict(x=-999, y=-999)) + assert build_generation_dependencies(moved, resolved(moved)) == edges + inactive = replace(state, 'references', 1, active=False) + assert len(build_generation_dependencies(inactive, resolved(inactive))) == 1 + + +def test_pinned_hidden_override_and_subject_bindings(): + state = graph() + hidden = replace(state, 'canvasItems', 1, visible=False) + assert build_generation_dependencies(hidden, resolved(hidden)) == build_generation_dependencies(state, resolved(state)) + pinned = replace(state, 'references', 1, binding='pinned', source=asset_ref(state.assets[1]).model_dump(), + sourceVersion=dict(objectType='canvas_item', id=uid(201), revision=1)) + assert [e.targetSpecId for e in build_generation_dependencies(pinned, resolved(pinned))] == [uid(101)] + # An explicit override wins even when it is the same bytes as a generated result. + data = state.model_dump() + override = asset(310, 'image').model_copy(update={'provenance': state.assets[0].provenance.model_copy(update={'source': 'imported'})}) + data['assets'] = [*state.assets, override] + data['canvasItems'][1]['binding']['materialOverride'] = asset_ref(override).model_dump() + overridden = ProjectSnapshot.model_validate(data) + edge = build_generation_dependencies(overridden, resolved(overridden))[1] + assert edge.sourceSpecId is None and edge.assetId == override.id + data = state.model_dump() + data['editorDocuments'] = [entity(700, kind='subject', data=dict(main=asset_ref(state.assets[0]), + auxiliaries=[asset_ref(state.assets[3])]))] + data['canvasItems'] = [*state.canvasItems, entity(701, kind='subject', + binding=dict(role='editor', objectRef=dict(id=uid(700), kind='subject')))] + data['references'][1]['source']['id'] = uid(701) + subject = ProjectSnapshot.model_validate(data) + edges = [e for e in build_generation_dependencies(subject, resolved(subject)) if e.targetSpecId == uid(102)] + assert {(e.assetId, e.sourceItemId, e.sourceSpecId) for e in edges} == { + (uid(300), uid(701), None), (uid(303), uid(701), None)} + + +def test_historical_usage_does_not_create_live_dependencies(): + state = replace(graph(), 'references', 1, source=dict(id=uid(203))) + assert state.jobs[2].inputSnapshot.references[0].sourceVersion.id == uid(201) + edges = build_generation_dependencies(state, resolved(state)) + assert edges[1].sourceSpecId == uid(103) + inputs = resolved(state) + inputs[uid(102)] = None + uncertain = build_generation_dependencies(state, inputs)[1] + assert uncertain.sourceSpecId == uid(103) and not uncertain.inputConfirmed + assert uncertain.assetId is None + + +def query(**fields): + return TypeAdapter(Query).validate_python(dict(type='generation.impact', queryId=uid(900), + projectId=PROJECT, rootSpecIds=[uid(101)], **fields)) + + +def test_impact_query_is_registered_without_changing_ordinary_queries(): + parsed = query() + assert parsed.rootSpecIds == (uid(101),) and parsed.maxNodes == 2000 + ordinary = TypeAdapter(Query).validate_python(dict(type='project.get', queryId=uid(900), projectId=PROJECT)) + assert ordinary.type == 'project.get' + + +def test_dependency_budget_rejects_partial_reports(): + from opendirector.domain.creation.validation import ContractError + state = graph() + # Construct a trusted in-memory stress fixture without a huge persisted document. + state = state.model_copy(update={'references': tuple( + state.references[0].model_copy(update={'id': uid(10000+i), 'order': i}) for i in range(20001))}) + with pytest.raises(ContractError) as error: + build_generation_dependencies(state, {uid(101): None}) + assert error.value.issue.code == 'impact_scope_exceeded' + + +def test_report_rejects_unknown_states_and_reason_codes(): + from opendirector.domain.creation.impact import GenerationImpactItem, ImpactReason + with pytest.raises(ValidationError): + GenerationImpactItem(specId=uid(100), specRevision=1, inputState='equal', + reuseState='auto_retry', relation='root') + with pytest.raises(ValidationError): + ImpactReason(code='auto_submit') + + +@pytest.mark.parametrize('updates', [ + {'rootSpecIds': []}, {'rootSpecIds': [uid(101), uid(101)]}, {'rootSpecIds': ['invalid']}, + {'rootSpecIds': [UUID(int=i+1000) for i in range(101)]}, + {'maxNodes': 0}, {'maxNodes': 10001}, {'maxNodes': True}, {'maxNodes': '5'}, {'unexpected': True}, +]) +def test_impact_query_rejects_unbounded_or_ambiguous_inputs(updates): + data = dict(type='generation.impact', queryId=uid(900), projectId=PROJECT, rootSpecIds=[uid(101)]) + with pytest.raises(ValidationError): + TypeAdapter(Query).validate_python(data | updates) From 2d07b7b80ae4368cff5ce08c185d93b28c8a2272 Mon Sep 17 00:00:00 2001 From: qingpeng Date: Mon, 23 Nov 2026 16:34:38 -0800 Subject: [PATCH 2/8] [feat] generation: analyze dependencies and adopted result reuse ## summary Compare current inputs with the adopted successful job using the shared snapshot constructor. Report current mismatches separately from pending upstream changes, retain unresolved execution evidence and original job identities, and identify retained timeline usages without mutation. ## validation 35 impact tests passed; 49 generation, recovery, H3, continuation and version regressions passed. Static checks passed. Refs: #355 --- .../application/creation_generation.py | 6 +- .../application/creation_impact.py | 294 +++++++++++++++++- .../domain/creation/generation.py | 10 + tests/test_generation_impact.py | 233 +++++++++++++- 4 files changed, 531 insertions(+), 12 deletions(-) diff --git a/packages/core/src/opendirector/application/creation_generation.py b/packages/core/src/opendirector/application/creation_generation.py index 52b12bc1d..e3b8591eb 100644 --- a/packages/core/src/opendirector/application/creation_generation.py +++ b/packages/core/src/opendirector/application/creation_generation.py @@ -22,7 +22,7 @@ from opendirector.domain.creation.canvas import TextCanvasItem, ImageCanvasItem, VideoCanvasItem, AudioCanvasItem from opendirector.domain.creation.base import ObjectVersion from opendirector.domain.creation.commands import parse_command -from opendirector.domain.creation.generation import (DEFAULT_MUSIC_SECONDS, InputSnapshot, Job, ResultVersion, execution_spec, +from opendirector.domain.creation.generation import (DEFAULT_MUSIC_SECONDS, InputSnapshot, Job, ResultVersion, execution_spec, freeze_input_snapshot, reference_music_seconds, validate_generation) from opendirector.domain.creation.models import ModelConfigPublic, ModelSnapshot from opendirector.domain.creation.project import ProjectSnapshot @@ -403,8 +403,8 @@ def accept(before): if reference.transmission != 'context_only': self.assets.reference_available(command.projectId, reference.asset.assetId) self.provider.validate(spec.kind, config) - snapshot = InputSnapshot(spec=spec.model_copy(update={'currentResultId': None}), - model=ModelSnapshot(modelConfigId=public.id, inputRules=public.inputRules, + snapshot = freeze_input_snapshot(spec, + ModelSnapshot(modelConfigId=public.id, inputRules=public.inputRules, **{k: getattr(public, k) for k in ('kind', 'modelId', 'url', 'protocol', 'connectionType', 'proxyMode', 'videoAdapter')}), references=resolved) # Use the same rendering, protocol validation and parameter resolver # as the established adapters, with immutable media from the facade. diff --git a/packages/core/src/opendirector/application/creation_impact.py b/packages/core/src/opendirector/application/creation_impact.py index 2eaec2ebd..bf72be2ea 100644 --- a/packages/core/src/opendirector/application/creation_impact.py +++ b/packages/core/src/opendirector/application/creation_impact.py @@ -1,11 +1,17 @@ """Read current business bindings and adopted execution evidence without mutations.""" -from collections.abc import Mapping +from collections import deque +from collections.abc import Callable, Mapping from uuid import UUID -from opendirector.domain.creation.generation import ResolvedReference -from opendirector.domain.creation.impact import ImpactDependency +from opendirector.domain.creation.base import ObjectVersion +from opendirector.domain.creation.generation import ResolvedReference, freeze_input_snapshot +from opendirector.domain.creation.impact import ( + GenerationImpactItem, GenerationImpactReport, ImpactDependency, ImpactReason, TimelineImpactConsumer, +) +from opendirector.domain.creation.models import ModelSnapshot from opendirector.domain.creation.project import ProjectSnapshot from opendirector.domain.creation.validation import ContractError +from opendirector.domain.rule_facts import MAX_REFERENCES MAX_IMPACT_EDGES = 20000 @@ -46,3 +52,285 @@ def _by_reference(values): for value in values: grouped.setdefault(value.referenceId, []).append(value) return grouped + + +class _SnapshotIndex: + def __init__(self, snapshot): + self.snapshot = snapshot + self.specs = {s.id: s for s in snapshot.generationSpecs} + self.items = {i.id: i for i in snapshot.canvasItems} + self.assets = {a.id: a for a in snapshot.assets} + self.results = {r.id: r for r in snapshot.results} + self.jobs = {j.id: j for j in snapshot.jobs} + self.documents = {d.id: d for d in snapshot.editorDocuments} + self.references = {} + self.active_jobs = {} + for ref in snapshot.references: + if ref.active: + self.references.setdefault(ref.targetSpecId, []).append(ref) + for job in snapshot.jobs: + if job.status in {'queued', 'running', 'interrupted'} or job.recovery == 'review': + self.active_jobs.setdefault(job.inputSnapshot.spec.id, []).append(job.id) + + def resolution_view(self, spec): + """Narrow the existing resolver's search space without changing any saved facts. + + The resolver reads one level only. Index once, then pass the exact source + objects needed by each spec; avoid rescanning all assets for every edge. + """ + specs, items, assets, results, documents = {spec.id: spec}, {}, {}, {}, {} + refs = self.references.get(spec.id, ()) + for ref in refs: + if ref.binding == 'pinned': + if ref.source.assetId in self.assets: + assets[ref.source.assetId] = self.assets[ref.source.assetId] + continue + source = self.items.get(ref.source.id) + if source is None: + continue + items[source.id] = source + source_assets = [] + if source.binding.role == 'material': + source_assets.append(source.binding.objectRef.assetId) + elif source.binding.role == 'generation': + upstream = self.specs.get(source.binding.objectRef.id) + if upstream: + specs[upstream.id] = upstream + result = self.results.get(upstream.currentResultId) + if result: + results[result.id] = result + source_assets.append(result.asset.assetId) + if source.binding.materialOverride: + source_assets.append(source.binding.materialOverride.assetId) + elif source.kind == 'subject': + doc = self.documents.get(source.binding.objectRef.id) + if doc: + documents[doc.id] = doc + source_assets.extend(a.assetId for a in (doc.data.main, *doc.data.auxiliaries, doc.data.voice) if a) + for key in source_assets: + if key in self.assets: + assets[key] = self.assets[key] + return self.snapshot.model_copy(update=dict(generationSpecs=tuple(specs.values()), + canvasItems=tuple(items.values()), assets=tuple(assets.values()), results=tuple(results.values()), + editorDocuments=tuple(documents.values()), references=tuple(refs))) + + def baseline(self, spec): + result = self.results.get(spec.currentResultId) + job = self.jobs.get(result.jobId) if result else None + if (result is None or job is None or result.specId != spec.id + or job.inputSnapshot.spec.id != spec.id or job.status != 'succeeded' + or job.projectId != self.snapshot.project.id or result.projectId != job.projectId + or job.asset != result.asset or job.inputFingerprint != result.inputFingerprint + or job.inputSnapshot.fingerprint() != job.inputFingerprint): + return None + output = self.assets.get(result.asset.assetId) + if output is None or (output.kind, output.fingerprint) != (result.asset.kind, result.asset.fingerprint): + return None + return job + + +# Ordinary adapter output settings and generated seeds are already captured +# execution facts, not extra input dependencies. Unrecognized extension fields +# (guides, LoRA, external windows, transcription model snapshots, etc.) require +# additional persisted evidence before this query can assert reuse. +_KNOWN_ADAPTER_FIELDS = { + 'text': {'thinking', 'max_tokens'}, + 'image': {'size', 'quality', 'response_format', 'output_format', 'watermark', 'watermark_enabled', + 'num_inference_steps', 'guidance_scale', 'prompt_enhance', 'seed'}, + 'video': {'seconds', 'duration', 'ratio', 'generate_audio', 'size', 'resolution', 'fps', 'num_frames', + 'num_inference_steps', 'guidance_scale', 'seed', 'watermark', 'mode', 'cfg_scale', + 'audio', 'operation', 'route', 'quality'}, + 'audio': {'speaker', 'voice', 'audio_params', 'format', 'sample_rate', 'response_format', + 'delivery_method', 'stream', 'output_format', 'watermark_enabled', 'creation_type', + 'lyrics', 'duration', 'seed', 'score_mode'}, +} + + +def _basis_complete(job): + if job.inputSnapshot.model.inputRules is None: + return False + if job.adapterParameters.keys() - _KNOWN_ADAPTER_FIELDS[job.inputSnapshot.spec.kind]: + return False + # No arbitrary nested adapter data is accepted as known scalar settings. + for key, value in job.adapterParameters.items(): + if key == 'audio_params': + if not isinstance(value, dict) or value.keys() - {'format', 'sample_rate'}: + return False + elif isinstance(value, (dict, list)): + return False + return True + + +def _changed_fields(old, current): + paths = [] + for field in ('prompt', 'promptContent', 'parameters'): + if getattr(old.spec, field) != getattr(current.spec, field): + paths.append('spec.' + field) + if old.model != current.model: + paths.append('model') + # Delegate reference equality to the shared fingerprint, including its + # deliberate exclusions for display labels and audit-only revisions. + if old.model_copy(update={'references': current.references}).fingerprint() != old.fingerprint(): + paths.append('references') + return tuple(paths) + + +def _reachable(seeds, outgoing): + seen = set(seeds) + queue = deque(seeds) + while queue: + for target in outgoing.get(queue.popleft(), ()): + if target not in seen: + seen.add(target) + queue.append(target) + return seen + + +def _cycle_dependents(spec_ids, outgoing): + """Kahn elimination leaves cycles and their dependents, with no recursion.""" + incoming = dict.fromkeys(spec_ids, 0) + for targets in outgoing.values(): + for target in targets: + incoming[target] += 1 + queue = deque(key for key, count in incoming.items() if not count) + while queue: + key = queue.popleft() + for target in outgoing.get(key, ()): + incoming[target] -= 1 + if not incoming[target]: + queue.append(target) + return {key for key, count in incoming.items() if count} + + +def _timeline_consumers(index, related): + by_asset = {} + for result in index.results.values(): + if result.specId in related: + by_asset.setdefault(result.asset.assetId, set()).add(result.specId) + consumers = [] + for document in index.snapshot.editorDocuments: + if document.kind != 'timeline': + continue + connections = {c.slotId: c for c in document.inputConnections} + for track in document.data.tracks: + for clip in track.clips: + asset_specs = by_asset.get(clip.resource.asset.assetId, set()) + connection = connections.get(clip.id) + source = index.items.get(connection.sourceId) if connection else None + source_spec = source.binding.objectRef.id if source and source.binding.role == 'generation' else None + source_specs = {source_spec} if source_spec in related else set() + if not asset_specs and not source_specs: + continue + consumers.append(TimelineImpactConsumer(editorDocumentId=document.id, revision=document.revision, + clipId=clip.id, assetId=clip.resource.asset.assetId, specIds=tuple(sorted(asset_specs | source_specs)), + association='asset_and_source' if asset_specs and source_specs else 'asset' if asset_specs else 'source', + sourceItemId=source.id if source_specs else None)) + return tuple(consumers) + + +def analyze_generation_impact(snapshot: ProjectSnapshot, *, root_spec_ids: tuple[UUID, ...], + models: Mapping[UUID, ModelSnapshot | None], asset_available: Callable[[UUID], bool], + max_nodes: int) -> GenerationImpactReport: + """Compare one snapshot with locally frozen models keyed by modelConfigId. + + Reuse concerns existing assets, not deterministic re-generation, creative + approval, provider health, or the availability of remote continuation cache. + """ + from opendirector.application.creation_canvas import current_generation_inputs + if (type(max_nodes) is not int or not 1 <= max_nodes <= 10000 + or len(snapshot.generationSpecs) > max_nodes + or sum(ref.active for ref in snapshot.references) > MAX_IMPACT_EDGES): + raise ContractError('impact_scope_exceeded', '依赖分析超出节点或参考数量上限。') + index = _SnapshotIndex(snapshot) + if not root_spec_ids or len(root_spec_ids) > 100 or len(set(root_spec_ids)) != len(root_spec_ids): + raise ContractError('invalid_input', '请提供 1 至 100 个不同的生成配置。') + if any(key not in index.specs for key in root_spec_ids): + raise ContractError('missing_object', '生成配置不在当前工程中。') + availability = {} + + def available(key): + if key not in availability: + availability[key] = key in index.assets and asset_available(key) + return availability[key] + + items, resolved = {}, {} + for spec in snapshot.generationSpecs: + reasons, current = [], None + model = models.get(spec.modelConfigId) + resolved[spec.id] = None + if model is None or model.inputRules is None: + reasons.append(ImpactReason(code='model_unresolved', objectId=spec.modelConfigId)) + else: + try: + if len(index.references.get(spec.id, ())) > MAX_REFERENCES: + raise ValueError('Current references exceed the acceptance limit') + effective, refs = current_generation_inputs(index.resolution_view(spec), spec, model.inputRules) + if len(refs) > MAX_REFERENCES: + raise ValueError('Expanded references exceed the acceptance limit') + resolved[spec.id] = refs + missing = next((ref for ref in refs if ref.transmission != 'context_only' and not available(ref.asset.assetId)), None) + if missing: + reasons.append(ImpactReason(code='input_unresolved', objectId=missing.asset.assetId, referenceId=missing.referenceId)) + else: + current = freeze_input_snapshot(effective, model, refs) + except (ValueError, StopIteration, KeyError): + reasons.append(ImpactReason(code='input_unresolved', objectId=spec.id)) + job = index.baseline(spec) if spec.currentResultId else None + input_state, reuse = 'unresolved', 'unknown' + if spec.currentResultId is None: + input_state, reuse = 'no_baseline', 'no_result' + reasons.append(ImpactReason(code='baseline_missing', objectId=spec.id)) + elif job is None: + reasons.append(ImpactReason(code='baseline_missing', objectId=spec.currentResultId)) + else: + if current is not None: + input_state = 'equal' if current.fingerprint() == job.inputFingerprint else 'changed' + if not _basis_complete(job): + reasons.append(ImpactReason(code='execution_basis_incomplete', objectId=job.id)) + elif current is not None: + if not available(job.asset.assetId): + reuse = 'unavailable' + reasons.append(ImpactReason(code='output_unavailable', objectId=job.asset.assetId)) + elif input_state == 'changed': + reuse = 'stale' + reasons.append(ImpactReason(code='inputs_changed', objectId=spec.id, + fieldPaths=_changed_fields(job.inputSnapshot, current))) + else: + reuse = 'reusable' + items[spec.id] = GenerationImpactItem(specId=spec.id, specRevision=spec.revision, + currentResultId=spec.currentResultId, baselineJobId=job.id if job else None, + baselineInputFingerprint=job.inputFingerprint if job else None, + currentInputFingerprint=current.fingerprint() if current else None, + inputState=input_state, reuseState=reuse, relation='independent', + activeJobIds=tuple(index.active_jobs.get(spec.id, ())), reasons=tuple(reasons)) + edges = build_generation_dependencies(snapshot, resolved) + outgoing, incoming = {}, {} + for edge in edges: + incoming.setdefault(edge.targetSpecId, []).append(edge) + if edge.sourceSpecId in index.specs: + outgoing.setdefault(edge.sourceSpecId, []).append(edge.targetSpecId) + related = _reachable(root_spec_ids, outgoing) + cycles = _cycle_dependents(index.specs, outgoing) + uncertain = _reachable({key for key, item in items.items() if item.reuseState == 'unknown'} | cycles, outgoing) + pending = _reachable({key for key, item in items.items() if item.reuseState in {'stale', 'unavailable', 'no_result'}}, outgoing) + for key, item in items.items(): + direct = incoming.get(key, ()) + reasons = list(item.reasons) + reuse = item.reuseState + if key in cycles: + reuse = 'unknown' + reasons.append(ImpactReason(code='dependency_cycle', objectId=key)) + for edge in direct: + if not edge.inputConfirmed or edge.sourceSpecId in uncertain: + reasons.append(ImpactReason(code='dependency_unresolved', objectId=edge.sourceSpecId or edge.sourceItemId, referenceId=edge.referenceId)) + if reuse == 'reusable': + reuse = 'unknown' + elif edge.sourceSpecId in pending and reuse in {'reusable', 'pending_upstream'}: + reuse = 'pending_upstream' + reasons.append(ImpactReason(code='upstream_pending', objectId=edge.sourceSpecId, referenceId=edge.referenceId)) + items[key] = item.model_copy(update=dict(reuseState=reuse, reasons=tuple(reasons), + relation='root' if key in root_spec_ids else 'downstream' if key in related else 'independent', + upstreamSpecIds=tuple(sorted({e.sourceSpecId for e in direct if e.sourceSpecId is not None})))) + return GenerationImpactReport(projectVersion=ObjectVersion(objectType='project', id=snapshot.project.id, + revision=snapshot.project.revision), eventCursor=snapshot.eventCursor, rootSpecIds=root_spec_ids, + items=tuple(items.values()), dependencies=edges, timelineConsumers=_timeline_consumers(index, related)) diff --git a/packages/core/src/opendirector/domain/creation/generation.py b/packages/core/src/opendirector/domain/creation/generation.py index 92b6ff5d8..a29784231 100644 --- a/packages/core/src/opendirector/domain/creation/generation.py +++ b/packages/core/src/opendirector/domain/creation/generation.py @@ -364,6 +364,16 @@ def execution_spec(spec, references, rules): return spec.model_copy(update={'parameters': spec.parameters.model_copy(update={'videoMode': mode})}) +def freeze_input_snapshot(spec: GenerationSpec, model: ModelSnapshot, + references: tuple[ResolvedReference, ...]) -> InputSnapshot: + """Freeze the same normalized creative inputs for acceptance and read-only comparison.""" + if model.inputRules is None: + raise ValueError('Effective input rules are required to freeze current inputs') + effective = execution_spec(spec, references, model.inputRules) + return InputSnapshot(spec=effective.model_copy(update={'purpose': 'generation', 'currentResultId': None}), + model=model, references=references) + + def implicit_text_prompt(spec: GenerationSpec, references: tuple[ResolvedReference, ...] = ()) -> bool: """A connected text reference implicitly supplies an image or video prompt. diff --git a/tests/test_generation_impact.py b/tests/test_generation_impact.py index 37a48bd5c..8b696cc76 100644 --- a/tests/test_generation_impact.py +++ b/tests/test_generation_impact.py @@ -22,17 +22,18 @@ def impact_model(): ('kind', 'modelId', 'url', 'protocol', 'connectionType', 'proxyMode', 'videoAdapter')}) -def graph(): +def graph(count=4, links=((0, 1), (1, 2))): """Four adopted image specs: A -> B -> C, with independent D.""" data = dict(project=dict(id=PROJECT, name='Impact'), generationSpecs=[ entity(100+i, kind='image', purpose='generation', modelConfigId=uid(20), prompt=f'Shot {i}') - for i in range(4)], canvasItems=[ + for i in range(count)], canvasItems=[ entity(200+i, kind='image', binding=dict(role='generation', objectRef=dict(id=uid(100+i)))) - for i in range(4)], assets=[], jobs=[], results=[], references=[]) - for i in range(4): - if i in (1, 2): + for i in range(count)], assets=[], jobs=[], results=[], references=[]) + for i in range(count): + source = next((source for source, target in links if target == i), None) + if source is not None: data['references'].append(entity(600+i, binding='follow_current', - targetSpecId=uid(100+i), source=dict(id=uid(199+i)))) + targetSpecId=uid(100+i), source=dict(id=uid(200+source)))) state = ProjectSnapshot.model_validate(data) spec, refs = current_generation_inputs(state, state.generationSpecs[i], impact_model().inputRules) frozen = InputSnapshot(spec=spec, model=impact_model(), references=refs) @@ -152,3 +153,223 @@ def test_impact_query_rejects_unbounded_or_ambiguous_inputs(updates): data = dict(type='generation.impact', queryId=uid(900), projectId=PROJECT, rootSpecIds=[uid(101)]) with pytest.raises(ValidationError): TypeAdapter(Query).validate_python(data | updates) + + +def report(state=None, *, models=None, missing=(), available=None, roots=(uid(101),), max_nodes=2000): + from opendirector.application.creation_impact import analyze_generation_impact + return analyze_generation_impact(state or graph(), root_spec_ids=roots, + models={uid(20): impact_model()} if models is None else models, + asset_available=available or (lambda key: key not in missing), max_nodes=max_nodes) + + +def by_spec(value): + return {item.specId: item for item in value.items} + + +def new_result(state, index, *, adopt=True, number=1000): + """Build an accepted result from real inputs, independently of the analyzer.""" + from opendirector.domain.creation.generation import execution_spec + spec, refs = current_generation_inputs(state, state.generationSpecs[index], impact_model().inputRules) + frozen = InputSnapshot(spec=execution_spec(spec, refs, impact_model().inputRules).model_copy( + update={'currentResultId': None}), model=impact_model(), references=refs) + output = asset(number, 'image') + job = Job(**entity(number+1, inputSnapshot=frozen, inputFingerprint=frozen.fingerprint(), + execution=dict(kind='image', size='2K'), status='succeeded', recovery='done', phase='complete', + asset=asset_ref(output))) + result = ResultVersion(**entity(number+2, specId=spec.id, jobId=job.id, + asset=job.asset, inputFingerprint=job.inputFingerprint)) + data = state.model_dump() + data.update(assets=[*state.assets, output], jobs=[*state.jobs, job], results=[*state.results, result]) + if adopt: + data['generationSpecs'][index]['currentResultId'] = result.id + return ProjectSnapshot.model_validate(data) + + +def test_unchanged_adopted_results_are_reusable(): + calls = [] + value = report(available=lambda key: calls.append(key) or True) + assert [item.reuseState for item in value.items] == ['reusable'] * 4 + assert [item.relation for item in value.items] == ['independent', 'root', 'downstream', 'independent'] + assert all(item.inputState == 'equal' and item.baselineInputFingerprint == item.currentInputFingerprint for item in value.items) + assert [item.baselineJobId for item in value.items] == [uid(400+i) for i in range(4)] + assert sorted(calls) == [uid(300+i) for i in range(4)] # shared inputs checked once + + +def test_pending_upstream_is_not_current_input_mismatch(): + state = replace(graph(), 'generationSpecs', 1, prompt='Changed B', revision=2) + items = report(state).items + assert [(i.inputState, i.reuseState) for i in items] == [ + ('equal', 'reusable'), ('changed', 'stale'), ('equal', 'pending_upstream'), ('equal', 'reusable')] + assert items[1].reasons[0].fieldPaths == ('spec.prompt',) + assert any(r.code == 'upstream_pending' and r.objectId == uid(101) and r.referenceId == uid(602) for r in items[2].reasons) + + +def test_adoption_changes_direct_consumer_inputs(): + state = graph(5, ((0, 1), (1, 2), (2, 4))) + state = new_result(replace(state, 'generationSpecs', 1, prompt='B2', revision=2), 1) + items = report(state).items + assert [(i.inputState, i.reuseState) for i in items] == [ + ('equal', 'reusable'), ('equal', 'reusable'), ('changed', 'stale'), + ('equal', 'reusable'), ('equal', 'pending_upstream')] + + +def test_candidate_and_pinned_reference_do_not_invalidate(): + state = graph() + candidate = new_result(state, 1, adopt=False) + assert all(i.reuseState == 'reusable' for i in report(candidate).items) + pinned = replace(state, 'references', 1, binding='pinned', source=asset_ref(state.assets[1]).model_dump(), + sourceVersion=dict(objectType='canvas_item', id=uid(201), revision=1)) + pinned = new_result(pinned, 2) # Adopt C generated from a fixed reference. + adopted = new_result(pinned, 1, number=1100) + item = report(adopted).items[2] + assert (item.inputState, item.reuseState, item.relation) == ('equal', 'reusable', 'independent') + + +def test_display_changes_do_not_change_effective_inputs(): + state = replace(graph(), 'canvasItems', 1, position=dict(x=99, y=20), visible=False, revision=2) + state = replace(state, 'assets', 1, name='A renamed file', revision=2) + assert all(i.inputState == 'equal' and i.reuseState == 'reusable' for i in report(state).items) + + +@pytest.mark.parametrize('change,path', [ + ('model', 'model'), ('rules', 'model'), ('connection', 'model'), ('parameters', 'spec.parameters'), + ('identity', 'references'), ('source_identity', 'references'), ('order', 'references'), ('role', 'references'), +]) +def test_model_parameters_order_and_identity_changes_are_detected(change, path): + state = graph() + models = {uid(20): impact_model()} + if change == 'model': + models[uid(20)] = models[uid(20)].model_copy(update={'modelId': 'another-model'}) + elif change == 'rules': + models[uid(20)] = models[uid(20)].model_copy(update={'inputRules': models[uid(20)].inputRules.model_copy(update={'maxImages': 1})}) + elif change == 'connection': + models[uid(20)] = models[uid(20)].model_copy(update={'url': 'https://other.example/v1'}) + elif change == 'parameters': + state = replace(state, 'generationSpecs', 1, parameters=dict(size='1024x1024')) + elif change == 'identity': + data = state.model_dump() + twin = state.assets[0].model_copy(update={'id': uid(999), 'path': f'assets/{uid(999)}'}) + data['assets'] = [*state.assets, twin] + data['canvasItems'][0]['binding'] = dict(role='material', objectRef=asset_ref(twin)) + state = ProjectSnapshot.model_validate(data) + elif change == 'source_identity': + data = state.model_dump() + data['canvasItems'] = [*state.canvasItems, entity(999, kind='image', binding=dict(role='material', objectRef=asset_ref(state.assets[0])))] + data['references'][0]['source']['id'] = uid(999) + state = ProjectSnapshot.model_validate(data) + elif change == 'role': + state = replace(state, 'references', 0, role='first_frame') + else: + data = state.model_dump() + data['references'] = [*state.references, entity(699, binding='follow_current', targetSpecId=uid(101), source=dict(id=uid(203)), order=1)] + state = new_result(ProjectSnapshot.model_validate(data), 1) + data = state.model_dump() + data['references'][0]['order'], data['references'][2]['order'] = 1, 0 + state = ProjectSnapshot.model_validate(data) + item = report(state, models=models).items[1] + assert item.inputState == 'changed' and item.reuseState == 'stale' + assert path in next(r.fieldPaths for r in item.reasons if r.code == 'inputs_changed') + + +def test_missing_output_and_unrecorded_inputs_are_not_reusable(): + state = graph() + missing = report(state, missing=(uid(303),)).items[3] + assert missing.reuseState == 'unavailable' and missing.reasons[0].code == 'output_unavailable' + unresolved = report(state, models={}).items[1] + assert (unresolved.inputState, unresolved.reuseState) == ('unresolved', 'unknown') + assert unresolved.reasons[0].code == 'model_unresolved' + incomplete = replace(state, 'jobs', 1, adapterParameters={'guide_frames': [0, 8], 'adapter': 'external'}) + assert report(incomplete).items[1].reuseState == 'unknown' + assert 'execution_basis_incomplete' in [r.code for r in report(incomplete).items[1].reasons] + # Defensive analyzer checks also reject inconsistent in-memory adopted links. + broken = state.model_copy(update={'results': tuple(r for r in state.results if r.id != uid(501))}) + assert report(broken).items[1].reuseState == 'unknown' + missing_input = report(state, missing=(uid(300),)).items[1] + assert missing_input.reuseState == 'unknown' and missing_input.inputState == 'unresolved' + assert 'input_unresolved' in [r.code for r in missing_input.reasons] + empty = replace(state, 'generationSpecs', 1, currentResultId=None) + assert report(empty).items[1].reuseState == 'no_result' + + +def test_active_and_unknown_jobs_do_not_create_retry_actions(): + state = graph() + active = state.jobs[1].model_copy(update={'id': uid(901), 'status': 'running', 'phase': 'poll', + 'recovery': 'remote', 'externalTaskId': 'original-task', 'asset': None, 'resumeAllowed': True}) + unknown = active.model_copy(update={'id': uid(902), 'status': 'interrupted', 'recovery': 'review', + 'resumeAllowed': False, 'externalTaskId': None}) + state = state.model_copy(update={'jobs': (*state.jobs, active, unknown)}) + before = state.model_dump_json() + item = report(state).items[1] + assert item.reuseState == 'reusable' and item.activeJobIds == (uid(901), uid(902)) + assert state.model_dump_json() == before + assert not {'action', 'submit', 'resume', 'retry'} & set(item.model_dump()) + + +def test_timeline_consumers_are_reported_without_mutation(): + state = graph() + resources = [dict(asset=asset_ref(state.assets[i]), title=f'Clip {i}') for i in (1, 2, 3)] + data = state.model_dump() + data['editorDocuments'] = [entity(800, kind='timeline', revision=3, + inputConnections=[dict(id=uid(801), sourceId=uid(201), slotId='b', asset=asset_ref(state.assets[1]))], + data=dict(fps=24, width=128, height=128, tracks=[dict(id='v', kind='visual', title='Shots', clips=[ + dict(id=key, resource=res, inPoint=0, outPoint=1) for key, res in zip(('b', 'c', 'd'), resources)])]))] + state = new_result(ProjectSnapshot.model_validate(data), 1) # timeline retains B1 + before = state.model_dump_json() + consumers = report(state).timelineConsumers + assert [(c.clipId, c.association, c.assetId, c.specIds, c.revision) for c in consumers] == [ + ('b', 'asset_and_source', uid(301), (uid(101),), 3), + ('c', 'asset', uid(302), (uid(102),), 3)] + assert state.model_dump_json() == before + + +def test_snapshot_normalization_matches_generation_acceptance(tmp_path): + from generation_helpers import new_project, command + from test_creation_generation_service import Provider + from opendirector.application.creation_generation import CreationGeneration + from opendirector.domain.creation.generation import freeze_input_snapshot + from opendirector.infrastructure.model_configs import ModelConfigs + project = new_project(tmp_path) + configs = ModelConfigs(tmp_path) + config = configs.save('video', 'http://127.0.0.1:12345/v1', 'standard-video-fixture', '', + connection_type='self_hosted', protocol='vllm_omni', auth_mode='none', video_adapter='standard', + video_capabilities={'outputs': [{'resolution': '480P', 'width': 832, 'height': 480, 'durations': [5]}], + 'defaultResolution': '480P', 'defaultDuration': 5, 'dimensionStep': 2}) + runner = CreationGeneration(project[0], configs, Provider()) + request = command(project, config, parameters={'videoMode': 'reference', 'resolution': '480P'}) + receipt = runner.prepare(request, session=project[2]) + assert receipt.status == 'accepted' + state = project[0].snapshot(project[1]) + spec, job = state.generationSpecs[-1], state.jobs[-1] + current, refs = current_generation_inputs(state, spec, job.inputSnapshot.model.inputRules) + frozen = freeze_input_snapshot(current, job.inputSnapshot.model, refs) + assert frozen == job.inputSnapshot and frozen.fingerprint() == job.inputFingerprint + assert spec.parameters.videoMode == 'reference' and frozen.spec.parameters.videoMode == 'first_frame' + + +def test_inputs_over_acceptance_limit_are_unresolved_before_fingerprinting(): + state = graph() + data = state.model_dump() + data['references'] = [entity(10000+i, binding='follow_current', targetSpecId=uid(101), + source=dict(id=uid(200)), order=i) for i in range(65)] + item = report(ProjectSnapshot.model_validate(data)).items[1] + assert (item.inputState, item.reuseState) == ('unresolved', 'unknown') + + +@pytest.mark.parametrize('parameters', [ + {'seconds': '5', 'duration': 5, 'num_frames': 124, 'fps': 24, 'seed': 123}, + {'duration': 5, 'generate_audio': True, 'audio': 'native', 'operation': 'text', 'route': '/text2video/fixture'}, +]) +def test_ordinary_adapter_settings_do_not_invent_missing_guide_requirements(parameters): + from opendirector.domain.creation.generation import VideoGenerationSpec + public = model('video') + frozen_model = ModelSnapshot(modelConfigId=public.id, inputRules=public.inputRules, + **{key: getattr(public, key) for key in ('kind', 'modelId', 'url', 'protocol', 'connectionType', 'videoAdapter')}) + frozen = InputSnapshot(spec=VideoGenerationSpec(**entity(100, kind='video', purpose='generation', modelConfigId=public.id)), model=frozen_model) + output = asset(300, 'video') + job = Job(**entity(400, inputSnapshot=frozen, inputFingerprint=frozen.fingerprint(), + execution=dict(kind='video'), asset=asset_ref(output), status='succeeded', recovery='done', + adapterParameters=parameters)) + result = ResultVersion(**entity(500, specId=uid(100), jobId=job.id, asset=job.asset, inputFingerprint=job.inputFingerprint)) + state = ProjectSnapshot(project=dict(id=PROJECT, name='Video'), assets=[output], jobs=[job], results=[result], + generationSpecs=[frozen.spec.model_copy(update={'currentResultId': result.id})]) + assert report(state, models={public.id: frozen_model}, roots=(uid(100),)).items[0].reuseState == 'reusable' From fa5b4c4ca44ab23283951ad002451d9255132f9e Mon Sep 17 00:00:00 2001 From: qingpeng Date: Mon, 23 Nov 2026 16:38:39 -0800 Subject: [PATCH 3/8] [feat] generation: expose impact through shared read-only queries ## summary Serve generation.impact through the existing HTTP, Agent and CLI query paths using one project snapshot and one local model catalog read. Add a typed frontend read and bilingual state/reason text for workbench consumers. ## validation 69 Python query/API/Agent/CLI tests and 33 client tests passed. Contract, import-layer, bilingual catalog, production build and static checks pass. Refs: #355 --- apps/api/src/opendirector_api/localization.py | 1 + packages/core/src/opendirector/agent/tools.py | 5 +- .../application/creation_canvas.py | 3 + .../application/creation_impact.py | 41 ++++ src/backend/creationClient.ts | 18 ++ src/backend/generationImpactText.ts | 33 +++ src/i18n/messages/en-US/generationImpact.ts | 26 +++ src/i18n/messages/en-US/index.ts | 2 + src/i18n/messages/zh-CN/generationImpact.ts | 26 +++ src/i18n/messages/zh-CN/index.ts | 2 + tests/generationImpact.test.ts | 63 ++++++ tests/test_generation_impact_queries.py | 200 ++++++++++++++++++ 12 files changed, 419 insertions(+), 1 deletion(-) create mode 100644 src/backend/generationImpactText.ts create mode 100644 src/i18n/messages/en-US/generationImpact.ts create mode 100644 src/i18n/messages/zh-CN/generationImpact.ts create mode 100644 tests/generationImpact.test.ts create mode 100644 tests/test_generation_impact_queries.py diff --git a/apps/api/src/opendirector_api/localization.py b/apps/api/src/opendirector_api/localization.py index ca5ae3605..67bd3293b 100644 --- a/apps/api/src/opendirector_api/localization.py +++ b/apps/api/src/opendirector_api/localization.py @@ -16,6 +16,7 @@ from opendirector.domain.capability_messages import english_capability_message, missing_tool_model_message ENGLISH_BY_CODE = { + 'impact_scope_exceeded': 'Generation impact exceeds the node or reference limit. Reduce the project scope or increase maxNodes within its supported limit.', "desktop_auth_required": "The desktop connection has expired. Reopen the application.", 'image_quality_unsupported': 'This model does not support the selected image quality. Choose Auto or select another model.', 'bigmodel_video_model': 'The BigModel video protocol supports CogVideoX-3 only.', diff --git a/packages/core/src/opendirector/agent/tools.py b/packages/core/src/opendirector/agent/tools.py index 4753be1d8..078852868 100644 --- a/packages/core/src/opendirector/agent/tools.py +++ b/packages/core/src/opendirector/agent/tools.py @@ -262,7 +262,10 @@ def tools() -> list[dict]: definition['properties'].pop(field) definition['required'].remove(field) result.append(tool_schema('query', f'Query objects, jobs, assets or versions. Valid types: {", ".join(QUERY_TYPES)}. ' - 'canvas.status waits and needs objectId; asset.preview returns media for native viewing.', query_schema)) + 'canvas.status waits and needs objectId; asset.preview returns media for native viewing. ' + 'generation.impact takes rootSpecIds and reports adopted-input reuse, potential downstream impact ' + 'and retained timeline usages without submitting or modifying anything. Inspect original active jobs; ' + 'the report does not authorize retries or guarantee remote cache availability.', query_schema)) command_type = {'type': 'string', 'enum': list(COMMANDS)} result.append(tool_schema('command_schema', 'Read command help before the first execute_command call of that type in this turn. ' 'Find commands with read_project. For the first lookup, pass only the exact type, e.g. {"type":"canvas.show"}. ' diff --git a/packages/core/src/opendirector/application/creation_canvas.py b/packages/core/src/opendirector/application/creation_canvas.py index 99bfcbfcb..df04511b1 100644 --- a/packages/core/src/opendirector/application/creation_canvas.py +++ b/packages/core/src/opendirector/application/creation_canvas.py @@ -851,6 +851,9 @@ async def query(self, query: Query) -> JsonValue: def query_snapshot(self, query): from opendirector.application.creation_history import CreationHistory + if query.type == 'generation.impact': + from opendirector.application.creation_impact import CreationImpact + return CreationImpact(self.projects).query(query) snapshot = self.projects.snapshot(query.projectId) history = CreationHistory(self.projects) if query.type == 'project.get': diff --git a/packages/core/src/opendirector/application/creation_impact.py b/packages/core/src/opendirector/application/creation_impact.py index bf72be2ea..c1b41ce90 100644 --- a/packages/core/src/opendirector/application/creation_impact.py +++ b/packages/core/src/opendirector/application/creation_impact.py @@ -4,6 +4,7 @@ from uuid import UUID from opendirector.domain.creation.base import ObjectVersion +from opendirector.domain.creation.commands import GenerationImpactQuery from opendirector.domain.creation.generation import ResolvedReference, freeze_input_snapshot from opendirector.domain.creation.impact import ( GenerationImpactItem, GenerationImpactReport, ImpactDependency, ImpactReason, TimelineImpactConsumer, @@ -12,10 +13,50 @@ from opendirector.domain.creation.project import ProjectSnapshot from opendirector.domain.creation.validation import ContractError from opendirector.domain.rule_facts import MAX_REFERENCES +from opendirector.domain.projects import ProjectError +from opendirector.ports.gateway import gateway MAX_IMPACT_EDGES = 20000 +class CreationImpact: + def __init__(self, projects): + self.projects = projects + + def query(self, query: GenerationImpactQuery) -> GenerationImpactReport: + from opendirector.application.creation_assets import CreationAssets + from opendirector.application.model_availability import ModelAvailability + snapshot = self.projects.snapshot(query.projectId) + configs = gateway().models(self.projects.local.repository) + availability = ModelAvailability(configs) + models = {} + # One locked catalog read. Effective rules use only cached/local facts; + # never prepare/refresh a capability probe for an impact query. + needed = {spec.modelConfigId for spec in snapshot.generationSpecs} + for public, private in configs.catalog_snapshot(): + identity = UUID(public['id']) + if identity not in needed: + continue + try: + models[identity] = ModelSnapshot(modelConfigId=identity, + inputRules=availability.effective_input_rules(private), + **{key: public[key] for key in + ('kind', 'modelId', 'url', 'protocol', 'connectionType', 'proxyMode', 'videoAdapter')}) + except ValueError: + models[identity] = None + assets = CreationAssets(self.projects) + + def available(asset_id): + try: + assets.reference_available(query.projectId, asset_id, snapshot=snapshot) + return True + except (ProjectError, ContractError, OSError, UnicodeError): + return False + + return analyze_generation_impact(snapshot, root_spec_ids=query.rootSpecIds, models=models, + asset_available=available, max_nodes=query.maxNodes) + + def build_generation_dependencies( snapshot: ProjectSnapshot, resolved_by_spec: Mapping[UUID, tuple[ResolvedReference, ...] | None], diff --git a/src/backend/creationClient.ts b/src/backend/creationClient.ts index 56e05c494..35f1721fa 100644 --- a/src/backend/creationClient.ts +++ b/src/backend/creationClient.ts @@ -6,6 +6,8 @@ import type { CommandInput, CommandReceipt, GenerationSpec, + GenerationImpactReport, + GenerationImpactQueryInput, Job, ObjectVersion, ProjectEvent, @@ -215,6 +217,22 @@ export class CreationClient { this.listeners.delete(listener); }; } + generationImpact( + rootSpecIds: readonly string[], + options: ReadOptions = {}, + ): Promise { + const query: GenerationImpactQueryInput = { + type: "generation.impact", + queryId: crypto.randomUUID(), + projectId: this.id, + rootSpecIds: [...rootSpecIds], + }; + return resilientRead( + (signal) => request(`${creationPath(this.id)}/queries`, { + ...json("POST", query), signal, + }), options, + ); + } async command( type: T, payload: Extract["payload"], diff --git a/src/backend/generationImpactText.ts b/src/backend/generationImpactText.ts new file mode 100644 index 000000000..d037326b6 --- /dev/null +++ b/src/backend/generationImpactText.ts @@ -0,0 +1,33 @@ +import type { Translate } from "../i18n/I18nProvider.tsx"; +import type { MessageKey } from "../i18n/types.ts"; + +const messages: Readonly> = { + reusable: "generationImpact.reusable", + stale: "generationImpact.stale", + pending_upstream: "generationImpact.pending_upstream", + unavailable: "generationImpact.unavailable", + unknown: "generationImpact.unknown", + no_result: "generationImpact.no_result", + equal: "generationImpact.equal", + changed: "generationImpact.changed", + unresolved: "generationImpact.unresolved", + no_baseline: "generationImpact.no_baseline", + root: "generationImpact.root", + downstream: "generationImpact.downstream", + independent: "generationImpact.independent", + inputs_changed: "generationImpact.inputs_changed", + upstream_pending: "generationImpact.upstream_pending", + output_unavailable: "generationImpact.output_unavailable", + baseline_missing: "generationImpact.baseline_missing", + input_unresolved: "generationImpact.input_unresolved", + model_unresolved: "generationImpact.model_unresolved", + dependency_unresolved: "generationImpact.dependency_unresolved", + execution_basis_incomplete: "generationImpact.execution_basis_incomplete", + dependency_cycle: "generationImpact.dependency_cycle", + impact_scope_exceeded: "generationImpact.impact_scope_exceeded", +}; + +/** Localize stable codes without rendering unknown provider or user content. */ +export function generationImpactText(code: string, t: Translate): string { + return t(Object.hasOwn(messages, code) ? messages[code]! : "generationImpact.fallback"); +} diff --git a/src/i18n/messages/en-US/generationImpact.ts b/src/i18n/messages/en-US/generationImpact.ts new file mode 100644 index 000000000..f612c47af --- /dev/null +++ b/src/i18n/messages/en-US/generationImpact.ts @@ -0,0 +1,26 @@ +export const generationImpact = { + "generationImpact.reusable": "Existing result can be reused", + "generationImpact.stale": "Current inputs have changed", + "generationImpact.pending_upstream": "Review after upstream adoption", + "generationImpact.unavailable": "Result file is unavailable", + "generationImpact.unknown": "Insufficient evidence for reuse", + "generationImpact.no_result": "No adopted result", + "generationImpact.equal": "Current inputs match", + "generationImpact.changed": "Current inputs differ", + "generationImpact.unresolved": "Current inputs could not be resolved", + "generationImpact.no_baseline": "No adopted execution to compare", + "generationImpact.root": "Requested source", + "generationImpact.downstream": "Dependent configuration", + "generationImpact.independent": "Independent configuration", + "generationImpact.inputs_changed": "The saved prompt, parameters, model or references differ from the adopted execution.", + "generationImpact.upstream_pending": "Inputs still match, but a changed upstream result may affect them after adoption.", + "generationImpact.output_unavailable": "The adopted result file is missing or could not be verified.", + "generationImpact.baseline_missing": "A trustworthy adopted result and successful job could not be found.", + "generationImpact.input_unresolved": "A current reference or its file could not be verified.", + "generationImpact.model_unresolved": "The current model configuration or effective input rules are unavailable.", + "generationImpact.dependency_unresolved": "A current dependency has incomplete evidence. Inspect its original objects and jobs.", + "generationImpact.execution_basis_incomplete": "Additional adapter or guide inputs were recorded but cannot be reconstructed from this project.", + "generationImpact.dependency_cycle": "This configuration is in or depends on a reference cycle; no execution order is inferred.", + "generationImpact.impact_scope_exceeded": "Impact analysis exceeds the supported node or reference limit.", + "generationImpact.fallback": "Impact details are unavailable. Refresh the report or inspect the original job.", +}; diff --git a/src/i18n/messages/en-US/index.ts b/src/i18n/messages/en-US/index.ts index 86adf91ae..a25b353aa 100644 --- a/src/i18n/messages/en-US/index.ts +++ b/src/i18n/messages/en-US/index.ts @@ -14,6 +14,7 @@ import { common } from "./common.ts"; import { editors } from "./editors.ts"; import { errors } from "./errors.ts"; import { generation } from "./generation.ts"; +import { generationImpact } from "./generationImpact.ts"; import { library } from "./library.ts"; import { models } from "./models.ts"; import { settings } from "./settings.ts"; @@ -36,6 +37,7 @@ export const enUS: Record = { ...canvasNodes, ...canvasWorkspace, ...generation, + ...generationImpact, ...tools, ...editors, ...timeline, diff --git a/src/i18n/messages/zh-CN/generationImpact.ts b/src/i18n/messages/zh-CN/generationImpact.ts new file mode 100644 index 000000000..9d25e17d5 --- /dev/null +++ b/src/i18n/messages/zh-CN/generationImpact.ts @@ -0,0 +1,26 @@ +export const generationImpact = { + "generationImpact.reusable": "已有结果可复用", + "generationImpact.stale": "当前输入已变化", + "generationImpact.pending_upstream": "上游采用新结果后需复核", + "generationImpact.unavailable": "结果文件不可用", + "generationImpact.unknown": "复用依据不足", + "generationImpact.no_result": "尚无采用结果", + "generationImpact.equal": "当前输入相同", + "generationImpact.changed": "当前输入不同", + "generationImpact.unresolved": "当前输入无法确定", + "generationImpact.no_baseline": "没有可比较的已采用执行", + "generationImpact.root": "本次查询起点", + "generationImpact.downstream": "下游生成配置", + "generationImpact.independent": "独立生成配置", + "generationImpact.inputs_changed": "已保存的提示词、参数、模型或参考与当前采用结果的执行输入不同。", + "generationImpact.upstream_pending": "当前输入仍相同,但上游采用变化后的结果可能影响这些输入。", + "generationImpact.output_unavailable": "采用结果的文件缺失或未能通过校验。", + "generationImpact.baseline_missing": "未找到可信的采用结果及其成功任务。", + "generationImpact.input_unresolved": "当前参考关系或参考文件未能通过校验。", + "generationImpact.model_unresolved": "当前模型配置或有效输入规则不可用。", + "generationImpact.dependency_unresolved": "当前依赖的依据不完整,请检查原始对象和任务。", + "generationImpact.execution_basis_incomplete": "已记录额外适配器或引导输入,但无法从当前工程重建这些依据。", + "generationImpact.dependency_cycle": "该配置处于参考环中或依赖参考环,报告不推断执行顺序。", + "generationImpact.impact_scope_exceeded": "依赖分析超出支持的节点或参考数量上限。", + "generationImpact.fallback": "暂时无法解释该影响状态,请刷新报告或检查原任务。", +}; diff --git a/src/i18n/messages/zh-CN/index.ts b/src/i18n/messages/zh-CN/index.ts index 96bde2cda..7e2c92f59 100644 --- a/src/i18n/messages/zh-CN/index.ts +++ b/src/i18n/messages/zh-CN/index.ts @@ -13,6 +13,7 @@ import { common } from "./common.ts"; import { editors } from "./editors.ts"; import { errors } from "./errors.ts"; import { generation } from "./generation.ts"; +import { generationImpact } from "./generationImpact.ts"; import { library } from "./library.ts"; import { models } from "./models.ts"; import { settings } from "./settings.ts"; @@ -33,6 +34,7 @@ export const zhCN = { ...canvasNodes, ...canvasWorkspace, ...generation, + ...generationImpact, ...tools, ...editors, ...timeline, diff --git a/tests/generationImpact.test.ts b/tests/generationImpact.test.ts new file mode 100644 index 000000000..1875a7bba --- /dev/null +++ b/tests/generationImpact.test.ts @@ -0,0 +1,63 @@ +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import test from "node:test"; +import { CreationClient } from "../src/backend/creationClient.ts"; +import { generationImpactText } from "../src/backend/generationImpactText.ts"; +import { catalogs, setActiveLocale } from "../src/i18n/messages.ts"; +import { defaultTranslate as tNow } from "../src/canvas/assistantTranslate.ts"; +import type { GenerationImpactReport, ProjectSnapshot } from "../src/contracts/generated.ts"; + +test("impact reads send the typed query without opening a session or replacing a newer snapshot", async () => { + const snapshot = JSON.parse(readFileSync(new URL("fixtures/creation-project.json", import.meta.url), "utf8")) as ProjectSnapshot; + const client = new CreationClient(snapshot.project.id); + client.install(snapshot); + const newer = { ...snapshot, eventCursor: snapshot.eventCursor + 1 }; + const report = { analysisVersion: 1, projectVersion: { objectType: "project", id: snapshot.project.id, revision: snapshot.project.revision }, + eventCursor: snapshot.eventCursor, rootSpecIds: [snapshot.generationSpecs[0]!.id], items: [], dependencies: [], timelineConsumers: [] } satisfies GenerationImpactReport; + const original = globalThis.fetch; + let requests = 0; + globalThis.fetch = async (url, options) => { + requests++; + assert.equal(url, `/api/creation/projects/${snapshot.project.id}/queries`); + assert.equal(options?.method, "POST"); + const query = JSON.parse(String(options?.body)); + assert.equal(query.type, "generation.impact"); + assert.equal(query.projectId, snapshot.project.id); + assert.deepEqual(query.rootSpecIds, report.rootSpecIds); + assert.match(query.queryId, /^[0-9a-f-]{36}$/); + assert.ok(options?.signal); + client.install(newer); + return Response.json(report); + }; + try { + assert.deepEqual(await client.generationImpact(report.rootSpecIds), report); + assert.equal(client.snapshot, newer); + assert.equal(requests, 1); + } finally { globalThis.fetch = original; } +}); + +test("impact states, reasons and fallback switch languages without changing business codes", () => { + const schema = JSON.parse(readFileSync(new URL("../src/contracts/creation.schema.json", import.meta.url), "utf8")); + const defs = schema.output.$defs; + const codes = [...defs.GenerationImpactItem.properties.reuseState.enum, + ...defs.GenerationImpactItem.properties.inputState.enum, + ...defs.GenerationImpactItem.properties.relation.enum, + ...defs.ImpactReason.properties.code.enum, "impact_scope_exceeded"]; + const localized: Record = {}; + try { + for (const locale of ["en-US", "zh-CN"] as const) { + setActiveLocale(locale); + localized[locale] = codes.map(code => { + const value = generationImpactText(code, tNow); + assert.notEqual(value, code); + assert.notEqual(value, generationImpactText("future_code", tNow)); + assert.equal(typeof catalogs[locale][`generationImpact.${code}`], "string"); + assert.equal(/[\u3400-\u9fff]/.test(value), locale === "zh-CN"); + return value; + }); + const fallback = generationImpactText("", tNow); + assert.ok(fallback && !fallback.includes("script")); + } + assert.notDeepEqual(localized["en-US"], localized["zh-CN"]); + } finally { setActiveLocale("zh-CN"); } +}); diff --git a/tests/test_generation_impact_queries.py b/tests/test_generation_impact_queries.py new file mode 100644 index 000000000..7a72bd3db --- /dev/null +++ b/tests/test_generation_impact_queries.py @@ -0,0 +1,200 @@ +"""Shared query entry points against committed projects and real small image files.""" +import asyncio +import hashlib +from io import BytesIO +import json +from uuid import UUID, uuid4 + +from fastapi.testclient import TestClient +from PIL import Image +import pytest +from typer.testing import CliRunner + +from generation_helpers import command, new_project, settled +from opendirector import cli +from opendirector.agent.tools import AgentTools +from opendirector.application.creation_canvas import CreationCanvas +from opendirector.application.creation_generation import CreationGeneration +from opendirector.domain.creation.commands import GenerationImpactQuery, parse_command +from opendirector.infrastructure.model_configs import ModelConfigs +from opendirector.integrations.capability_probe import CapabilityProbe +from opendirector_api.main import create_app +from test_creation_canvas_service import send, ver +from test_generation_impact import graph, report, replace, uid + +pytestmark = pytest.mark.cpu + + +class ImageProvider: + """Only model execution is replaced; acceptance, files and adoption are real.""" + def __init__(self): + self.calls = 0 + + def validate(self, kind, config): + assert kind == 'image' + + async def generate(self, config, task, submitted): + self.calls += 1 + stream = BytesIO() + Image.new('RGB', (16, 16), (self.calls * 20, 100, 120)).save(stream, 'PNG') + return 'png', stream.getvalue() + + +@pytest.fixture +def saved(tmp_path): + project = new_project(tmp_path, 'Dependency case') + store, pid, session = project + configs = ModelConfigs(tmp_path) + config = configs.save('image', 'http://127.0.0.1:12345/v1', 'fixture-image', '', + connection_type='self_hosted', auth_mode='none', protocol='openai') + provider = ImageProvider() + runner = CreationGeneration(store, configs, provider) + specs, items = [], [] + + async def build(): + for index in range(4): + request = command(project, config, prompt=f'Frame {index}') + state = store.snapshot(pid) + spec, item = state.generationSpecs[-1], state.canvasItems[-1] + if index in (1, 2): + receipt = send(store, pid, 'reference.add', session=session, + versions=[ver('generation_spec', spec), ver('canvas_item', item)], reference=dict( + id=uuid4(), projectId=pid, targetSpecId=spec.id, binding='follow_current', + source=dict(id=items[-1]))) + assert receipt.status == 'applied', receipt + state = store.snapshot(pid) + spec = next(s for s in state.generationSpecs if s.id == spec.id) + item = next(i for i in state.canvasItems if i.id == item.id) + request = parse_command(dict(commandId=request.commandId, projectId=pid, type='generation.submit', + expectedVersions=[ver('generation_spec', spec), ver('canvas_item', item)], + payload=dict(specId=spec.id, expectedSpecRevision=spec.revision, originItemId=item.id))) + receipt = await runner.execute(request, session=session) + assert receipt.status == 'accepted', receipt + await settled(runner) + state = store.snapshot(pid) + assert state.jobs[-1].status == 'succeeded' + assert next(s for s in state.generationSpecs if s.id == spec.id).currentResultId is not None + specs.append(spec.id) + items.append(item.id) + await runner.close() + + asyncio.run(build()) + return project, configs, runner, provider, specs, items + + +def impact_query(pid, roots, **kwargs): + return GenerationImpactQuery(type='generation.impact', queryId=uuid4(), projectId=pid, + rootSpecIds=tuple(roots), **kwargs) + + +def test_http_agent_and_cli_share_impact_report(saved, tmp_path, monkeypatch): + (store, pid, session), configs, runner, provider, specs, _ = saved + query = impact_query(pid, [specs[1]]) + api = TestClient(create_app(store.local, generation_provider=provider), headers={'X-OpenDirector-Request': '1'}) + response = api.post(f'/api/creation/projects/{pid}/queries', json=query.model_dump(mode='json')) + assert response.status_code == 200, response.text + expected = response.json() + agent = asyncio.run(AgentTools(store, runner, configs).execute(pid, uuid4(), session, 'impact', + 'query', dict(type='generation.impact', rootSpecIds=[str(specs[1])]), [], None)) + assert agent == expected + params = tmp_path / 'impact-query.json' + params.write_text(json.dumps(dict(rootSpecIds=[str(specs[1])])), encoding='utf-8') + for key in ('OPENDIRECTOR_AGENT_SOCKET', 'OPENDIRECTOR_AGENT_HOST', 'OPENDIRECTOR_PROJECT'): + monkeypatch.delenv(key, raising=False) + monkeypatch.setattr(cli.httpx, 'Client', lambda **kwargs: api) + result = CliRunner().invoke(cli.app, ['--project', str(pid), 'query', 'generation.impact', '--file', str(params)]) + assert result.exit_code == 0, result.output + assert json.loads(result.output) == expected + assert [i['reuseState'] for i in expected['items']] == ['reusable'] * 4 + + +def files_under(path): + return {str(p.relative_to(path)): hashlib.sha256(p.read_bytes()).hexdigest() + for p in path.rglob('*') if p.is_file() and not p.name.endswith('.lock')} + + +def test_impact_query_is_read_only(saved, monkeypatch): + (store, pid, session), _, _, provider, specs, _ = saved + before = store.snapshot(pid).model_dump_json() + files = files_under(store.local.repository) + calls = provider.calls + + def forbidden(*args, **kwargs): + raise AssertionError('Read-only query attempted a mutation or remote capability probe') + + monkeypatch.setattr(store, 'open', forbidden) + monkeypatch.setattr(store, 'commit', forbidden) + monkeypatch.setattr(CapabilityProbe, 'query', forbidden) + canvas = CreationCanvas(store) + first = canvas.query_snapshot(impact_query(pid, [specs[1]])) + assert first == canvas.query_snapshot(impact_query(pid, [specs[1]])) + assert store.snapshot(pid).model_dump_json() == before + assert files_under(store.local.repository) == files + assert provider.calls == calls + + +def test_snapshot_version_and_scope_limits(saved, monkeypatch): + (store, pid, _), _, _, _, specs, _ = saved + original = store.snapshot + state = original(pid) + reads = [] + + def one_snapshot(key): + reads.append(key) + assert len(reads) == 1 + return state + + catalog = ModelConfigs.catalog_snapshot + catalogs = [] + + def one_catalog(self): + catalogs.append(True) + assert len(catalogs) == 1 + return catalog(self) + + monkeypatch.setattr(store, 'snapshot', one_snapshot) + monkeypatch.setattr(ModelConfigs, 'catalog_snapshot', one_catalog) + value = CreationCanvas(store).query_snapshot(impact_query(pid, [specs[1]])) + assert value.projectVersion.revision == state.project.revision and value.eventCursor == state.eventCursor + assert len(reads) == len(catalogs) == 1 + + +@pytest.mark.parametrize('locale', ['zh-CN', 'en-US']) +def test_impact_errors_and_codes_are_locale_safe(saved, locale): + (store, pid, _), _, _, provider, specs, _ = saved + api = TestClient(create_app(store.local, generation_provider=provider), + headers={'Accept-Language': locale, 'X-OpenDirector-Request': '1'}) + query = impact_query(pid, [specs[1]], maxNodes=3) + response = api.post(f'/api/creation/projects/{pid}/queries', json=query.model_dump(mode='json')) + assert response.status_code == 422 and response.json()['code'] == 'impact_scope_exceeded' + message = response.json()['detail'] + assert ('上限' in message) if locale == 'zh-CN' else ('limit' in message and not any('\u4e00' <= c <= '\u9fff' for c in message)) + for roots in ([uuid4()], [pid]): # foreign and wrong-kind identity + response = api.post(f'/api/creation/projects/{pid}/queries', json=impact_query(pid, roots).model_dump(mode='json')) + assert response.status_code == 404 and response.json()['code'] == 'missing_object' + valid = impact_query(pid, [specs[1]]).model_dump(mode='json') + english = api.post(f'/api/creation/projects/{pid}/queries', json=valid, headers={'Accept-Language': 'en-US'}).json() + chinese = api.post(f'/api/creation/projects/{pid}/queries', json=valid, headers={'Accept-Language': 'zh-CN'}).json() + assert english == chinese + assert all(secret not in json.dumps(english) for secret in ('12345', str(store.local.repository), 'apiKey', 'Frame 0')) + + +def test_long_chain_cycles_and_scope_are_bounded(): + from opendirector.domain.creation.project import ProjectSnapshot + from opendirector.domain.creation.validation import ContractError + from test_creation_contracts import entity, PROJECT + data = dict(project=dict(id=PROJECT, name='Long chain'), generationSpecs=[ + entity(10000+i, kind='image', purpose='generation', modelConfigId=uid(20)) for i in range(1200)], + canvasItems=[entity(20000+i, kind='image', binding=dict(role='generation', objectRef=dict(id=uid(10000+i)))) for i in range(1200)], + references=[entity(30000+i, binding='follow_current', targetSpecId=uid(10000+i), source=dict(id=uid(19999+i))) for i in range(1,1200)]) + state = ProjectSnapshot.model_validate(data) + value = report(state, roots=(uid(10000),)) + assert len(value.items) == 1200 and value.items[-1].relation == 'downstream' + assert value.items[-1].reuseState == 'no_result' + with pytest.raises(ContractError) as error: + report(state, roots=(uid(10000),), max_nodes=1199) + assert error.value.issue.code == 'impact_scope_exceeded' + cyclic = replace(graph(), 'references', 0, source=dict(id=uid(202))) + value = report(cyclic) + assert all(value.items[i].reuseState == 'unknown' for i in (1, 2)) + assert any(r.code == 'dependency_cycle' for r in value.items[1].reasons) From 81b9643f4fba6c74a011cad69b28d0878acb481a Mon Sep 17 00:00:00 2001 From: qingpeng Date: Mon, 23 Nov 2026 16:45:31 -0800 Subject: [PATCH 4/8] [feat] generation: complete impact validation and handoff ## summary Exercise real project commands, files, candidate adoption, pinning and reopening. Keep uncertainty ahead of pending propagation regardless of reference order. Document the bilingual query workflow and provide recorded request/response examples for workbench integration. ## validation - Impact domain and query tests: 47 passed. - Frontend suite: 961 passed. - Static hooks, sample contracts and documentation links passed. - Full CPU regression is still running; no live model calls were made. Refs: #355 --- docs/README.md | 1 + .../fixtures/generation-impact-request.json | 9 ++ .../fixtures/generation-impact-response.json | 136 ++++++++++++++++++ .../generation-impact-validation.md | 62 ++++++++ docs/development/i18n.md | 1 + docs/guides/cli.md | 37 +++++ .../skills/character-replacement/workflow.md | 4 + .../application/creation_impact.py | 2 +- tests/test_generation_impact.py | 53 +++++++ tests/test_generation_impact_queries.py | 110 ++++++++++++++ 10 files changed, 414 insertions(+), 1 deletion(-) create mode 100644 docs/development/fixtures/generation-impact-request.json create mode 100644 docs/development/fixtures/generation-impact-response.json create mode 100644 docs/development/generation-impact-validation.md diff --git a/docs/README.md b/docs/README.md index 3c224ce6a..99dbfb7b8 100644 --- a/docs/README.md +++ b/docs/README.md @@ -14,6 +14,7 @@ This directory is the entry point for the repository's shared documentation. The | [Capability mapping contract](architecture/capability-contract.md) | Evidenced upstream vocabulary, the `(operation, profile) → capability` table, the untranslatable declarations, and how it feeds discovery | Upstream vocabulary, capability ids, or discovery matching change | | [Roadmap](development/roadmap.md) | Capability dependencies and delivery criteria | Scope, dependencies, or acceptance criteria change | | [Validation guide](development/validation.md) | Reproducible checks and evidence requirements | Tools, runtime requirements, or validation entry points change | +| [Generation impact integration](development/generation-impact-validation.md) | Shared impact query, recorded request/response and workbench integration boundary | Impact semantics, validation or workbench integration changes | | [CI layer assessment](development/ci-layer-assessment.md) | Timing evidence, critical PR representatives and staged Python classification | Measured evidence or classification decisions change | | [Issue #87 Windows handoff](development/issue-87-windows-handoff.md) ([中文](development/issue-87-windows-handoff.zh-CN.md)) | Native ACL repair and final text acceptance | The shared checkpoint or native validation scope changes | | [Development lessons](development/lessons.md) | Risks identified from recent fixes | New evidence emerges or a lesson no longer applies | diff --git a/docs/development/fixtures/generation-impact-request.json b/docs/development/fixtures/generation-impact-request.json new file mode 100644 index 000000000..fc933fa79 --- /dev/null +++ b/docs/development/fixtures/generation-impact-request.json @@ -0,0 +1,9 @@ +{ + "queryId": "3cf1e8e1-89b9-4f5e-8838-54f2b3268fb4", + "projectId": "f41fe83e-0ddb-4784-8d91-c1c670065f71", + "type": "generation.impact", + "rootSpecIds": [ + "4d5f438a-f86f-4f0f-b9aa-7d6e6cebeeef" + ], + "maxNodes": 2000 +} diff --git a/docs/development/fixtures/generation-impact-response.json b/docs/development/fixtures/generation-impact-response.json new file mode 100644 index 000000000..17bce1e73 --- /dev/null +++ b/docs/development/fixtures/generation-impact-response.json @@ -0,0 +1,136 @@ +{ + "analysisVersion": 1, + "projectVersion": { + "objectType": "project", + "id": "f41fe83e-0ddb-4784-8d91-c1c670065f71", + "revision": 1 + }, + "eventCursor": 33, + "rootSpecIds": [ + "4d5f438a-f86f-4f0f-b9aa-7d6e6cebeeef" + ], + "items": [ + { + "specId": "d2f677d8-e6cd-43c8-ae54-8df7734c28fa", + "specRevision": 4, + "currentResultId": "b77c3085-eaec-5a08-8a6c-9fc076328ff0", + "baselineJobId": "13677f9c-6502-5697-8a38-283e5e8d32da", + "baselineInputFingerprint": "dbd75ac7625191fcfbc582b6ca5c3ed73d3d441caa6e0d1618ae00accf64719f", + "currentInputFingerprint": "dbd75ac7625191fcfbc582b6ca5c3ed73d3d441caa6e0d1618ae00accf64719f", + "inputState": "equal", + "reuseState": "reusable", + "relation": "independent", + "upstreamSpecIds": [], + "activeJobIds": [], + "reasons": [] + }, + { + "specId": "4d5f438a-f86f-4f0f-b9aa-7d6e6cebeeef", + "specRevision": 5, + "currentResultId": "2b2e7541-87c7-5117-bb94-8ff1c87cf509", + "baselineJobId": "ead6bc3b-ec09-5875-96cb-5e0471cd9c1f", + "baselineInputFingerprint": "f9880a78e32a8718d511531daa1aa418d591687480de3b66e2d5a3844d10497e", + "currentInputFingerprint": "02448c6c6142e6924b90cbeea3825d41c1ac6c436f69dc239f323944cbf3a0a6", + "inputState": "changed", + "reuseState": "stale", + "relation": "root", + "upstreamSpecIds": [ + "d2f677d8-e6cd-43c8-ae54-8df7734c28fa" + ], + "activeJobIds": [], + "reasons": [ + { + "code": "inputs_changed", + "objectId": "4d5f438a-f86f-4f0f-b9aa-7d6e6cebeeef", + "referenceId": null, + "fieldPaths": [ + "spec.prompt" + ] + } + ] + }, + { + "specId": "dee2d143-046b-47fc-86f3-1c24f113c236", + "specRevision": 4, + "currentResultId": "1d33a0aa-803a-545f-88d7-0ac154e1f720", + "baselineJobId": "a038682a-0fe5-53e4-8191-e78a2df1d92e", + "baselineInputFingerprint": "b8a061d7123836311407bb42ef23b6e12033f0524c529f1673914c7793f29bf2", + "currentInputFingerprint": "b8a061d7123836311407bb42ef23b6e12033f0524c529f1673914c7793f29bf2", + "inputState": "equal", + "reuseState": "pending_upstream", + "relation": "downstream", + "upstreamSpecIds": [ + "4d5f438a-f86f-4f0f-b9aa-7d6e6cebeeef" + ], + "activeJobIds": [], + "reasons": [ + { + "code": "upstream_pending", + "objectId": "4d5f438a-f86f-4f0f-b9aa-7d6e6cebeeef", + "referenceId": "c936fa2f-fae2-4b38-869d-fb355edfbc2f", + "fieldPaths": [] + } + ] + }, + { + "specId": "7f268b78-755a-433e-8751-cdf17259877d", + "specRevision": 4, + "currentResultId": "4c98012b-86e3-5a07-a496-affb1d644b17", + "baselineJobId": "6c90d034-a5d1-53c5-94e9-8f46647d6ff5", + "baselineInputFingerprint": "3c218cd8c9c95ecd2fa681b236beaa062a6c5bb62d1005bb587cd5367a07bb7e", + "currentInputFingerprint": "3c218cd8c9c95ecd2fa681b236beaa062a6c5bb62d1005bb587cd5367a07bb7e", + "inputState": "equal", + "reuseState": "reusable", + "relation": "independent", + "upstreamSpecIds": [], + "activeJobIds": [], + "reasons": [] + } + ], + "dependencies": [ + { + "sourceSpecId": "d2f677d8-e6cd-43c8-ae54-8df7734c28fa", + "sourceItemId": "f31f1bee-df50-4378-8c1e-40c22050dec6", + "targetSpecId": "4d5f438a-f86f-4f0f-b9aa-7d6e6cebeeef", + "referenceId": "be3a9284-43d1-4dda-b47e-d12da4585da2", + "role": "reference", + "assetId": "df7a7beb-bdb3-50f0-882d-644224938ed4", + "documentId": null, + "inputConfirmed": true + }, + { + "sourceSpecId": "4d5f438a-f86f-4f0f-b9aa-7d6e6cebeeef", + "sourceItemId": "9c445317-46cb-4ed5-801c-4a357a406dad", + "targetSpecId": "dee2d143-046b-47fc-86f3-1c24f113c236", + "referenceId": "c936fa2f-fae2-4b38-869d-fb355edfbc2f", + "role": "reference", + "assetId": "9cb90c95-d158-5c58-9a28-84b4d35aff9b", + "documentId": null, + "inputConfirmed": true + } + ], + "timelineConsumers": [ + { + "editorDocumentId": "35c2b0d7-a177-4161-aeda-4f77317dc6a3", + "revision": 1, + "clipId": "B", + "assetId": "9cb90c95-d158-5c58-9a28-84b4d35aff9b", + "specIds": [ + "4d5f438a-f86f-4f0f-b9aa-7d6e6cebeeef" + ], + "association": "asset_and_source", + "sourceItemId": "9c445317-46cb-4ed5-801c-4a357a406dad" + }, + { + "editorDocumentId": "35c2b0d7-a177-4161-aeda-4f77317dc6a3", + "revision": 1, + "clipId": "C", + "assetId": "6e22e526-0f09-5e94-9d95-e7a21f60d890", + "specIds": [ + "dee2d143-046b-47fc-86f3-1c24f113c236" + ], + "association": "asset_and_source", + "sourceItemId": "2bf7e3c4-b587-4fbb-adad-30c6a1dfbb45" + } + ] +} diff --git a/docs/development/generation-impact-validation.md b/docs/development/generation-impact-validation.md new file mode 100644 index 000000000..c4c92f81f --- /dev/null +++ b/docs/development/generation-impact-validation.md @@ -0,0 +1,62 @@ +# Generation impact: integration and validation + +This records the dependency/reuse foundation for [#355](https://github.com/ThinkFlowLab/OpenDirector/issues/355). User-facing instructions and state meanings are available in both languages in the [CLI guide](../guides/cli.md). It does not establish completion of the full long-video workflow. + +## Upstream boundary, checked 2026-11-23 + +- The isolated implementation starts at upstream `main` `52102ed03d74d08f52face27113fc9d44e283216`. No commits from the local issue-87 branch were carried in. +- [#342](https://github.com/ThinkFlowLab/OpenDirector/pull/342) was open at `f9993a1fb9db103ab028103859d26bdf93f4935d`. Its public patch provides H3 compilation, storyboard audit/QC and shot revision, not an adopted-input impact/reuse query. This change reuses existing execution snapshots, input resolution, asset verification and query dispatch. +- [#212's progress report](https://github.com/ThinkFlowLab/OpenDirector/issues/212#issuecomment-6821432061) describes a separate workbench service and editor document. The public branch/PR searches and the [interface request](https://github.com/ThinkFlowLab/OpenDirector/issues/355#issuecomment-7116407885) did not provide a runnable workbench branch or schema. No reply was present on recheck. Overlap with that unpublished implementation remains unconfirmed. +- Client and bilingual display strings are ready; visible workbench integration and a browser language-switch acceptance remain pending #212. No second workbench or speculative workbench document adapter was added. + +客户端与双语词条已就绪,工作台可见接入待 #212 提供公共代码及真实契约;本记录不宣称完整 #355、真实 H3 生成质量或续写缓存恢复已验收。 + +## Shared integration contract + +Use `generation.impact` through `POST /api/creation/projects/{projectId}/queries`, the existing Agent query tool, or `opendirector --project PROJECT_UUID query generation.impact --file impact-query.json`. The HTTP request uses the existing local-API request-header protection. No editing session is required. + +- Query and report definitions: [commands.py](../../packages/core/src/opendirector/domain/creation/commands.py), [impact.py](../../packages/core/src/opendirector/domain/creation/impact.py), [generated TypeScript](../../src/contracts/generated.ts). +- Frontend: `CreationClient.generationImpact(rootSpecIds, { signal })` in [creationClient.ts](../../src/backend/creationClient.ts). It performs a read without installing the response as a project snapshot or entering the mutation queue. +- Display: pass stable states/reasons to `generationImpactText(code, t)` in [generationImpactText.ts](../../src/backend/generationImpactText.ts). Unknown codes have a translated fallback; no provider payload is rendered. +- Show both `inputState` and `reuseState`, the reasons and original `baselineJobId`/`activeJobIds`. Retain `projectVersion`, `eventCursor` and object revisions for context; they do not reserve a future edit. Any workbench action continues through existing commands with current versions, locks and authorization. +- Reports cover all project generation configurations. `relation` is relative to the requested roots; `timelineConsumers` covers only those roots and their downstream configurations. Fixed asset usage and source associations are review evidence, not automatic replacement instructions. + +### Recorded request and response + +The [request](fixtures/generation-impact-request.json) and [response](fixtures/generation-impact-response.json) were captured from `test_reopenable_dependency_case_uses_real_commands_and_files` after editing B's prompt. These UUIDs belong to an isolated test project; substitute IDs from your own project to execute a query. The HTTP sample includes the envelope; the CLI parameter file contains just `rootSpecIds` and optional `maxNodes`. + +| Test object | Spec ID | Current inputs | Reuse | Relation | +| --- | --- | --- | --- | --- | +| A | `d2f677d8-e6cd-43c8-ae54-8df7734c28fa` | equal | reusable | independent | +| B | `4d5f438a-f86f-4f0f-b9aa-7d6e6cebeeef` | changed | stale | root | +| C | `dee2d143-046b-47fc-86f3-1c24f113c236` | equal | pending_upstream | downstream | +| D | `7f268b78-755a-433e-8751-cdf17259877d` | equal | reusable | independent | + +A is an upstream dependency of B, but is not downstream of the requested B root. The timeline contains B/C/D; the response lists B/C consumers with their retained assets and source associations. D remains outside the requested downstream scope. The report contains IDs, fingerprints and controlled field paths, not prompts, provider URLs, credentials, local paths or raw adapter data. + +## Coverage decisions + +Current active `follow_current` references determine propagation. Pinned inputs, overrides, candidates, display changes and historical Job usage do not create spurious live edges. `context_only` inputs do not propagate future upstream changes; the existing shared fingerprint still decides their current equality after actual adoption. + +Subject slots retain assets in their editor document. Their `inputConnections` do not establish live generation-follow semantics. The report keeps document/item/asset evidence without inferring upstream specs from identical bytes or old provenance. Any future #212/#354 slot adapter must explicitly define its live binding semantics. + +The comparison uses the same frozen inputs as generation acceptance. Known adapter output settings and generated random seeds remain execution facts. Unknown adapter extension fields or missing saved model rules prevent a reuse claim. Current storage has no reconstructable guide/window/direction plan for external workflows; a future persisted field needs explicit comparison coverage. `reusable` means the registered existing output can be reused under the compared inputs, not a remote cache hit or deterministic new generation. + +Inputs are bounded to 100 distinct roots, at most 10,000 configurations (default budget 2,000), and 20,000 active references/expanded edges. A limit error returns no partial success. Unresolved dependencies and cycles remain explicit uncertainty, including dependent nodes; no execution order or retry command is invented. + +## Reproducible validation + +Run with Python 3.12 and the Node version in `.nvmrc`, using the [validation guide](validation.md) for setup: + +```bash +PYTHONPATH=packages/core/src:apps/api/src:tests .venv/bin/python -m pytest tests/test_generation_impact.py tests/test_generation_impact_queries.py -q +node --test tests/generationImpact.test.ts tests/creationClient.test.ts +.venv/bin/python scripts/generate_contracts.py --check +PYTHONPATH=packages/core/src:apps/api/src .venv/bin/lint-imports +npm run check:i18n +npm run build +``` + +The Python scenario uses real small PNG files, real command acceptance, immutable Job inputs, candidate generation, result adoption, pinning, timeline creation and a fresh project service after reopen. Only model execution is doubled. It verifies query equality across HTTP/Agent/CLI, file and project immutability, one project/catalog read, unavailable output files, foreign-project roots, limits, cycles and a 1,200-node graph. Frontend tests switch the active locale through English and Chinese for all declared report codes and verify typed read behavior while a newer project snapshot arrives. + +No live GPU/commercial provider was called. The workbench UI, native visual Harness matrix, browser export and remote continuation caches are separate acceptance scopes; they are not proven by these fixtures. diff --git a/docs/development/i18n.md b/docs/development/i18n.md index fc0837253..4a98a148c 100644 --- a/docs/development/i18n.md +++ b/docs/development/i18n.md @@ -98,6 +98,7 @@ npm run check:i18n | 画布外壳 | [canvasShell.ts](../../src/i18n/messages/zh-CN/canvasShell.ts) | [canvasShell.ts](../../src/i18n/messages/en-US/canvasShell.ts) | | 画布工作区 | [canvasWorkspace.ts](../../src/i18n/messages/zh-CN/canvasWorkspace.ts) | [canvasWorkspace.ts](../../src/i18n/messages/en-US/canvasWorkspace.ts) | | 生成器 | [generation.ts](../../src/i18n/messages/zh-CN/generation.ts) | [generation.ts](../../src/i18n/messages/en-US/generation.ts) | +| 生成依赖影响与复用 | [generationImpact.ts](../../src/i18n/messages/zh-CN/generationImpact.ts) | [generationImpact.ts](../../src/i18n/messages/en-US/generationImpact.ts) | | 音色库 | [voiceLibrary.ts](../../src/i18n/messages/zh-CN/voiceLibrary.ts) | [voiceLibrary.ts](../../src/i18n/messages/en-US/voiceLibrary.ts) | | 时间线 | [timeline.ts](../../src/i18n/messages/zh-CN/timeline.ts) | [timeline.ts](../../src/i18n/messages/en-US/timeline.ts) | | 素材库 | [library.ts](../../src/i18n/messages/zh-CN/library.ts) | [library.ts](../../src/i18n/messages/en-US/library.ts) | diff --git a/docs/guides/cli.md b/docs/guides/cli.md index 743279638..bdd30ff01 100644 --- a/docs/guides/cli.md +++ b/docs/guides/cli.md @@ -47,6 +47,43 @@ Agent 的 Shell 通过 PATH 使用同一个 `opendirector`。宿主提供受令 `job show` / `job wait` 在任务成功后返回 `delivery`:已登记的 AssetRef、当前采用状态及展示该素材的画布项。生成成功不等于质量验收;Agent 应检查现有素材。复制到执行目录做媒体探测、抽帧和审看不需要重新发布,也不应为同一次交付新增画布项。编辑产生的新交付文件才需要登记;独立副本展示应有用户要求。 +## 生成依赖影响与结果复用 / Generation impact and result reuse + +`generation.impact` 从已保存的工程读取当前生成输入,并与当前采用结果对应的成功 Job 比较。以下参数文件中的 UUID 必须替换为当前工程的真实 GenerationSpec ID(不是画布项或 Job ID)。查询不会申请编辑会话、提交生成、采用候选或修改时间线。 + +`generation.impact` compares saved current inputs with the successful Job behind each adopted result. Replace the UUID in the parameter file with a real GenerationSpec ID from the selected project, not a canvas item or Job ID. The query does not open an edit session, submit generation, adopt candidates or edit the timeline. + +```json +{"rootSpecIds":["4d5f438a-f86f-4f0f-b9aa-7d6e6cebeeef"]} +``` + +Save this as `impact-query.json` / 保存为 `impact-query.json`: + +```bash +opendirector --project PROJECT_UUID query generation.impact --file impact-query.json +``` + +| `reuseState` | 中文含义 | Meaning | +| --- | --- | --- | +| `reusable` | 当前依据一致,已有结果文件可用 | Current evidence matches and the existing result file is available | +| `stale` | 当前有效输入与采用时不同 | Current effective inputs differ from the adopted execution | +| `pending_upstream` | 当前输入仍相同,上游后续采用可能影响它 | Inputs still match; a future upstream adoption may affect them | +| `unavailable` | 已采用结果文件不可用 | The adopted result file is unavailable | +| `unknown` | 输入、模型或执行依据不足 | Input, model or execution evidence is incomplete | +| `no_result` | 没有已采用结果 | No result is currently adopted | + +例如 A→B→C 与独立 D:只改 B 提示词时,B 为 `stale`,C 为 `pending_upstream`,D 仍为 `reusable`。生成 B2 候选尚未采用不会改变 C 的当前输入;采用 B2 后,跟随 B 的 C 变为 `stale`。C 固定引用 B1 则不跟随 B2。`inputState` 独立说明本次输入是否相同,`relation` 表示相对请求根的关系;独立节点仍会检查自己的输入和文件。 + +For A→B→C and independent D, editing only B's prompt makes B `stale`, C `pending_upstream` and D `reusable`. A B2 candidate does not change C's current inputs until adopted; after adoption, C following B becomes `stale`. C pinned to B1 remains unchanged. `inputState` separately describes current input equality, while `relation` describes reachability from the requested roots. Independent nodes still have their own inputs and files checked. + +报告含 `projectVersion`、`eventCursor`、各配置版本、`baselineJobId`、`activeJobIds`、稳定原因码及受控字段路径。时间线使用点仅列出请求根和下游配置的相关片段,区分固定素材与来源关联,不代表允许自动替换。查询后工程可能继续变化;修改前须重读相关对象、校验当前版本和锁定。活动或未知提交先查询原 Job,不能因为本报告另建任务重发。 + +The report includes `projectVersion`, `eventCursor`, spec revisions, `baselineJobId`, `activeJobIds`, stable reason codes and controlled field paths. Timeline consumers cover the requested roots and their downstream configurations, distinguishing fixed assets from source associations; they do not authorize replacement. State may change after a query. Re-read affected objects and check current versions and locks before any modification. Inspect the original Job for active or uncertain submissions instead of creating another attempt from this report. + +每次最多 100 个不同根;检查工程全部生成配置,`maxNodes` 默认 2,000、最大 10,000,活动参考及展开依赖边最多 20,000。超限返回 `impact_scope_exceeded`,不返回截断后看似完整的报告。缺少可重建的 guide、窗口或扩展 adapter 依据时保持未知。复用只针对已有素材,不保证重新生成确定性、创作质量、服务商健康或远端 latent/cache 命中。外部 ComfyUI 未登记的 graph/history/cache 仍需单独核对。 + +Queries accept up to 100 distinct roots and inspect all generation configurations in the project. `maxNodes` defaults to 2,000 with a maximum of 10,000; active references and expanded edges are limited to 20,000. Overflow returns `impact_scope_exceeded`, not a truncated report. Missing reconstructable guide, window or adapter-extension evidence remains unknown. Reuse concerns existing assets, not deterministic regeneration, creative quality, provider health or remote latent/cache hits. Unregistered external ComfyUI graphs, history and caches require separate checks. + ## 更新生成配置 `generation-spec update` 替换完整配置,不是局部补丁。先用 `opendirector query object.get --object-id ` 读取当前配置,修改需要调整的字段后,将完整对象放入命令文件的 `payload.spec`,并携带当前 `expectedVersions`。 diff --git a/packages/agent/skills/character-replacement/workflow.md b/packages/agent/skills/character-replacement/workflow.md index 3873ef73a..710e8e98f 100644 --- a/packages/agent/skills/character-replacement/workflow.md +++ b/packages/agent/skills/character-replacement/workflow.md @@ -52,6 +52,10 @@ Change one variable per comparison and retain previous outputs. Editing a segmen Use versioned output prefixes only on affected outputs where possible; changing every prefix can invalidate otherwise reusable save nodes. Retry within the agreed budget and report persistent defects rather than silently changing the model, replacement scope or reference images. +For relationships already registered in an OpenDirector project, save `{"rootSpecIds":[""]}` as `impact-query.json` and run `opendirector --project query generation.impact --file impact-query.json`. It compares current inputs with the adopted result's original Job. `pending_upstream` means current inputs still match but future upstream adoption may affect them; `stale` means current inputs already differ. Unadopted candidates and pinned inputs do not create live propagation. Inspect the returned reasons and original Job IDs; unknown submissions follow the existing recovery workflow. Re-read versions and locks before authorized edits. This read-only report does not execute reruns, promise creative quality, or guarantee ComfyUI/Omni latent or execution-cache availability. External graphs/history/cache remain subject to the checks above; unregistered guide/window/direction inputs are outside its proven coverage. + +对于已登记到 OpenDirector 工程的业务关系,将 `{"rootSpecIds":["<真实 GenerationSpec UUID>"]}` 保存为 `impact-query.json`,执行 `opendirector --project <真实 Project UUID> query generation.impact --file impact-query.json`。查询比较当前输入与已采用结果的原 Job:`pending_upstream` 表示当前输入仍相同、后续上游采用可能影响它;`stale` 表示当前输入已不同。未采用候选和固定引用不产生跟随传播。检查原因与原 Job,未知提交沿用现有恢复流程,授权修改前重读版本与锁定。查询不执行重做,不证明创作质量,也不保证 ComfyUI/Omni latent 或执行缓存可用;外部 graph/history/cache 仍按上述流程核对,未登记的 guide/窗口/方向不在已验证覆盖内。 + ## First-run qualification and history backup Validate the execution path once with empty history and new inputs. A workflow-to-API exporter/helper must handle native subgraphs, changed instance counts and current widget values without a matching prior run. A documented manual export handoff is a remaining automation limitation, not a completed one-sentence flow. diff --git a/packages/core/src/opendirector/application/creation_impact.py b/packages/core/src/opendirector/application/creation_impact.py index c1b41ce90..366e487cf 100644 --- a/packages/core/src/opendirector/application/creation_impact.py +++ b/packages/core/src/opendirector/application/creation_impact.py @@ -364,7 +364,7 @@ def available(key): for edge in direct: if not edge.inputConfirmed or edge.sourceSpecId in uncertain: reasons.append(ImpactReason(code='dependency_unresolved', objectId=edge.sourceSpecId or edge.sourceItemId, referenceId=edge.referenceId)) - if reuse == 'reusable': + if reuse in {'reusable', 'pending_upstream'}: reuse = 'unknown' elif edge.sourceSpecId in pending and reuse in {'reusable', 'pending_upstream'}: reuse = 'pending_upstream' diff --git a/tests/test_generation_impact.py b/tests/test_generation_impact.py index 8b696cc76..06a931ba0 100644 --- a/tests/test_generation_impact.py +++ b/tests/test_generation_impact.py @@ -373,3 +373,56 @@ def test_ordinary_adapter_settings_do_not_invent_missing_guide_requirements(para state = ProjectSnapshot(project=dict(id=PROJECT, name='Video'), assets=[output], jobs=[job], results=[result], generationSpecs=[frozen.spec.model_copy(update={'currentResultId': result.id})]) assert report(state, models={public.id: frozen_model}, roots=(uid(100),)).items[0].reuseState == 'reusable' + + +def test_context_only_is_not_a_propagation_edge_but_retains_shared_fingerprint_semantics(): + from opendirector.domain.creation.generation import VideoGenerationSpec + state = graph() + public = model('video') + video_model = ModelSnapshot(modelConfigId=uid(21), inputRules=public.inputRules, + **{key: getattr(public, key) for key in ('kind', 'modelId', 'url', 'protocol', 'connectionType', 'videoAdapter')}) + data = state.model_dump() + data['generationSpecs'] = list(data['generationSpecs']) + data['generationSpecs'][2] = VideoGenerationSpec(**entity(102, kind='video', purpose='generation', modelConfigId=uid(21))) + data['canvasItems'][2]['kind'] = 'video' + data['jobs'] = [j for j in state.jobs if j.id != uid(402)] + data['results'] = [r for r in state.results if r.id != uid(502)] + state = ProjectSnapshot.model_validate(data) + spec, refs = current_generation_inputs(state, state.generationSpecs[2], video_model.inputRules) + assert refs[0].transmission == 'context_only' + frozen = InputSnapshot(spec=spec, model=video_model, references=refs) + output = asset(350, 'video') + job = Job(**entity(450, inputSnapshot=frozen, inputFingerprint=frozen.fingerprint(), execution=dict(kind='video'), + status='succeeded', recovery='done', asset=asset_ref(output))) + result = ResultVersion(**entity(550, specId=spec.id, jobId=job.id, asset=job.asset, inputFingerprint=job.inputFingerprint)) + data = state.model_dump() + data.update(assets=[*state.assets, output], jobs=[*state.jobs, job], results=[*state.results, result]) + data['generationSpecs'][2]['currentResultId'] = result.id + state = ProjectSnapshot.model_validate(data) + models = {uid(20): impact_model(), uid(21): video_model} + changed = replace(state, 'generationSpecs', 1, prompt='B changed') + value = report(changed, models=models) + assert value.items[2].reuseState == 'reusable' + assert not any(e.targetSpecId == uid(102) for e in value.dependencies) + adopted = new_result(changed, 1) + item = report(adopted, models=models).items[2] + assert (item.inputState, item.reuseState) == ('changed', 'stale') + assert item.reasons[0].fieldPaths == ('references',) + + +@pytest.mark.parametrize('reverse', [False, True]) +def test_unknown_upstream_overrides_pending_independently_of_reference_order(reverse): + state = graph() + data = state.model_dump() + data['references'] = [*state.references, entity(650, binding='follow_current', + targetSpecId=uid(102), source=dict(id=uid(203)), order=1)] + state = new_result(ProjectSnapshot.model_validate(data), 2) + state = replace(state, 'generationSpecs', 1, prompt='B changed') + # D's adopted inputs still match, but its execution evidence is incomplete. + state = replace(state, 'jobs', 3, adapterParameters={'guide': 'unregistered'}) + if reverse: + state = state.model_copy(update={'references': tuple(reversed(state.references))}) + item = report(state).items[2] + assert item.inputState == 'equal' + assert item.reuseState == 'unknown' + assert any(reason.code == 'dependency_unresolved' and reason.objectId == uid(103) for reason in item.reasons) diff --git a/tests/test_generation_impact_queries.py b/tests/test_generation_impact_queries.py index 7a72bd3db..2569af514 100644 --- a/tests/test_generation_impact_queries.py +++ b/tests/test_generation_impact_queries.py @@ -198,3 +198,113 @@ def test_long_chain_cycles_and_scope_are_bounded(): value = report(cyclic) assert all(value.items[i].reuseState == 'unknown' for i in (1, 2)) assert any(r.code == 'dependency_cycle' for r in value.items[1].reasons) + + +def submit_existing(saved, index, *, adopt=False): + (store, pid, session), configs, _, provider, specs, items = saved + + async def generate(): + runner = CreationGeneration(store, configs, provider) + state = store.snapshot(pid) + spec = next(s for s in state.generationSpecs if s.id == specs[index]) + item = next(i for i in state.canvasItems if i.id == items[index]) + request = parse_command(dict(commandId=uuid4(), projectId=pid, type='generation.submit', + expectedVersions=[ver('generation_spec', spec), ver('canvas_item', item)], payload=dict( + specId=spec.id, expectedSpecRevision=spec.revision, originItemId=item.id, + adoptionPolicy='if_current' if adopt else 'candidate_only'))) + receipt = await runner.execute(request, session=session) + assert receipt.status == 'accepted', receipt + await settled(runner) + await runner.close() + state = store.snapshot(pid) + job = next(j for j in state.jobs if j.id == receipt.jobIds[0]) + assert job.status == 'succeeded' + return next(r for r in state.results if r.jobId == job.id) + + return asyncio.run(generate()) + + +@pytest.mark.parametrize('pinned', [False, True], ids=['following', 'pinned']) +def test_reopenable_dependency_case_uses_real_commands_and_files(saved, tmp_path, pinned): + from opendirector.infrastructure.creation_projects import CreationProjects + from opendirector.infrastructure.local_projects import LocalProjects + (store, pid, session), _, _, _, specs, items = saved + canvas = CreationCanvas(store) + query = impact_query(pid, [specs[1]]) + if pinned: + state = store.snapshot(pid) + reference = next(r for r in state.references if r.targetSpecId == specs[2]) + source = next(i for i in state.canvasItems if i.id == items[1]) + result = next(r for r in state.results if r.specId == specs[1]) + receipt = send(store, pid, 'reference.update', session=session, + versions=[ver('reference', reference), ver('generation_spec', next(s for s in state.generationSpecs if s.id == specs[2]))], + reference={**reference.model_dump(exclude={'binding', 'source'}), 'binding': 'pinned', + 'source': result.asset, 'sourceVersion': ver('canvas_item', source)}) + assert receipt.status == 'applied', receipt + submit_existing(saved, 2, adopt=True) + state = store.snapshot(pid) + results = {r.id: r for r in state.results} + selected = {s.id: results[s.currentResultId] for s in state.generationSpecs} + timeline_id = uuid4() + clips = [dict(id=key, resource=dict(asset=selected[specs[i]].asset, title=key), inPoint=0, outPoint=1) + for key, i in (('B', 1), ('C', 2), ('D', 3))] + receipt = send(store, pid, 'editor.create', session=session, document=dict(id=timeline_id, projectId=pid, + kind='timeline', inputConnections=[dict(id=uuid4(), sourceId=items[1], slotId='B', asset=selected[specs[1]].asset)], + data=dict(fps=24, width=16, height=16, tracks=[dict(id='v', kind='visual', title='Shots', clips=clips)]))) + assert receipt.status == 'applied', receipt + assert all(item.reuseState == 'reusable' for item in canvas.query_snapshot(query).items) + before = store.snapshot(pid) + b = next(s for s in before.generationSpecs if s.id == specs[1]) + receipt = send(store, pid, 'generationSpec.update', session=session, versions=[ver('generation_spec', b)], + spec=b.model_copy(update={'prompt': 'Change only B'})) + assert receipt.status == 'applied', receipt + changed = canvas.query_snapshot(query) + by_id = {i.specId: i for i in changed.items} + assert by_id[specs[1]].reuseState == 'stale' + assert (by_id[specs[2]].inputState, by_id[specs[2]].reuseState) == ('equal', 'reusable' if pinned else 'pending_upstream') + assert by_id[specs[3]].reuseState == 'reusable' + if not pinned: + # Keep the actual public request/response as a reproducible handoff artifact. + (tmp_path / 'impact-request.json').write_text(query.model_dump_json(indent=2), encoding='utf-8') + (tmp_path / 'impact-response.json').write_text(changed.model_dump_json(indent=2), encoding='utf-8') + candidate = submit_existing(saved, 1) + pending = {i.specId: i for i in canvas.query_snapshot(query).items} + assert pending[specs[2]].currentInputFingerprint == by_id[specs[2]].currentInputFingerprint + assert pending[specs[2]].inputState == 'equal' + state = store.snapshot(pid) + b = next(s for s in state.generationSpecs if s.id == specs[1]) + receipt = send(store, pid, 'result.select', session=session, versions=[ver('generation_spec', b)], + specId=b.id, resultId=candidate.id) + assert receipt.status == 'applied', receipt + after = canvas.query_snapshot(query) + by_id = {i.specId: i for i in after.items} + assert by_id[specs[2]].reuseState == ('reusable' if pinned else 'stale') + assert by_id[specs[3]].reuseState == 'reusable' + assert before.jobs == store.snapshot(pid).jobs[:len(before.jobs)] + assert before.editorDocuments == store.snapshot(pid).editorDocuments + snapshot_bytes = store.snapshot(pid).model_dump_json() + files = files_under(store.local.repository) + reopened = CreationProjects(LocalProjects(store.local.repository)) + assert CreationCanvas(reopened).query_snapshot(query) == after + assert reopened.snapshot(pid).model_dump_json() == snapshot_bytes + assert files_under(store.local.repository) == files + # Remove one isolated result's real bytes, retaining all metadata and history. + with store.local.transaction() as db: + directory, _ = store._find(db, pid) + (directory / 'assets' / str(selected[specs[3]].asset.assetId)).unlink() + missing = {i.specId: i for i in CreationCanvas(reopened).query_snapshot(query).items} + assert missing[specs[3]].reuseState == 'unavailable' + assert reopened.snapshot(pid).model_dump_json() == snapshot_bytes + + +def test_foreign_project_root_never_switches_or_opens_a_session(saved, tmp_path): + from test_creation_canvas_service import media + from opendirector.domain.creation.validation import ContractError + (store, pid, _), _, _, _, specs, _ = saved + other = new_project(tmp_path, 'Other') + _, foreign = media(other) + before = store.snapshot(pid) + with pytest.raises(ContractError) as error: + CreationCanvas(store).query_snapshot(impact_query(pid, [foreign.id])) + assert error.value.issue.code == 'missing_object' + assert store.snapshot(pid) == before From b00b780e9a6260b2169ec27206c3985519e4740d Mon Sep 17 00:00:00 2001 From: qingpeng Date: Mon, 23 Nov 2026 16:56:00 -0800 Subject: [PATCH 5/8] [bugfix] generation: preserve impact evidence across query entries ## summary - Reuse current capability observations and safe file verification caches across HTTP and Agent reads; retain typed query error codes. - Include text overlays and recoverable original jobs in bounded evidence. - Expose the supported node budget to the typed client, regenerate contracts and refresh bilingual integration examples. ## validation - Focused impact, acceptance, gateway, timeline and asset suite: 215 pass. - Final overlay and evidence-budget cases: 4 pass. - Frontend suite: 962 pass; i18n: 3352 keys, no problems. - Type checking, production build, contracts and import rules pass. Refs: #355 --- apps/api/src/opendirector_api/creation.py | 2 +- apps/api/src/opendirector_api/localization.py | 2 +- .../fixtures/generation-impact-request.json | 6 +- .../fixtures/generation-impact-response.json | 96 ++--- .../generation-impact-validation.md | 20 +- docs/guides/cli.md | 10 +- .../core/src/opendirector/agent/gateway.py | 3 + packages/core/src/opendirector/agent/tools.py | 2 +- .../application/creation_canvas.py | 7 +- .../application/creation_impact.py | 39 +- .../opendirector/domain/creation/impact.py | 32 +- .../opendirector/domain/creation/schema.py | 3 +- .../src/opendirector/domain/rule_facts.py | 1 + src/backend/creationClient.ts | 3 +- src/backend/generationImpactText.ts | 2 + src/contracts/creation.schema.json | 378 ++++++++++++++++-- src/contracts/generated.ts | 38 +- src/i18n/messages/en-US/generationImpact.ts | 4 +- src/i18n/messages/zh-CN/generationImpact.ts | 4 +- tests/generationImpact.test.ts | 21 +- tests/test_generation_impact.py | 67 ++++ tests/test_generation_impact_queries.py | 108 +++++ 22 files changed, 723 insertions(+), 125 deletions(-) diff --git a/apps/api/src/opendirector_api/creation.py b/apps/api/src/opendirector_api/creation.py index c1de28496..597528035 100644 --- a/apps/api/src/opendirector_api/creation.py +++ b/apps/api/src/opendirector_api/creation.py @@ -62,7 +62,7 @@ async def __call__(self, scope, receive, send): def creation_routes(projects: CreationProjects, generation=None): router = APIRouter(prefix='/api/creation', tags=['Unified creation projects']) assets = CreationAssets(projects) - canvas = CreationCanvas(projects) + canvas = CreationCanvas(projects, availability=getattr(generation, 'availability', None), assets=assets) history = CreationHistory(projects, assets=assets) timeline_packages = CreationTimelinePackages(projects) diff --git a/apps/api/src/opendirector_api/localization.py b/apps/api/src/opendirector_api/localization.py index 67bd3293b..fa16ca639 100644 --- a/apps/api/src/opendirector_api/localization.py +++ b/apps/api/src/opendirector_api/localization.py @@ -16,7 +16,7 @@ from opendirector.domain.capability_messages import english_capability_message, missing_tool_model_message ENGLISH_BY_CODE = { - 'impact_scope_exceeded': 'Generation impact exceeds the node or reference limit. Reduce the project scope or increase maxNodes within its supported limit.', + 'impact_scope_exceeded': 'Generation impact exceeds the node, reference or retained-evidence limit. Increase maxNodes only for a node-budget error; other limits require a smaller project scope.', "desktop_auth_required": "The desktop connection has expired. Reopen the application.", 'image_quality_unsupported': 'This model does not support the selected image quality. Choose Auto or select another model.', 'bigmodel_video_model': 'The BigModel video protocol supports CogVideoX-3 only.', diff --git a/docs/development/fixtures/generation-impact-request.json b/docs/development/fixtures/generation-impact-request.json index fc933fa79..0b7a2dd83 100644 --- a/docs/development/fixtures/generation-impact-request.json +++ b/docs/development/fixtures/generation-impact-request.json @@ -1,9 +1,9 @@ { - "queryId": "3cf1e8e1-89b9-4f5e-8838-54f2b3268fb4", - "projectId": "f41fe83e-0ddb-4784-8d91-c1c670065f71", + "queryId": "8bac72e6-9535-4c4c-a393-12dc18b173ae", + "projectId": "83f26cfd-cc61-4fef-96cd-d5c6f7e88226", "type": "generation.impact", "rootSpecIds": [ - "4d5f438a-f86f-4f0f-b9aa-7d6e6cebeeef" + "56d1b593-545a-4cb9-8903-fbf620101873" ], "maxNodes": 2000 } diff --git a/docs/development/fixtures/generation-impact-response.json b/docs/development/fixtures/generation-impact-response.json index 17bce1e73..d139c7494 100644 --- a/docs/development/fixtures/generation-impact-response.json +++ b/docs/development/fixtures/generation-impact-response.json @@ -2,21 +2,21 @@ "analysisVersion": 1, "projectVersion": { "objectType": "project", - "id": "f41fe83e-0ddb-4784-8d91-c1c670065f71", + "id": "83f26cfd-cc61-4fef-96cd-d5c6f7e88226", "revision": 1 }, "eventCursor": 33, "rootSpecIds": [ - "4d5f438a-f86f-4f0f-b9aa-7d6e6cebeeef" + "56d1b593-545a-4cb9-8903-fbf620101873" ], "items": [ { - "specId": "d2f677d8-e6cd-43c8-ae54-8df7734c28fa", + "specId": "9264a3d1-0870-4c79-af14-35ce50eaf4e9", "specRevision": 4, - "currentResultId": "b77c3085-eaec-5a08-8a6c-9fc076328ff0", - "baselineJobId": "13677f9c-6502-5697-8a38-283e5e8d32da", - "baselineInputFingerprint": "dbd75ac7625191fcfbc582b6ca5c3ed73d3d441caa6e0d1618ae00accf64719f", - "currentInputFingerprint": "dbd75ac7625191fcfbc582b6ca5c3ed73d3d441caa6e0d1618ae00accf64719f", + "currentResultId": "66382380-52d2-5474-bd6f-5c77f63a523a", + "baselineJobId": "22f37f8f-cb26-539b-aeb3-819556ea075c", + "baselineInputFingerprint": "84ef83d051aee309c805f5cd83018d7697fcd0a4ecd930d680993d9e03a132b6", + "currentInputFingerprint": "84ef83d051aee309c805f5cd83018d7697fcd0a4ecd930d680993d9e03a132b6", "inputState": "equal", "reuseState": "reusable", "relation": "independent", @@ -25,23 +25,23 @@ "reasons": [] }, { - "specId": "4d5f438a-f86f-4f0f-b9aa-7d6e6cebeeef", + "specId": "56d1b593-545a-4cb9-8903-fbf620101873", "specRevision": 5, - "currentResultId": "2b2e7541-87c7-5117-bb94-8ff1c87cf509", - "baselineJobId": "ead6bc3b-ec09-5875-96cb-5e0471cd9c1f", - "baselineInputFingerprint": "f9880a78e32a8718d511531daa1aa418d591687480de3b66e2d5a3844d10497e", - "currentInputFingerprint": "02448c6c6142e6924b90cbeea3825d41c1ac6c436f69dc239f323944cbf3a0a6", + "currentResultId": "fa016899-6647-51c0-a2b2-168fe74fbc78", + "baselineJobId": "00f89541-bc7a-5835-a49d-8b99e8a0c873", + "baselineInputFingerprint": "4f752409b7a68fb14a679c25afe640fe61d1d27ea0cae9a4d45841677581db28", + "currentInputFingerprint": "77088f9d501af32ea6f1044ceaef9592757e1914f354eae1cd0f1cf9001d242a", "inputState": "changed", "reuseState": "stale", "relation": "root", "upstreamSpecIds": [ - "d2f677d8-e6cd-43c8-ae54-8df7734c28fa" + "9264a3d1-0870-4c79-af14-35ce50eaf4e9" ], "activeJobIds": [], "reasons": [ { "code": "inputs_changed", - "objectId": "4d5f438a-f86f-4f0f-b9aa-7d6e6cebeeef", + "objectId": "56d1b593-545a-4cb9-8903-fbf620101873", "referenceId": null, "fieldPaths": [ "spec.prompt" @@ -50,35 +50,35 @@ ] }, { - "specId": "dee2d143-046b-47fc-86f3-1c24f113c236", + "specId": "2997eb24-2271-4595-aebc-f336c55a92fe", "specRevision": 4, - "currentResultId": "1d33a0aa-803a-545f-88d7-0ac154e1f720", - "baselineJobId": "a038682a-0fe5-53e4-8191-e78a2df1d92e", - "baselineInputFingerprint": "b8a061d7123836311407bb42ef23b6e12033f0524c529f1673914c7793f29bf2", - "currentInputFingerprint": "b8a061d7123836311407bb42ef23b6e12033f0524c529f1673914c7793f29bf2", + "currentResultId": "6e7f2451-d616-53ea-8c73-d4488db11cff", + "baselineJobId": "5b45d7a6-deed-55f2-92a0-97b175037193", + "baselineInputFingerprint": "4196061e7d0e8067cdcb34c7a72da8a9d3e240564da3beefffd6d1179d79758d", + "currentInputFingerprint": "4196061e7d0e8067cdcb34c7a72da8a9d3e240564da3beefffd6d1179d79758d", "inputState": "equal", "reuseState": "pending_upstream", "relation": "downstream", "upstreamSpecIds": [ - "4d5f438a-f86f-4f0f-b9aa-7d6e6cebeeef" + "56d1b593-545a-4cb9-8903-fbf620101873" ], "activeJobIds": [], "reasons": [ { "code": "upstream_pending", - "objectId": "4d5f438a-f86f-4f0f-b9aa-7d6e6cebeeef", - "referenceId": "c936fa2f-fae2-4b38-869d-fb355edfbc2f", + "objectId": "56d1b593-545a-4cb9-8903-fbf620101873", + "referenceId": "1278b110-a3ec-4b05-9453-c680eae89508", "fieldPaths": [] } ] }, { - "specId": "7f268b78-755a-433e-8751-cdf17259877d", + "specId": "39390819-baf0-47cc-bc4e-dceb4fbb51b7", "specRevision": 4, - "currentResultId": "4c98012b-86e3-5a07-a496-affb1d644b17", - "baselineJobId": "6c90d034-a5d1-53c5-94e9-8f46647d6ff5", - "baselineInputFingerprint": "3c218cd8c9c95ecd2fa681b236beaa062a6c5bb62d1005bb587cd5367a07bb7e", - "currentInputFingerprint": "3c218cd8c9c95ecd2fa681b236beaa062a6c5bb62d1005bb587cd5367a07bb7e", + "currentResultId": "9059cef8-0d63-58ba-9cc4-082f51796ac5", + "baselineJobId": "c283b814-6d48-531e-8b31-4981f3a53df3", + "baselineInputFingerprint": "8406aced182d2b10851fa5029a7f199a17dd9421455a7d907e867921b1cbb0c7", + "currentInputFingerprint": "8406aced182d2b10851fa5029a7f199a17dd9421455a7d907e867921b1cbb0c7", "inputState": "equal", "reuseState": "reusable", "relation": "independent", @@ -89,48 +89,50 @@ ], "dependencies": [ { - "sourceSpecId": "d2f677d8-e6cd-43c8-ae54-8df7734c28fa", - "sourceItemId": "f31f1bee-df50-4378-8c1e-40c22050dec6", - "targetSpecId": "4d5f438a-f86f-4f0f-b9aa-7d6e6cebeeef", - "referenceId": "be3a9284-43d1-4dda-b47e-d12da4585da2", + "sourceSpecId": "9264a3d1-0870-4c79-af14-35ce50eaf4e9", + "sourceItemId": "5b47a640-b73a-416b-9308-a9e04e9e77f2", + "targetSpecId": "56d1b593-545a-4cb9-8903-fbf620101873", + "referenceId": "fdef75ed-6736-4644-8367-2b83a1fb5158", "role": "reference", - "assetId": "df7a7beb-bdb3-50f0-882d-644224938ed4", + "assetId": "5252d9b7-3f06-502a-b1a1-c3b3a010d6b3", "documentId": null, "inputConfirmed": true }, { - "sourceSpecId": "4d5f438a-f86f-4f0f-b9aa-7d6e6cebeeef", - "sourceItemId": "9c445317-46cb-4ed5-801c-4a357a406dad", - "targetSpecId": "dee2d143-046b-47fc-86f3-1c24f113c236", - "referenceId": "c936fa2f-fae2-4b38-869d-fb355edfbc2f", + "sourceSpecId": "56d1b593-545a-4cb9-8903-fbf620101873", + "sourceItemId": "c7adfdb2-33e1-4c6d-9651-e1381c87439f", + "targetSpecId": "2997eb24-2271-4595-aebc-f336c55a92fe", + "referenceId": "1278b110-a3ec-4b05-9453-c680eae89508", "role": "reference", - "assetId": "9cb90c95-d158-5c58-9a28-84b4d35aff9b", + "assetId": "ef2016b4-9d94-505f-a0bd-a70b5f045343", "documentId": null, "inputConfirmed": true } ], "timelineConsumers": [ { - "editorDocumentId": "35c2b0d7-a177-4161-aeda-4f77317dc6a3", + "editorDocumentId": "185ed3f0-7c98-4c58-adea-5a5fc565ed3a", "revision": 1, - "clipId": "B", - "assetId": "9cb90c95-d158-5c58-9a28-84b4d35aff9b", + "assetId": "ef2016b4-9d94-505f-a0bd-a70b5f045343", "specIds": [ - "4d5f438a-f86f-4f0f-b9aa-7d6e6cebeeef" + "56d1b593-545a-4cb9-8903-fbf620101873" ], "association": "asset_and_source", - "sourceItemId": "9c445317-46cb-4ed5-801c-4a357a406dad" + "sourceItemId": "c7adfdb2-33e1-4c6d-9651-e1381c87439f", + "kind": "clip", + "clipId": "B" }, { - "editorDocumentId": "35c2b0d7-a177-4161-aeda-4f77317dc6a3", + "editorDocumentId": "185ed3f0-7c98-4c58-adea-5a5fc565ed3a", "revision": 1, - "clipId": "C", - "assetId": "6e22e526-0f09-5e94-9d95-e7a21f60d890", + "assetId": "ed2582c2-fb58-5cfd-b91f-8186b29d3eb3", "specIds": [ - "dee2d143-046b-47fc-86f3-1c24f113c236" + "2997eb24-2271-4595-aebc-f336c55a92fe" ], "association": "asset_and_source", - "sourceItemId": "2bf7e3c4-b587-4fbb-adad-30c6a1dfbb45" + "sourceItemId": "bb0fa4f2-9e65-4d6e-9d90-7251cf7a7e8e", + "kind": "clip", + "clipId": "C" } ] } diff --git a/docs/development/generation-impact-validation.md b/docs/development/generation-impact-validation.md index c4c92f81f..299a57711 100644 --- a/docs/development/generation-impact-validation.md +++ b/docs/development/generation-impact-validation.md @@ -16,10 +16,10 @@ This records the dependency/reuse foundation for [#355](https://github.com/Think Use `generation.impact` through `POST /api/creation/projects/{projectId}/queries`, the existing Agent query tool, or `opendirector --project PROJECT_UUID query generation.impact --file impact-query.json`. The HTTP request uses the existing local-API request-header protection. No editing session is required. - Query and report definitions: [commands.py](../../packages/core/src/opendirector/domain/creation/commands.py), [impact.py](../../packages/core/src/opendirector/domain/creation/impact.py), [generated TypeScript](../../src/contracts/generated.ts). -- Frontend: `CreationClient.generationImpact(rootSpecIds, { signal })` in [creationClient.ts](../../src/backend/creationClient.ts). It performs a read without installing the response as a project snapshot or entering the mutation queue. +- Frontend: `CreationClient.generationImpact(rootSpecIds, { signal, maxNodes })` in [creationClient.ts](../../src/backend/creationClient.ts). The options are optional. It performs a read without installing the response as a project snapshot or entering the mutation queue. - Display: pass stable states/reasons to `generationImpactText(code, t)` in [generationImpactText.ts](../../src/backend/generationImpactText.ts). Unknown codes have a translated fallback; no provider payload is rendered. - Show both `inputState` and `reuseState`, the reasons and original `baselineJobId`/`activeJobIds`. Retain `projectVersion`, `eventCursor` and object revisions for context; they do not reserve a future edit. Any workbench action continues through existing commands with current versions, locks and authorization. -- Reports cover all project generation configurations. `relation` is relative to the requested roots; `timelineConsumers` covers only those roots and their downstream configurations. Fixed asset usage and source associations are review evidence, not automatic replacement instructions. +- Reports cover all project generation configurations. `relation` is relative to the requested roots; `timelineConsumers` covers only those roots and their downstream configurations. Consumers are discriminated as `clip` with `clipId`, or `text_overlay` with `overlayId`. Fixed asset usage and source associations are review evidence, not automatic replacement instructions. Recoverable failures and unresolved cancellations retain their original `activeJobIds`. ### Recorded request and response @@ -27,10 +27,10 @@ The [request](fixtures/generation-impact-request.json) and [response](fixtures/g | Test object | Spec ID | Current inputs | Reuse | Relation | | --- | --- | --- | --- | --- | -| A | `d2f677d8-e6cd-43c8-ae54-8df7734c28fa` | equal | reusable | independent | -| B | `4d5f438a-f86f-4f0f-b9aa-7d6e6cebeeef` | changed | stale | root | -| C | `dee2d143-046b-47fc-86f3-1c24f113c236` | equal | pending_upstream | downstream | -| D | `7f268b78-755a-433e-8751-cdf17259877d` | equal | reusable | independent | +| A | `9264a3d1-0870-4c79-af14-35ce50eaf4e9` | equal | reusable | independent | +| B | `56d1b593-545a-4cb9-8903-fbf620101873` | changed | stale | root | +| C | `2997eb24-2271-4595-aebc-f336c55a92fe` | equal | pending_upstream | downstream | +| D | `39390819-baf0-47cc-bc4e-dceb4fbb51b7` | equal | reusable | independent | A is an upstream dependency of B, but is not downstream of the requested B root. The timeline contains B/C/D; the response lists B/C consumers with their retained assets and source associations. D remains outside the requested downstream scope. The report contains IDs, fingerprints and controlled field paths, not prompts, provider URLs, credentials, local paths or raw adapter data. @@ -42,7 +42,13 @@ Subject slots retain assets in their editor document. Their `inputConnections` d The comparison uses the same frozen inputs as generation acceptance. Known adapter output settings and generated random seeds remain execution facts. Unknown adapter extension fields or missing saved model rules prevent a reuse claim. Current storage has no reconstructable guide/window/direction plan for external workflows; a future persisted field needs explicit comparison coverage. `reusable` means the registered existing output can be reused under the compared inputs, not a remote cache hit or deterministic new generation. -Inputs are bounded to 100 distinct roots, at most 10,000 configurations (default budget 2,000), and 20,000 active references/expanded edges. A limit error returns no partial success. Unresolved dependencies and cycles remain explicit uncertainty, including dependent nodes; no execution order or retry command is invented. +Inputs are bounded to 100 distinct roots, at most 10,000 configurations (default budget 2,000), and 20,000 active references/expanded edges. Timeline consumers and retained Job IDs share a combined evidence limit of 20,000 entries. A limit error returns no partial success, and HTTP and Agent preserve its stable code. Unresolved dependencies and cycles remain explicit uncertainty, including dependent nodes; no execution order or retry command is invented. + +HTTP and Agent queries read the generation service's existing capability observations without refreshing them. Repeated queries reuse the safe asset reader's bounded file-signature verification cache; replaced or deleted files are checked again. Project directory resolution remains under the existing storage lock. This does not introduce a new persistent index or claim a measured production throughput improvement. + +Direct application callers should pass their owning generation service's `availability` and shared `assets` when constructing `CreationCanvas`. Without an injected capability service, the standalone reader has only local configuration rules, not another process's transient observations. + +One display detail remains deferred: if a clip is explicitly connected through an ordinary material node containing a related result, the report includes its exact asset usage but omits that material node's `sourceItemId`. This does not remove the consumer or imply a live generation dependency. ## Reproducible validation diff --git a/docs/guides/cli.md b/docs/guides/cli.md index bdd30ff01..62026a6f9 100644 --- a/docs/guides/cli.md +++ b/docs/guides/cli.md @@ -54,7 +54,7 @@ Agent 的 Shell 通过 PATH 使用同一个 `opendirector`。宿主提供受令 `generation.impact` compares saved current inputs with the successful Job behind each adopted result. Replace the UUID in the parameter file with a real GenerationSpec ID from the selected project, not a canvas item or Job ID. The query does not open an edit session, submit generation, adopt candidates or edit the timeline. ```json -{"rootSpecIds":["4d5f438a-f86f-4f0f-b9aa-7d6e6cebeeef"]} +{"rootSpecIds":["56d1b593-545a-4cb9-8903-fbf620101873"]} ``` Save this as `impact-query.json` / 保存为 `impact-query.json`: @@ -76,13 +76,13 @@ opendirector --project PROJECT_UUID query generation.impact --file impact-query. For A→B→C and independent D, editing only B's prompt makes B `stale`, C `pending_upstream` and D `reusable`. A B2 candidate does not change C's current inputs until adopted; after adoption, C following B becomes `stale`. C pinned to B1 remains unchanged. `inputState` separately describes current input equality, while `relation` describes reachability from the requested roots. Independent nodes still have their own inputs and files checked. -报告含 `projectVersion`、`eventCursor`、各配置版本、`baselineJobId`、`activeJobIds`、稳定原因码及受控字段路径。时间线使用点仅列出请求根和下游配置的相关片段,区分固定素材与来源关联,不代表允许自动替换。查询后工程可能继续变化;修改前须重读相关对象、校验当前版本和锁定。活动或未知提交先查询原 Job,不能因为本报告另建任务重发。 +报告含 `projectVersion`、`eventCursor`、各配置版本、`baselineJobId`、`activeJobIds`、稳定原因码及受控字段路径。`activeJobIds` 包括可恢复失败和远端取消未决的原任务。时间线使用点仅列出请求根和下游配置相关的媒体片段(`kind=clip`、`clipId`)与文字来源(`kind=text_overlay`、`overlayId`),区分固定素材与来源关联,不代表允许自动替换。查询后工程可能继续变化;修改前须重读相关对象、校验当前版本和锁定。活动或未知提交先查询原 Job,不能因为本报告另建任务重发。 -The report includes `projectVersion`, `eventCursor`, spec revisions, `baselineJobId`, `activeJobIds`, stable reason codes and controlled field paths. Timeline consumers cover the requested roots and their downstream configurations, distinguishing fixed assets from source associations; they do not authorize replacement. State may change after a query. Re-read affected objects and check current versions and locks before any modification. Inspect the original Job for active or uncertain submissions instead of creating another attempt from this report. +The report includes `projectVersion`, `eventCursor`, spec revisions, `baselineJobId`, `activeJobIds`, stable reason codes and controlled field paths. `activeJobIds` includes recoverable failures and unresolved remote cancellations. Timeline consumers cover media clips (`kind=clip`, `clipId`) and text sources (`kind=text_overlay`, `overlayId`) for the requested roots and their downstream configurations, distinguishing fixed assets from source associations; they do not authorize replacement. State may change after a query. Re-read affected objects and check current versions and locks before any modification. Inspect the original Job for active or uncertain submissions instead of creating another attempt from this report. -每次最多 100 个不同根;检查工程全部生成配置,`maxNodes` 默认 2,000、最大 10,000,活动参考及展开依赖边最多 20,000。超限返回 `impact_scope_exceeded`,不返回截断后看似完整的报告。缺少可重建的 guide、窗口或扩展 adapter 依据时保持未知。复用只针对已有素材,不保证重新生成确定性、创作质量、服务商健康或远端 latent/cache 命中。外部 ComfyUI 未登记的 graph/history/cache 仍需单独核对。 +每次最多 100 个不同根;检查工程全部生成配置,`maxNodes` 默认 2,000、最大 10,000,活动参考及展开依赖边最多 20,000;时间线使用点与原任务身份合计最多 20,000 条。超限返回 `impact_scope_exceeded`,不返回截断后看似完整的报告。缺少可重建的 guide、窗口或扩展 adapter 依据时保持未知。复用只针对已有素材,不保证重新生成确定性、创作质量、服务商健康或远端 latent/cache 命中。外部 ComfyUI 未登记的 graph/history/cache 仍需单独核对。 -Queries accept up to 100 distinct roots and inspect all generation configurations in the project. `maxNodes` defaults to 2,000 with a maximum of 10,000; active references and expanded edges are limited to 20,000. Overflow returns `impact_scope_exceeded`, not a truncated report. Missing reconstructable guide, window or adapter-extension evidence remains unknown. Reuse concerns existing assets, not deterministic regeneration, creative quality, provider health or remote latent/cache hits. Unregistered external ComfyUI graphs, history and caches require separate checks. +Queries accept up to 100 distinct roots and inspect all generation configurations in the project. `maxNodes` defaults to 2,000 with a maximum of 10,000; active references and expanded edges are limited to 20,000. Timeline consumers and retained Job IDs share a separate combined limit of 20,000 entries. Overflow returns `impact_scope_exceeded`, not a truncated report. Missing reconstructable guide, window or adapter-extension evidence remains unknown. Reuse concerns existing assets, not deterministic regeneration, creative quality, provider health or remote latent/cache hits. Unregistered external ComfyUI graphs, history and caches require separate checks. ## 更新生成配置 diff --git a/packages/core/src/opendirector/agent/gateway.py b/packages/core/src/opendirector/agent/gateway.py index 6f11d131f..40a765095 100644 --- a/packages/core/src/opendirector/agent/gateway.py +++ b/packages/core/src/opendirector/agent/gateway.py @@ -11,6 +11,7 @@ from opendirector.agent.tools import AgentTools, tools from opendirector.domain.projects import ProjectError from opendirector.domain.creation.commands import COMMAND_MODELS +from opendirector.domain.creation.validation import ContractError @dataclass(frozen=True, kw_only=True) @@ -95,6 +96,8 @@ async def execute(self, call_id: str, name: str, arguments: dict[str, JsonValue] messages.append(f"{path or 'command'}: {issue['msg']}") error = '; '.join(messages) return ToolResult(value={'error': error}, error=error) + except ContractError as failure: + return ToolResult(value={'error': str(failure), 'code': failure.issue.code}, error=str(failure)) except (ProjectError, ValueError, KeyError, OSError, UnicodeError) as failure: details = {'error': str(failure)} if isinstance(failure, ProjectError): diff --git a/packages/core/src/opendirector/agent/tools.py b/packages/core/src/opendirector/agent/tools.py index 078852868..29ec94167 100644 --- a/packages/core/src/opendirector/agent/tools.py +++ b/packages/core/src/opendirector/agent/tools.py @@ -368,7 +368,7 @@ def recording(): # A rejected query must name the accepted types rather than echo a # tag list the model has to reinterpret. raise ProjectError(query_guidance(failure)) from None - result = await CreationCanvas(self.projects).query(query) + result = await CreationCanvas(self.projects, availability=self.availability, assets=self.assets).query(query) if query.type == 'asset.preview' and 'preview' in result: with self.projects.local.transaction() as db: project_directory, _, _ = self.projects._load(db, project_id) diff --git a/packages/core/src/opendirector/application/creation_canvas.py b/packages/core/src/opendirector/application/creation_canvas.py index df04511b1..69642030c 100644 --- a/packages/core/src/opendirector/application/creation_canvas.py +++ b/packages/core/src/opendirector/application/creation_canvas.py @@ -290,10 +290,11 @@ def bind_unique_timeline_sources(data, document, *, new_slot_ids): class CreationCanvas: - def __init__(self, projects): + def __init__(self, projects, *, availability=None, assets=None): self.projects = projects + self.availability = availability from opendirector.application.creation_assets import CreationAssets - self.assets = CreationAssets(projects) + self.assets = assets if assets is not None else CreationAssets(projects) def _available(self, asset): return self.assets.reference_available(asset.projectId, asset.id) @@ -853,7 +854,7 @@ def query_snapshot(self, query): from opendirector.application.creation_history import CreationHistory if query.type == 'generation.impact': from opendirector.application.creation_impact import CreationImpact - return CreationImpact(self.projects).query(query) + return CreationImpact(self.projects, availability=self.availability, assets=self.assets).query(query) snapshot = self.projects.snapshot(query.projectId) history = CreationHistory(self.projects) if query.type == 'project.get': diff --git a/packages/core/src/opendirector/application/creation_impact.py b/packages/core/src/opendirector/application/creation_impact.py index 366e487cf..6374713b2 100644 --- a/packages/core/src/opendirector/application/creation_impact.py +++ b/packages/core/src/opendirector/application/creation_impact.py @@ -7,12 +7,13 @@ from opendirector.domain.creation.commands import GenerationImpactQuery from opendirector.domain.creation.generation import ResolvedReference, freeze_input_snapshot from opendirector.domain.creation.impact import ( - GenerationImpactItem, GenerationImpactReport, ImpactDependency, ImpactReason, TimelineImpactConsumer, + GenerationImpactItem, GenerationImpactReport, ImpactDependency, ImpactReason, + TimelineClipImpactConsumer, TimelineTextImpactConsumer, ) from opendirector.domain.creation.models import ModelSnapshot from opendirector.domain.creation.project import ProjectSnapshot from opendirector.domain.creation.validation import ContractError -from opendirector.domain.rule_facts import MAX_REFERENCES +from opendirector.domain.rule_facts import GENERATION_IMPACT_EVIDENCE_LIMIT, MAX_REFERENCES from opendirector.domain.projects import ProjectError from opendirector.ports.gateway import gateway @@ -20,15 +21,17 @@ class CreationImpact: - def __init__(self, projects): + def __init__(self, projects, *, availability=None, assets=None): + from opendirector.application.creation_assets import CreationAssets self.projects = projects + self.availability = availability + self.assets = assets if assets is not None else CreationAssets(projects) def query(self, query: GenerationImpactQuery) -> GenerationImpactReport: - from opendirector.application.creation_assets import CreationAssets from opendirector.application.model_availability import ModelAvailability snapshot = self.projects.snapshot(query.projectId) configs = gateway().models(self.projects.local.repository) - availability = ModelAvailability(configs) + availability = self.availability or ModelAvailability(configs) models = {} # One locked catalog read. Effective rules use only cached/local facts; # never prepare/refresh a capability probe for an impact query. @@ -44,11 +47,9 @@ def query(self, query: GenerationImpactQuery) -> GenerationImpactReport: ('kind', 'modelId', 'url', 'protocol', 'connectionType', 'proxyMode', 'videoAdapter')}) except ValueError: models[identity] = None - assets = CreationAssets(self.projects) - def available(asset_id): try: - assets.reference_available(query.projectId, asset_id, snapshot=snapshot) + self.assets.reference_available(query.projectId, asset_id, snapshot=snapshot) return True except (ProjectError, ContractError, OSError, UnicodeError): return False @@ -106,11 +107,16 @@ def __init__(self, snapshot): self.documents = {d.id: d for d in snapshot.editorDocuments} self.references = {} self.active_jobs = {} + self.active_job_count = 0 for ref in snapshot.references: if ref.active: self.references.setdefault(ref.targetSpecId, []).append(ref) for job in snapshot.jobs: - if job.status in {'queued', 'running', 'interrupted'} or job.recovery == 'review': + if (job.status in {'queued', 'running', 'interrupted'} or job.recovery == 'review' + or job.resumeAllowed or job.remoteCancellation in {'requested', 'unknown'}): + self.active_job_count += 1 + if self.active_job_count > GENERATION_IMPACT_EVIDENCE_LIMIT: + raise ContractError('impact_scope_exceeded', '依赖分析超出节点、参考或证据数量上限。') self.active_jobs.setdefault(job.inputSnapshot.spec.id, []).append(job.id) def resolution_view(self, spec): @@ -249,6 +255,12 @@ def _timeline_consumers(index, related): if result.specId in related: by_asset.setdefault(result.asset.assetId, set()).add(result.specId) consumers = [] + + def append(consumer): + if len(consumers) + index.active_job_count >= GENERATION_IMPACT_EVIDENCE_LIMIT: + raise ContractError('impact_scope_exceeded', '依赖分析超出节点、参考或证据数量上限。') + consumers.append(consumer) + for document in index.snapshot.editorDocuments: if document.kind != 'timeline': continue @@ -262,10 +274,17 @@ def _timeline_consumers(index, related): source_specs = {source_spec} if source_spec in related else set() if not asset_specs and not source_specs: continue - consumers.append(TimelineImpactConsumer(editorDocumentId=document.id, revision=document.revision, + append(TimelineClipImpactConsumer(editorDocumentId=document.id, revision=document.revision, clipId=clip.id, assetId=clip.resource.asset.assetId, specIds=tuple(sorted(asset_specs | source_specs)), association='asset_and_source' if asset_specs and source_specs else 'asset' if asset_specs else 'source', sourceItemId=source.id if source_specs else None)) + for overlay in document.data.overlays: + if overlay.sourceAsset is None: + continue + asset_specs = by_asset.get(overlay.sourceAsset.assetId, set()) + if asset_specs: + append(TimelineTextImpactConsumer(editorDocumentId=document.id, revision=document.revision, + overlayId=overlay.id, assetId=overlay.sourceAsset.assetId, specIds=tuple(sorted(asset_specs)), association='asset')) return tuple(consumers) diff --git a/packages/core/src/opendirector/domain/creation/impact.py b/packages/core/src/opendirector/domain/creation/impact.py index fc9a29b91..8900516b0 100644 --- a/packages/core/src/opendirector/domain/creation/impact.py +++ b/packages/core/src/opendirector/domain/creation/impact.py @@ -1,9 +1,11 @@ """Reconstructible, read-only dependency and adopted-result reuse evidence.""" -from typing import Literal +from typing import Annotated, Literal, Union from uuid import UUID from pydantic import Field, model_validator +from opendirector.domain.rule_facts import GENERATION_IMPACT_EVIDENCE_LIMIT + from .base import Contract, Digest, Identifier, ObjectVersion, Revision, unique @@ -28,16 +30,30 @@ class ImpactDependency(Contract): inputConfirmed: bool = Field(description='Whether the current resolver confirmed this transmitted input. False is uncertainty, not an empty dependency.') -class TimelineImpactConsumer(Contract): +class TimelineImpactConsumerBase(Contract): editorDocumentId: UUID = Field(description='Current timeline document identity.') revision: Revision = Field(description='Timeline document revision read by this report.') - clipId: Identifier = Field(description='Retained timeline clip identity.') - assetId: UUID = Field(description='Asset currently retained in this clip; the query never replaces it.') + assetId: UUID = Field(description='Asset currently retained in this timeline usage; the query never replaces it.') specIds: tuple[UUID, ...] = Field(description='Related generation specs from exact result or source identities.') association: Literal['asset', 'source', 'asset_and_source'] = Field(description='Exact retained result asset, explicit input connection, or both; none implies automatic replacement.') sourceItemId: UUID | None = Field(default=None, description='Source item from the document input connection, when relevant.') +class TimelineClipImpactConsumer(TimelineImpactConsumerBase): + kind: Literal['clip'] = Field(default='clip', description='Retained media clip usage.') + clipId: Identifier = Field(description='Retained timeline clip identity.') + + +class TimelineTextImpactConsumer(TimelineImpactConsumerBase): + kind: Literal['text_overlay'] = Field(default='text_overlay', description='Retained text overlay source usage.') + overlayId: Identifier = Field(description='Retained timeline text overlay identity.') + association: Literal['asset'] = Field(description='Exact frozen source text asset; subsequent source edits do not replace overlay text.') + sourceItemId: None = Field(default=None, description='Text overlays retain source assets without a live source connection.') + + +TimelineImpactConsumer = Annotated[Union[TimelineClipImpactConsumer, TimelineTextImpactConsumer], Field(discriminator='kind')] + + class GenerationImpactItem(Contract): specId: UUID = Field(description='Generation configuration identity.') specRevision: Revision = Field(description='Configuration revision read by this report.') @@ -49,7 +65,8 @@ class GenerationImpactItem(Contract): reuseState: Literal['reusable', 'stale', 'pending_upstream', 'unavailable', 'unknown', 'no_result'] = Field(description='Result reuse evidence, independent of creative approval and remote cache availability.') relation: Literal['root', 'downstream', 'independent'] = Field(description='Relationship to requested roots, not an invalidation decision.') upstreamSpecIds: tuple[UUID, ...] = Field(default=(), description='Direct current generation dependencies only; no enumeration of all paths.') - activeJobIds: tuple[UUID, ...] = Field(default=(), description='Active or unresolved job identities; inspect the original jobs before deciding any action.') + activeJobIds: tuple[UUID, ...] = Field(default=(), max_length=GENERATION_IMPACT_EVIDENCE_LIMIT, + description='Active, recoverable or unresolved job identities; inspect the original jobs before deciding any action.') reasons: tuple[ImpactReason, ...] = Field(default=(), description='Bounded direct evidence for this decision.') @@ -60,7 +77,8 @@ class GenerationImpactReport(Contract): rootSpecIds: tuple[UUID, ...] = Field(min_length=1, max_length=100, description='Unique requested roots in this project.') items: tuple[GenerationImpactItem, ...] = Field(max_length=10000, description='All project generation configurations, including independent branches.') dependencies: tuple[ImpactDependency, ...] = Field(max_length=20000, description='Current effective follow bindings; scope overflow fails instead of truncating.') - timelineConsumers: tuple[TimelineImpactConsumer, ...] = Field(description='Current timeline usages requiring review, never automatic replacement instructions.') + timelineConsumers: tuple[TimelineImpactConsumer, ...] = Field(max_length=GENERATION_IMPACT_EVIDENCE_LIMIT, + description='Current clip and text overlay usages requiring review; combined with all activeJobIds, limited to 20000 entries. Never automatic replacement instructions.') @model_validator(mode='after') def identities(self): @@ -70,4 +88,6 @@ def identities(self): raise ValueError('Impact roots must belong to the reported specs') if self.projectVersion.objectType != 'project': raise ValueError('Impact report requires a project version') + if len(self.timelineConsumers) + sum(len(item.activeJobIds) for item in self.items) > GENERATION_IMPACT_EVIDENCE_LIMIT: + raise ValueError('Impact report exceeds the retained evidence budget') return self diff --git a/packages/core/src/opendirector/domain/creation/schema.py b/packages/core/src/opendirector/domain/creation/schema.py index b1dd6bc11..a22102530 100644 --- a/packages/core/src/opendirector/domain/creation/schema.py +++ b/packages/core/src/opendirector/domain/creation/schema.py @@ -7,7 +7,7 @@ from .commands import Command, CommandReceipt, ProjectEvent, Query from .editors import EditorDocument from .generation import ExecutionParameters, GenerationSpec, InputSnapshot, Job, PromptPart, Reference, ResultVersion -from .impact import GenerationImpactReport +from .impact import GenerationImpactReport, TimelineImpactConsumer from .models import ModelConfigPublic, ModelConfigWrite, ModelKind, VideoMode from .project import ProjectSnapshot, ViewState from .timeline_packages import TimelinePackageManifest, TimelinePackageImportRequest, TimelinePackageImportReceipt @@ -44,4 +44,5 @@ class CreationContracts(Contract): 'EditorDocument': EditorDocument, 'Command': Command, 'ExecutionParameters': ExecutionParameters, 'PromptPart': PromptPart, 'MediaRole': MediaRole, 'RoleAction': RoleAction, 'ModelKind': ModelKind, 'VideoMode': VideoMode, + 'TimelineImpactConsumer': TimelineImpactConsumer, } diff --git a/packages/core/src/opendirector/domain/rule_facts.py b/packages/core/src/opendirector/domain/rule_facts.py index 91f96d755..6088b409a 100644 --- a/packages/core/src/opendirector/domain/rule_facts.py +++ b/packages/core/src/opendirector/domain/rule_facts.py @@ -12,6 +12,7 @@ # Storage/structure guard. Provider budgets are checked separately. MAX_REFERENCES = 64 +GENERATION_IMPACT_EVIDENCE_LIMIT = 20000 TEXT_REFERENCE_BYTES = 64 * 1024 # Chat and agent image references, and the browser fallback when a payload # omits imageBytes. Adapter profiles publish their own imageBytes. diff --git a/src/backend/creationClient.ts b/src/backend/creationClient.ts index 35f1721fa..85d6d584c 100644 --- a/src/backend/creationClient.ts +++ b/src/backend/creationClient.ts @@ -219,13 +219,14 @@ export class CreationClient { } generationImpact( rootSpecIds: readonly string[], - options: ReadOptions = {}, + options: ReadOptions & { maxNodes?: number } = {}, ): Promise { const query: GenerationImpactQueryInput = { type: "generation.impact", queryId: crypto.randomUUID(), projectId: this.id, rootSpecIds: [...rootSpecIds], + ...(options.maxNodes !== undefined ? { maxNodes: options.maxNodes } : {}), }; return resilientRead( (signal) => request(`${creationPath(this.id)}/queries`, { diff --git a/src/backend/generationImpactText.ts b/src/backend/generationImpactText.ts index d037326b6..766f87cca 100644 --- a/src/backend/generationImpactText.ts +++ b/src/backend/generationImpactText.ts @@ -25,6 +25,8 @@ const messages: Readonly> = { execution_basis_incomplete: "generationImpact.execution_basis_incomplete", dependency_cycle: "generationImpact.dependency_cycle", impact_scope_exceeded: "generationImpact.impact_scope_exceeded", + clip: "generationImpact.clip", + text_overlay: "generationImpact.text_overlay", }; /** Localize stable codes without rendering unknown provider or user content. */ diff --git a/src/contracts/creation.schema.json b/src/contracts/creation.schema.json index e1f6732b5..a739cd81a 100644 --- a/src/contracts/creation.schema.json +++ b/src/contracts/creation.schema.json @@ -5755,11 +5755,12 @@ }, "activeJobIds": { "default": [], - "description": "Active or unresolved job identities; inspect the original jobs before deciding any action.", + "description": "Active, recoverable or unresolved job identities; inspect the original jobs before deciding any action.", "items": { "format": "uuid", "type": "string" }, + "maxItems": 20000, "title": "Activejobids", "type": "array" }, @@ -5883,10 +5884,25 @@ "type": "array" }, "timelineConsumers": { - "description": "Current timeline usages requiring review, never automatic replacement instructions.", + "description": "Current clip and text overlay usages requiring review; combined with all activeJobIds, limited to 20000 entries. Never automatic replacement instructions.", "items": { - "$ref": "#/$defs/TimelineImpactConsumer" + "discriminator": { + "mapping": { + "clip": "#/$defs/TimelineClipImpactConsumer", + "text_overlay": "#/$defs/TimelineTextImpactConsumer" + }, + "propertyName": "kind" + }, + "oneOf": [ + { + "$ref": "#/$defs/TimelineClipImpactConsumer" + }, + { + "$ref": "#/$defs/TimelineTextImpactConsumer" + } + ] }, + "maxItems": 20000, "title": "Timelineconsumers", "type": "array" } @@ -13588,6 +13604,87 @@ "title": "TimelineClip", "type": "object" }, + "TimelineClipImpactConsumer": { + "additionalProperties": false, + "properties": { + "editorDocumentId": { + "description": "Current timeline document identity.", + "format": "uuid", + "title": "Editordocumentid", + "type": "string" + }, + "revision": { + "description": "Timeline document revision read by this report.", + "minimum": 1, + "title": "Revision", + "type": "integer" + }, + "assetId": { + "description": "Asset currently retained in this timeline usage; the query never replaces it.", + "format": "uuid", + "title": "Assetid", + "type": "string" + }, + "specIds": { + "description": "Related generation specs from exact result or source identities.", + "items": { + "format": "uuid", + "type": "string" + }, + "title": "Specids", + "type": "array" + }, + "association": { + "description": "Exact retained result asset, explicit input connection, or both; none implies automatic replacement.", + "enum": [ + "asset", + "source", + "asset_and_source" + ], + "title": "Association", + "type": "string" + }, + "sourceItemId": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Source item from the document input connection, when relevant.", + "title": "Sourceitemid" + }, + "kind": { + "const": "clip", + "default": "clip", + "description": "Retained media clip usage.", + "title": "Kind", + "type": "string" + }, + "clipId": { + "description": "Retained timeline clip identity.", + "maxLength": 100, + "minLength": 1, + "pattern": "\\S", + "title": "Clipid", + "type": "string" + } + }, + "required": [ + "editorDocumentId", + "revision", + "assetId", + "specIds", + "association", + "clipId" + ], + "title": "TimelineClipImpactConsumer", + "type": "object" + }, "TimelineData": { "additionalProperties": false, "properties": { @@ -13745,7 +13842,7 @@ "title": "TimelineFontResource", "type": "object" }, - "TimelineImpactConsumer": { + "TimelineImpactConsumerBase": { "additionalProperties": false, "properties": { "editorDocumentId": { @@ -13760,16 +13857,8 @@ "title": "Revision", "type": "integer" }, - "clipId": { - "description": "Retained timeline clip identity.", - "maxLength": 100, - "minLength": 1, - "pattern": "\\S", - "title": "Clipid", - "type": "string" - }, "assetId": { - "description": "Asset currently retained in this clip; the query never replaces it.", + "description": "Asset currently retained in this timeline usage; the query never replaces it.", "format": "uuid", "title": "Assetid", "type": "string" @@ -13811,12 +13900,11 @@ "required": [ "editorDocumentId", "revision", - "clipId", "assetId", "specIds", "association" ], - "title": "TimelineImpactConsumer", + "title": "TimelineImpactConsumerBase", "type": "object" }, "TimelinePackageExportFile": { @@ -14331,6 +14419,75 @@ "title": "TimelineTextBackground", "type": "object" }, + "TimelineTextImpactConsumer": { + "additionalProperties": false, + "properties": { + "editorDocumentId": { + "description": "Current timeline document identity.", + "format": "uuid", + "title": "Editordocumentid", + "type": "string" + }, + "revision": { + "description": "Timeline document revision read by this report.", + "minimum": 1, + "title": "Revision", + "type": "integer" + }, + "assetId": { + "description": "Asset currently retained in this timeline usage; the query never replaces it.", + "format": "uuid", + "title": "Assetid", + "type": "string" + }, + "specIds": { + "description": "Related generation specs from exact result or source identities.", + "items": { + "format": "uuid", + "type": "string" + }, + "title": "Specids", + "type": "array" + }, + "association": { + "const": "asset", + "description": "Exact frozen source text asset; subsequent source edits do not replace overlay text.", + "title": "Association", + "type": "string" + }, + "sourceItemId": { + "default": null, + "description": "Text overlays retain source assets without a live source connection.", + "title": "Sourceitemid", + "type": "null" + }, + "kind": { + "const": "text_overlay", + "default": "text_overlay", + "description": "Retained text overlay source usage.", + "title": "Kind", + "type": "string" + }, + "overlayId": { + "description": "Retained timeline text overlay identity.", + "maxLength": 100, + "minLength": 1, + "pattern": "\\S", + "title": "Overlayid", + "type": "string" + } + }, + "required": [ + "editorDocumentId", + "revision", + "assetId", + "specIds", + "association", + "overlayId" + ], + "title": "TimelineTextImpactConsumer", + "type": "object" + }, "TimelineTextOverlay": { "additionalProperties": false, "properties": { @@ -22422,11 +22579,12 @@ }, "activeJobIds": { "default": [], - "description": "Active or unresolved job identities; inspect the original jobs before deciding any action.", + "description": "Active, recoverable or unresolved job identities; inspect the original jobs before deciding any action.", "items": { "format": "uuid", "type": "string" }, + "maxItems": 20000, "title": "Activejobids", "type": "array" }, @@ -22558,10 +22716,25 @@ "type": "array" }, "timelineConsumers": { - "description": "Current timeline usages requiring review, never automatic replacement instructions.", + "description": "Current clip and text overlay usages requiring review; combined with all activeJobIds, limited to 20000 entries. Never automatic replacement instructions.", "items": { - "$ref": "#/$defs/TimelineImpactConsumer" + "discriminator": { + "mapping": { + "clip": "#/$defs/TimelineClipImpactConsumer", + "text_overlay": "#/$defs/TimelineTextImpactConsumer" + }, + "propertyName": "kind" + }, + "oneOf": [ + { + "$ref": "#/$defs/TimelineClipImpactConsumer" + }, + { + "$ref": "#/$defs/TimelineTextImpactConsumer" + } + ] }, + "maxItems": 20000, "title": "Timelineconsumers", "type": "array" } @@ -30573,6 +30746,89 @@ "title": "TimelineClip", "type": "object" }, + "TimelineClipImpactConsumer": { + "additionalProperties": false, + "properties": { + "editorDocumentId": { + "description": "Current timeline document identity.", + "format": "uuid", + "title": "Editordocumentid", + "type": "string" + }, + "revision": { + "description": "Timeline document revision read by this report.", + "minimum": 1, + "title": "Revision", + "type": "integer" + }, + "assetId": { + "description": "Asset currently retained in this timeline usage; the query never replaces it.", + "format": "uuid", + "title": "Assetid", + "type": "string" + }, + "specIds": { + "description": "Related generation specs from exact result or source identities.", + "items": { + "format": "uuid", + "type": "string" + }, + "title": "Specids", + "type": "array" + }, + "association": { + "description": "Exact retained result asset, explicit input connection, or both; none implies automatic replacement.", + "enum": [ + "asset", + "source", + "asset_and_source" + ], + "title": "Association", + "type": "string" + }, + "sourceItemId": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Source item from the document input connection, when relevant.", + "title": "Sourceitemid" + }, + "kind": { + "const": "clip", + "default": "clip", + "description": "Retained media clip usage.", + "title": "Kind", + "type": "string" + }, + "clipId": { + "description": "Retained timeline clip identity.", + "maxLength": 100, + "minLength": 1, + "pattern": "\\S", + "title": "Clipid", + "type": "string" + } + }, + "required": [ + "editorDocumentId", + "revision", + "assetId", + "specIds", + "association", + "sourceItemId", + "kind", + "clipId" + ], + "title": "TimelineClipImpactConsumer", + "type": "object" + }, "TimelineData": { "additionalProperties": false, "properties": { @@ -30734,7 +30990,7 @@ "title": "TimelineFontResource", "type": "object" }, - "TimelineImpactConsumer": { + "TimelineImpactConsumerBase": { "additionalProperties": false, "properties": { "editorDocumentId": { @@ -30749,16 +31005,8 @@ "title": "Revision", "type": "integer" }, - "clipId": { - "description": "Retained timeline clip identity.", - "maxLength": 100, - "minLength": 1, - "pattern": "\\S", - "title": "Clipid", - "type": "string" - }, "assetId": { - "description": "Asset currently retained in this clip; the query never replaces it.", + "description": "Asset currently retained in this timeline usage; the query never replaces it.", "format": "uuid", "title": "Assetid", "type": "string" @@ -30800,13 +31048,12 @@ "required": [ "editorDocumentId", "revision", - "clipId", "assetId", "specIds", "association", "sourceItemId" ], - "title": "TimelineImpactConsumer", + "title": "TimelineImpactConsumerBase", "type": "object" }, "TimelinePackageExportFile": { @@ -31336,6 +31583,77 @@ "title": "TimelineTextBackground", "type": "object" }, + "TimelineTextImpactConsumer": { + "additionalProperties": false, + "properties": { + "editorDocumentId": { + "description": "Current timeline document identity.", + "format": "uuid", + "title": "Editordocumentid", + "type": "string" + }, + "revision": { + "description": "Timeline document revision read by this report.", + "minimum": 1, + "title": "Revision", + "type": "integer" + }, + "assetId": { + "description": "Asset currently retained in this timeline usage; the query never replaces it.", + "format": "uuid", + "title": "Assetid", + "type": "string" + }, + "specIds": { + "description": "Related generation specs from exact result or source identities.", + "items": { + "format": "uuid", + "type": "string" + }, + "title": "Specids", + "type": "array" + }, + "association": { + "const": "asset", + "description": "Exact frozen source text asset; subsequent source edits do not replace overlay text.", + "title": "Association", + "type": "string" + }, + "sourceItemId": { + "default": null, + "description": "Text overlays retain source assets without a live source connection.", + "title": "Sourceitemid", + "type": "null" + }, + "kind": { + "const": "text_overlay", + "default": "text_overlay", + "description": "Retained text overlay source usage.", + "title": "Kind", + "type": "string" + }, + "overlayId": { + "description": "Retained timeline text overlay identity.", + "maxLength": 100, + "minLength": 1, + "pattern": "\\S", + "title": "Overlayid", + "type": "string" + } + }, + "required": [ + "editorDocumentId", + "revision", + "assetId", + "specIds", + "association", + "sourceItemId", + "kind", + "overlayId" + ], + "title": "TimelineTextImpactConsumer", + "type": "object" + }, "TimelineTextOverlay": { "additionalProperties": false, "properties": { diff --git a/src/contracts/generated.ts b/src/contracts/generated.ts index 95c31068a..7f72f53c2 100644 --- a/src/contracts/generated.ts +++ b/src/contracts/generated.ts @@ -598,7 +598,7 @@ export interface GenerationImpactReportInput extends ContractInput { readonly rootSpecIds: ReadonlyArray; readonly items: ReadonlyArray; readonly dependencies: ReadonlyArray; - readonly timelineConsumers: ReadonlyArray; + readonly timelineConsumers: ReadonlyArray; } export interface GenerationSpecBaseInput extends ProjectEntityInput { @@ -1400,6 +1400,11 @@ export interface TimelineClipInput extends ContractInput { readonly muted?: boolean; } +export interface TimelineClipImpactConsumerInput extends TimelineImpactConsumerBaseInput { + readonly kind?: "clip"; + readonly clipId: string; +} + export interface TimelineDataInput extends ContractInput { readonly fps: number; readonly width: number; @@ -1421,10 +1426,9 @@ export interface TimelineFontResourceInput extends ContractInput { readonly asset: AssetRefInput; } -export interface TimelineImpactConsumerInput extends ContractInput { +export interface TimelineImpactConsumerBaseInput extends ContractInput { readonly editorDocumentId: string; readonly revision: number; - readonly clipId: string; readonly assetId: string; readonly specIds: ReadonlyArray; readonly association: "asset" | "source" | "asset_and_source"; @@ -1506,6 +1510,13 @@ export interface TimelineTextBackgroundInput extends ContractInput { readonly padding: number; } +export interface TimelineTextImpactConsumerInput extends TimelineImpactConsumerBaseInput { + readonly association: "asset"; + readonly sourceItemId?: null; + readonly kind?: "text_overlay"; + readonly overlayId: string; +} + export interface TimelineTextOverlayInput extends ContractInput { readonly id: string; readonly start: number; @@ -1711,6 +1722,8 @@ export type ModelKindInput = "agent" | "image" | "video" | "audio" | "vision"; export type VideoModeInput = "first_frame" | "reference" | "continuation"; +export type TimelineImpactConsumerInput = TimelineClipImpactConsumerInput | TimelineTextImpactConsumerInput; + export interface ArtifactPublish extends Contract { readonly path: string; readonly name: string; @@ -2307,7 +2320,7 @@ export interface GenerationImpactReport extends Contract { readonly rootSpecIds: ReadonlyArray; readonly items: ReadonlyArray; readonly dependencies: ReadonlyArray; - readonly timelineConsumers: ReadonlyArray; + readonly timelineConsumers: ReadonlyArray; } export interface GenerationSpecBase extends ProjectEntity { @@ -3108,6 +3121,11 @@ export interface TimelineClip extends Contract { readonly muted: boolean; } +export interface TimelineClipImpactConsumer extends TimelineImpactConsumerBase { + readonly kind: "clip"; + readonly clipId: string; +} + export interface TimelineData extends Contract { readonly fps: number; readonly width: number; @@ -3129,10 +3147,9 @@ export interface TimelineFontResource extends Contract { readonly asset: AssetRef; } -export interface TimelineImpactConsumer extends Contract { +export interface TimelineImpactConsumerBase extends Contract { readonly editorDocumentId: string; readonly revision: number; - readonly clipId: string; readonly assetId: string; readonly specIds: ReadonlyArray; readonly association: "asset" | "source" | "asset_and_source"; @@ -3214,6 +3231,13 @@ export interface TimelineTextBackground extends Contract { readonly padding: number; } +export interface TimelineTextImpactConsumer extends TimelineImpactConsumerBase { + readonly association: "asset"; + readonly sourceItemId: null; + readonly kind: "text_overlay"; + readonly overlayId: string; +} + export interface TimelineTextOverlay extends Contract { readonly id: string; readonly start: number; @@ -3418,3 +3442,5 @@ export type RoleAction = "configure_generation" | "save_manual_text" | "upload_m export type ModelKind = "agent" | "image" | "video" | "audio" | "vision"; export type VideoMode = "first_frame" | "reference" | "continuation"; + +export type TimelineImpactConsumer = TimelineClipImpactConsumer | TimelineTextImpactConsumer; diff --git a/src/i18n/messages/en-US/generationImpact.ts b/src/i18n/messages/en-US/generationImpact.ts index f612c47af..c780a2893 100644 --- a/src/i18n/messages/en-US/generationImpact.ts +++ b/src/i18n/messages/en-US/generationImpact.ts @@ -21,6 +21,8 @@ export const generationImpact = { "generationImpact.dependency_unresolved": "A current dependency has incomplete evidence. Inspect its original objects and jobs.", "generationImpact.execution_basis_incomplete": "Additional adapter or guide inputs were recorded but cannot be reconstructed from this project.", "generationImpact.dependency_cycle": "This configuration is in or depends on a reference cycle; no execution order is inferred.", - "generationImpact.impact_scope_exceeded": "Impact analysis exceeds the supported node or reference limit.", + "generationImpact.impact_scope_exceeded": "Impact analysis exceeds the supported node, reference or retained-evidence limit.", + "generationImpact.clip": "Timeline media clip", + "generationImpact.text_overlay": "Timeline text overlay", "generationImpact.fallback": "Impact details are unavailable. Refresh the report or inspect the original job.", }; diff --git a/src/i18n/messages/zh-CN/generationImpact.ts b/src/i18n/messages/zh-CN/generationImpact.ts index 9d25e17d5..d57be76f7 100644 --- a/src/i18n/messages/zh-CN/generationImpact.ts +++ b/src/i18n/messages/zh-CN/generationImpact.ts @@ -21,6 +21,8 @@ export const generationImpact = { "generationImpact.dependency_unresolved": "当前依赖的依据不完整,请检查原始对象和任务。", "generationImpact.execution_basis_incomplete": "已记录额外适配器或引导输入,但无法从当前工程重建这些依据。", "generationImpact.dependency_cycle": "该配置处于参考环中或依赖参考环,报告不推断执行顺序。", - "generationImpact.impact_scope_exceeded": "依赖分析超出支持的节点或参考数量上限。", + "generationImpact.impact_scope_exceeded": "依赖分析超出支持的节点、参考或保留证据数量上限。", + "generationImpact.clip": "时间线媒体片段", + "generationImpact.text_overlay": "时间线文字叠加层", "generationImpact.fallback": "暂时无法解释该影响状态,请刷新报告或检查原任务。", }; diff --git a/tests/generationImpact.test.ts b/tests/generationImpact.test.ts index 1875a7bba..70d56210f 100644 --- a/tests/generationImpact.test.ts +++ b/tests/generationImpact.test.ts @@ -42,7 +42,7 @@ test("impact states, reasons and fallback switch languages without changing busi const codes = [...defs.GenerationImpactItem.properties.reuseState.enum, ...defs.GenerationImpactItem.properties.inputState.enum, ...defs.GenerationImpactItem.properties.relation.enum, - ...defs.ImpactReason.properties.code.enum, "impact_scope_exceeded"]; + ...defs.ImpactReason.properties.code.enum, "impact_scope_exceeded", "clip", "text_overlay"]; const localized: Record = {}; try { for (const locale of ["en-US", "zh-CN"] as const) { @@ -61,3 +61,22 @@ test("impact states, reasons and fallback switch languages without changing busi assert.notDeepEqual(localized["en-US"], localized["zh-CN"]); } finally { setActiveLocale("zh-CN"); } }); + +test("impact queries can request the supported larger node budget without serializing read controls", async () => { + const client = new CreationClient("00000000-0000-0000-0000-000000000001"); + const original = globalThis.fetch; + let body: Record = {}; + globalThis.fetch = async (_url, options) => { + body = JSON.parse(String(options?.body)); + assert.ok(options?.signal); + return Response.json({}); + }; + try { + await client.generationImpact(["00000000-0000-0000-0000-000000000100"], { + maxNodes: 10000, signal: new AbortController().signal, attempts: 1, + }); + assert.equal(body.maxNodes, 10000); + assert.equal(body.signal, undefined); + assert.equal(body.attempts, undefined); + } finally { globalThis.fetch = original; } +}); diff --git a/tests/test_generation_impact.py b/tests/test_generation_impact.py index 06a931ba0..a832498a2 100644 --- a/tests/test_generation_impact.py +++ b/tests/test_generation_impact.py @@ -426,3 +426,70 @@ def test_unknown_upstream_overrides_pending_independently_of_reference_order(rev assert item.inputState == 'equal' assert item.reuseState == 'unknown' assert any(reason.code == 'dependency_unresolved' and reason.objectId == uid(103) for reason in item.reasons) + + +def test_timeline_text_overlay_retains_generated_source_without_replacing_text(): + from opendirector.domain.creation.generation import TextGenerationSpec, freeze_input_snapshot + from test_creation_timeline_text import data as timeline_data + public = model('agent') + text_model = ModelSnapshot(modelConfigId=public.id, inputRules=public.inputRules, + **{key: getattr(public, key) for key in ('kind', 'modelId', 'url', 'protocol', 'connectionType', 'videoAdapter')}) + spec = TextGenerationSpec(**entity(100, kind='text', purpose='generation', modelConfigId=public.id)) + frozen = freeze_input_snapshot(spec, text_model, ()) + output, font = asset(350, 'text'), asset(351, 'file') + job = Job(**entity(450, inputSnapshot=frozen, inputFingerprint=frozen.fingerprint(), execution=dict(kind='text'), + status='succeeded', recovery='done', asset=asset_ref(output))) + result = ResultVersion(**entity(550, specId=spec.id, jobId=job.id, asset=job.asset, inputFingerprint=job.inputFingerprint)) + timeline = timeline_data() + timeline['fonts'][0]['asset'] = asset_ref(font) + timeline['overlays'][0].update(sourceAsset=asset_ref(output), text='Edited retained title') + state = ProjectSnapshot(project=dict(id=PROJECT, name='Text impact'), assets=[output, font], jobs=[job], results=[result], + generationSpecs=[spec.model_copy(update={'currentResultId': result.id})], + editorDocuments=[entity(800, kind='timeline', revision=3, data=timeline)]) + before = state.model_dump_json() + consumers = report(state, roots=(spec.id,), models={public.id: text_model}).timelineConsumers + assert len(consumers) == 1 + consumer = consumers[0] + assert (consumer.kind, consumer.overlayId, consumer.assetId, consumer.specIds, consumer.association) == ( + 'text_overlay', 'a', output.id, (spec.id,), 'asset') + assert consumer.editorDocumentId == uid(800) and consumer.revision == 3 + assert state.model_dump_json() == before + + +@pytest.mark.parametrize('status,recovery,cancellation', [ + ('failed', 'download', 'not_requested'), ('failed', 'local', 'not_requested'), + ('cancelled', 'remote', 'unknown'), ('cancelled', 'remote', 'requested'), +]) +def test_recoverable_jobs_keep_their_original_identity(status, recovery, cancellation): + state = graph() + original = state.jobs[1].model_copy(update=dict(id=uid(901), status=status, recovery=recovery, + asset=None, resumeAllowed=True, cancelRequested=cancellation != 'not_requested', + remoteCancellation=cancellation, externalTaskId='accepted-original-job')) + terminal = original.model_copy(update=dict(id=uid(902), recovery='retry', resumeAllowed=False, + remoteCancellation='confirmed' if cancellation != 'not_requested' else cancellation)) + state = state.model_copy(update={'jobs': (*state.jobs, original, terminal)}) + item = report(state).items[1] + assert item.activeJobIds == (original.id,) + assert item.reuseState == 'reusable' + + +@pytest.mark.parametrize('evidence', ['timeline', 'jobs', 'combined']) +def test_report_evidence_overflow_is_explicit_including_pending_job_ids(evidence): + from opendirector.domain.creation.validation import ContractError + state = graph(count=1, links=()) + data = state.model_dump() + if evidence in {'jobs', 'combined'}: + count = 10001 if evidence == 'combined' else 20001 + original = state.jobs[0] + data['jobs'] = [original, *(original.model_copy(update=dict(id=UUID(int=10000+i), status='running', + recovery='remote', externalTaskId=f'accepted-{i}', asset=None)) for i in range(count))] + if evidence in {'timeline', 'combined'}: + count = 10000 if evidence == 'combined' else 20001 + resource = dict(asset=asset_ref(state.assets[0]), title='Retained output') + data['editorDocuments'] = [entity(800, kind='timeline', data=dict(fps=24, width=16, height=16, + tracks=[dict(id='v', kind='visual', title='Shots', clips=[dict(id=str(i), resource=resource, + inPoint=0, outPoint=1) for i in range(count)])]))] + state = ProjectSnapshot.model_validate(data) + with pytest.raises(ContractError) as error: + report(state, roots=(uid(100),), max_nodes=1) + assert error.value.issue.code == 'impact_scope_exceeded' diff --git a/tests/test_generation_impact_queries.py b/tests/test_generation_impact_queries.py index 2569af514..5b16a0c60 100644 --- a/tests/test_generation_impact_queries.py +++ b/tests/test_generation_impact_queries.py @@ -308,3 +308,111 @@ def test_foreign_project_root_never_switches_or_opens_a_session(saved, tmp_path) CreationCanvas(store).query_snapshot(impact_query(pid, [foreign.id])) assert error.value.issue.code == 'missing_object' assert store.snapshot(pid) == before + + +def test_cached_capability_rules_are_shared_across_query_entries_without_probing(tmp_path, monkeypatch): + from test_request_capability_acceptance import image_runtime, submit + from test_tool_tasks import png, upload + project = new_project(tmp_path) + store, pid, session = project + runner, config, probe, queries, posts = image_runtime(project, 2) + source = upload(store, str(pid), session, 'source.png', png()) + request = command(project, config, references=[source]) + try: + assert submit('service', project, runner, probe, request)['status'] == 'accepted' + state = store.snapshot(pid) + assert state.jobs[0].inputSnapshot.model.inputRules.maxImages == 2 + spec_id = state.generationSpecs[0].id + query = impact_query(pid, [spec_id]) + api = TestClient(create_app(store.local, generation_provider=runner.provider, capability_probe=probe), + headers={'X-OpenDirector-Request': '1'}) + + def forbidden(*args, **kwargs): + raise AssertionError('Impact queries must only read the existing capability cache') + + monkeypatch.setattr(probe, 'query', forbidden) + monkeypatch.setattr(probe, 'query_many', forbidden) + http = api.post(f'/api/creation/projects/{pid}/queries', json=query.model_dump(mode='json')) + assert http.status_code == 200, http.text + agent = asyncio.run(AgentTools(store, runner, runner.configs).execute(pid, uuid4(), session, 'impact-cache', + 'query', dict(type='generation.impact', rootSpecIds=[str(spec_id)]), [], None)) + assert http.json() == agent + assert CreationCanvas(store, availability=runner.availability).query_snapshot(query).model_dump(mode='json') == agent + assert [(i['inputState'], i['reuseState']) for i in agent['items']] == [('equal', 'reusable')] + assert len(queries) == len(posts) == 1 + assert store.snapshot(pid) == state + finally: + probe.close() + + +@pytest.mark.parametrize('failure', ['limit', 'foreign_root']) +def test_agent_gateway_preserves_impact_error_codes(saved, tmp_path, failure): + from opendirector.agent.context import RunContext + from opendirector.agent.gateway import ToolGateway + (store, pid, session), configs, runner, _, specs, _ = saved + arguments = dict(type='generation.impact', rootSpecIds=[str(specs[0])]) + if failure == 'limit': + arguments['maxNodes'] = 1 + expected = 'impact_scope_exceeded' + else: + arguments['rootSpecIds'] = [str(uuid4())] + expected = 'missing_object' + run = RunContext(runtime='codex', project_id=pid, turn_id=uuid4(), session=session, + directory=tmp_path, config=None, messages=[], selected_skills=[]) + + async def query(): + gateway = ToolGateway(AgentTools(store, runner, configs), run) + try: + result = await gateway.call('impact-rejected', 'query', arguments) + assert result.error + assert result.value['code'] == expected + assert result.event('query')['code'] == expected + finally: + await gateway.close() + + asyncio.run(query()) + + +@pytest.mark.parametrize('entry', ['service', 'http', 'agent']) +def test_impact_reuses_controlled_file_verification_and_detects_replacements(saved, monkeypatch, entry): + from opendirector.application import creation_assets + from test_tool_tasks import png + (store, pid, session), configs, runner, provider, specs, _ = saved + query = impact_query(pid, [specs[1]]) + canvas = CreationCanvas(store) + api = TestClient(create_app(store.local, generation_provider=provider), headers={'X-OpenDirector-Request': '1'}) + agent = AgentTools(store, runner, configs) + calls = [] + original = creation_assets.stream_identity + + def identity(stream): + calls.append(stream) + return original(stream) + + monkeypatch.setattr(creation_assets, 'stream_identity', identity) + + def read(): + if entry == 'service': + return canvas.query_snapshot(query).model_dump(mode='json') + if entry == 'http': + response = api.post(f'/api/creation/projects/{pid}/queries', json=query.model_dump(mode='json')) + assert response.status_code == 200, response.text + return response.json() + return asyncio.run(agent.execute(pid, uuid4(), session, 'impact-files', 'query', + dict(type='generation.impact', rootSpecIds=[str(specs[1])]), [], None)) + + assert all(item['reuseState'] == 'reusable' for item in read()['items']) + assert len(calls) == 4 + assert all(item['reuseState'] == 'reusable' for item in read()['items']) + assert len(calls) == 4 # unchanged file signatures reuse the safe reader's cache + state = store.snapshot(pid) + adopted = next(r for r in state.results if r.specId == specs[3]) + with store.local.transaction() as db: + directory, _ = store._find(db, pid) + output = directory / 'assets' / str(adopted.asset.assetId) + output.write_bytes(png(color='black')) + assert next(i for i in read()['items'] if i['specId'] == str(specs[3]))['reuseState'] == 'unavailable' + assert len(calls) == 5 + output.unlink() + assert next(i for i in read()['items'] if i['specId'] == str(specs[3]))['reuseState'] == 'unavailable' + assert store.snapshot(pid) == state From c5244a3ccc2e72496dffa228bffb08c313042b7e Mon Sep 17 00:00:00 2001 From: qingpeng Date: Mon, 23 Nov 2026 17:05:43 -0800 Subject: [PATCH 6/8] [docs] generation: record final impact validation evidence ## summary Record the tested source revision, complete local suite results, environment skips, independent review fixes and reproducible commands. Preserve the initial runtime-check failure and subsequent passing runs. ## validation Documentation links and static hooks passed. Refs: #355 --- .../generation-impact-validation.md | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/docs/development/generation-impact-validation.md b/docs/development/generation-impact-validation.md index 299a57711..4672d5179 100644 --- a/docs/development/generation-impact-validation.md +++ b/docs/development/generation-impact-validation.md @@ -66,3 +66,31 @@ npm run build The Python scenario uses real small PNG files, real command acceptance, immutable Job inputs, candidate generation, result adoption, pinning, timeline creation and a fresh project service after reopen. Only model execution is doubled. It verifies query equality across HTTP/Agent/CLI, file and project immutability, one project/catalog read, unavailable output files, foreign-project roots, limits, cycles and a 1,200-node graph. Frontend tests switch the active locale through English and Chinese for all declared report codes and verify typed read behavior while a newer project snapshot arrives. No live GPU/commercial provider was called. The workbench UI, native visual Harness matrix, browser export and remote continuation caches are separate acceptance scopes; they are not proven by these fixtures. + +### Recorded final checks, 2026-11-23 + +Code under test: `b00b780e9a6260b2169ec27206c3985519e4740d`, on macOS with Python 3.12.10, pytest 9.2.0 and Node 24.22.1. The full run started while that commit finalized, so its profile header records parent `81b9643f`. The reviewed staged diff and the final commit delta have the same SHA-256, `569705ca00960a4fb8c82fb5b823a723d2cc2db4f658ca7b30aa1f1b45fcaa6d`; source files did not change during this run. + +| Check | Observed result | +| --- | --- | +| Complete CPU suite with `OPENDIRECTOR_REAL_CLI=1` | 2,960 passed, 111 skipped, 1 dependency deprecation warning; 497.79 seconds | +| Complete layer inventory audit | 3,071 collected, 152/152 required representatives passed, 18 capabilities | +| Impact domain and query cases within that run | 61 passed | +| Actual bundled OpenCode binary with a test model gateway, within that run | 7 passed, 2 Windows-specific cases skipped | +| Complete frontend suite | 962 passed | +| Locale check | 3,352 keys, 0 problems | +| Type checking and production build | Passed; existing large-chunk advisory remains | +| Contract generation, import boundaries and branch static hooks | Passed; 4 import contracts kept | +| Browser locale and manifest inventories | Passed; these checks do not execute browser journeys | + +The 111 skips cover unavailable/opt-in native Harness executions and Windows-specific behavior on macOS. The first full run, before review fixes, had one failure: `test_rejects_removed_runtime_and_invalid_selection_before_acceptance` returned 503 during the default runtime check instead of 409. Its isolated repeat passed, and the final complete run passed it in 7.94 seconds. Runtime code was not changed to hide this observation. An intermediate run was interrupted to finish a generated TypeScript input-type correction and is not counted as successful validation. + +To repeat the full execution and its inventory check after environment setup: + +```bash +OPENDIRECTOR_REAL_CLI=1 PYTHONPATH=packages/core/src:apps/api/src:tests .venv/bin/python -m pytest tests -q -ra -m cpu --ci-profile=test-results/impact-python.json +.venv/bin/python scripts/ci/check_test_layers.py --profile test-results/impact-python.json --require-executed +npm test +``` + +One independent review identified seven important gaps: shared capability observations, text overlay consumers, recoverable Job identities, the browser node budget, structured Agent errors, a retained-evidence budget, and safe verification-cache reuse. Each was covered by a failing regression before its correction; the final suite above includes the corrected cases. Review and the first full test run ran concurrently; the complete suite was rerun after fixes. No second review was used as a substitute for regression tests. The material-node source display detail described above remains deferred. From 79e25cc45d7a00b332c0220d19e0019ea3638ed2 Mon Sep 17 00:00:00 2001 From: qingpeng Date: Mon, 23 Nov 2026 17:16:32 -0800 Subject: [PATCH 7/8] [bugfix] generation: retain material sources in timeline impact ## summary - Preserve the connected material node's sourceItemId in timeline consumers without adding a generation dependency or source association. - Cover both source roles, retained B1 after B2 adoption, unconnected clips, dependency identities and project immutability in regression. - Record the correction and distinguish its focused validation from the earlier complete-suite evidence. ## validation - Impact, shared-query and creation-contract tests: 141 passed. - Frontend impact and creation-client tests: 34 passed. - Generated contracts, all four import boundaries and static hooks passed. - i18n check: 3352 keys, 0 problems. Refs #355 --- .../generation-impact-validation.md | 10 ++++++-- .../application/creation_impact.py | 2 +- tests/test_generation_impact.py | 23 ++++++++++++++----- 3 files changed, 26 insertions(+), 9 deletions(-) diff --git a/docs/development/generation-impact-validation.md b/docs/development/generation-impact-validation.md index 4672d5179..6346ae572 100644 --- a/docs/development/generation-impact-validation.md +++ b/docs/development/generation-impact-validation.md @@ -48,7 +48,7 @@ HTTP and Agent queries read the generation service's existing capability observa Direct application callers should pass their owning generation service's `availability` and shared `assets` when constructing `CreationCanvas`. Without an injected capability service, the standalone reader has only local configuration rules, not another process's transient observations. -One display detail remains deferred: if a clip is explicitly connected through an ordinary material node containing a related result, the report includes its exact asset usage but omits that material node's `sourceItemId`. This does not remove the consumer or imply a live generation dependency. +If a clip is explicitly connected through an ordinary material node containing a related result, the report retains that node's `sourceItemId` alongside its exact asset usage. Its `association` remains `asset`: the source identity records the document connection without creating a live generation dependency. Clips without a source connection retain a null `sourceItemId`. ## Reproducible validation @@ -93,4 +93,10 @@ OPENDIRECTOR_REAL_CLI=1 PYTHONPATH=packages/core/src:apps/api/src:tests .venv/bi npm test ``` -One independent review identified seven important gaps: shared capability observations, text overlay consumers, recoverable Job identities, the browser node budget, structured Agent errors, a retained-evidence budget, and safe verification-cache reuse. Each was covered by a failing regression before its correction; the final suite above includes the corrected cases. Review and the first full test run ran concurrently; the complete suite was rerun after fixes. No second review was used as a substitute for regression tests. The material-node source display detail described above remains deferred. +One independent review identified seven important gaps: shared capability observations, text overlay consumers, recoverable Job identities, the browser node budget, structured Agent errors, a retained-evidence budget, and safe verification-cache reuse. Each was covered by a failing regression before its correction; the final suite above includes the corrected cases. Review and the first full test run ran concurrently; the complete suite was rerun after fixes. No second review was used as a substitute for regression tests. + +### Material source identity follow-up, 2026-11-23 + +The material-node regression initially failed because `sourceItemId` was null; the generation-node case passed. The correction retains the existing connected source identity independently of whether that source follows a generation spec. The regression verifies the retained B1 asset after B2 adoption, both source roles, a clip without a connection, the unchanged A → B → C dependency graph and an unchanged project snapshot. + +After this correction, `tests/test_generation_impact.py`, `tests/test_generation_impact_queries.py` and `tests/test_creation_contracts.py` passed together: 141 cases, with the same dependency deprecation warning. The frontend impact/client tests passed 34 cases; generated contracts and all four import boundaries passed. These focused checks cover the follow-up; the complete CPU/frontend counts above belong to the earlier recorded revision. diff --git a/packages/core/src/opendirector/application/creation_impact.py b/packages/core/src/opendirector/application/creation_impact.py index 6374713b2..14842fa90 100644 --- a/packages/core/src/opendirector/application/creation_impact.py +++ b/packages/core/src/opendirector/application/creation_impact.py @@ -277,7 +277,7 @@ def append(consumer): append(TimelineClipImpactConsumer(editorDocumentId=document.id, revision=document.revision, clipId=clip.id, assetId=clip.resource.asset.assetId, specIds=tuple(sorted(asset_specs | source_specs)), association='asset_and_source' if asset_specs and source_specs else 'asset' if asset_specs else 'source', - sourceItemId=source.id if source_specs else None)) + sourceItemId=source.id if source is not None else None)) for overlay in document.data.overlays: if overlay.sourceAsset is None: continue diff --git a/tests/test_generation_impact.py b/tests/test_generation_impact.py index a832498a2..0350ee9cc 100644 --- a/tests/test_generation_impact.py +++ b/tests/test_generation_impact.py @@ -305,20 +305,31 @@ def test_active_and_unknown_jobs_do_not_create_retry_actions(): assert not {'action', 'submit', 'resume', 'retry'} & set(item.model_dump()) -def test_timeline_consumers_are_reported_without_mutation(): +@pytest.mark.parametrize('source_role', ['generation', 'material']) +def test_timeline_consumers_are_reported_without_mutation(source_role): state = graph() resources = [dict(asset=asset_ref(state.assets[i]), title=f'Clip {i}') for i in (1, 2, 3)] data = state.model_dump() + source_id = uid(201) + if source_role == 'material': + source_id = uid(810) + data['canvasItems'] = [*state.canvasItems, entity(810, kind='image', + binding=dict(role='material', objectRef=asset_ref(state.assets[1])))] data['editorDocuments'] = [entity(800, kind='timeline', revision=3, - inputConnections=[dict(id=uid(801), sourceId=uid(201), slotId='b', asset=asset_ref(state.assets[1]))], + inputConnections=[dict(id=uid(801), sourceId=source_id, slotId='b', asset=asset_ref(state.assets[1]))], data=dict(fps=24, width=128, height=128, tracks=[dict(id='v', kind='visual', title='Shots', clips=[ dict(id=key, resource=res, inPoint=0, outPoint=1) for key, res in zip(('b', 'c', 'd'), resources)])]))] state = new_result(ProjectSnapshot.model_validate(data), 1) # timeline retains B1 before = state.model_dump_json() - consumers = report(state).timelineConsumers - assert [(c.clipId, c.association, c.assetId, c.specIds, c.revision) for c in consumers] == [ - ('b', 'asset_and_source', uid(301), (uid(101),), 3), - ('c', 'asset', uid(302), (uid(102),), 3)] + value = report(state) + association = 'asset_and_source' if source_role == 'generation' else 'asset' + assert [(c.clipId, c.association, c.assetId, c.specIds, c.revision, c.sourceItemId) + for c in value.timelineConsumers] == [ + ('b', association, uid(301), (uid(101),), 3, source_id), + ('c', 'asset', uid(302), (uid(102),), 3, None)] + # Retained material provenance does not introduce another generation edge. + assert [(e.sourceSpecId, e.targetSpecId) for e in value.dependencies] == [ + (uid(100), uid(101)), (uid(101), uid(102))] assert state.model_dump_json() == before From 65082d7f8d179033344f0312ac6033970ecf6278 Mon Sep 17 00:00:00 2001 From: qingpeng Date: Mon, 23 Nov 2026 17:34:10 -0800 Subject: [PATCH 8/8] [refactor] generation: clarify impact evidence and catalog errors ## summary - Document independent model reads and candidate timeline usage in the report contract and bilingual guide without changing wire structure. - Centralize impact error copy while preserving existing error codes, generic translations and HTTP statuses; align the bilingual checklist. - Cover candidate usage without adoption and missing-object responses in both languages, and record the validation scope. ## validation - Impact, query, creation-contract and localization tests: 150 passed. - Frontend impact/client tests: 34 passed. - Contracts, import boundaries, i18n, build and static checks passed. Refs #355 --- apps/api/src/opendirector_api/localization.py | 9 ++--- .../generation-impact-validation.md | 12 +++++++ docs/development/i18n.md | 4 ++- docs/guides/cli.md | 8 +++++ .../application/creation_impact.py | 18 +++++----- .../opendirector/domain/creation/impact.py | 12 +++---- .../domain/creation/impact_messages.py | 13 +++++++ src/contracts/creation.schema.json | 36 +++++++++---------- tests/test_generation_impact.py | 17 +++++++++ tests/test_generation_impact_queries.py | 3 ++ 10 files changed, 95 insertions(+), 37 deletions(-) create mode 100644 packages/core/src/opendirector/domain/creation/impact_messages.py diff --git a/apps/api/src/opendirector_api/localization.py b/apps/api/src/opendirector_api/localization.py index fa16ca639..08ee1dfe0 100644 --- a/apps/api/src/opendirector_api/localization.py +++ b/apps/api/src/opendirector_api/localization.py @@ -1,8 +1,8 @@ """Localized user-facing errors for the local HTTP boundary. -Domain code keeps its Chinese copy for CLI and Agent traces. The HTTP boundary -chooses an English message from the stable error code when the caller asks for -English, so a missing translation never leaks Chinese into an English UI. +Feature catalogs supply new display copy; older errors still carry their own +Chinese fallback for CLI and Agent traces. The HTTP boundary chooses English +from the stable error code when requested, with generic-code fallbacks. """ import re @@ -12,11 +12,12 @@ from opendirector.domain.timeline_errors import timeline_error_message from opendirector.domain.creation.commands import CommandReceipt +from opendirector.domain.creation.impact_messages import IMPACT_ERROR_EN from opendirector.domain.capabilities import Capability from opendirector.domain.capability_messages import english_capability_message, missing_tool_model_message ENGLISH_BY_CODE = { - 'impact_scope_exceeded': 'Generation impact exceeds the node, reference or retained-evidence limit. Increase maxNodes only for a node-budget error; other limits require a smaller project scope.', + **IMPACT_ERROR_EN, "desktop_auth_required": "The desktop connection has expired. Reopen the application.", 'image_quality_unsupported': 'This model does not support the selected image quality. Choose Auto or select another model.', 'bigmodel_video_model': 'The BigModel video protocol supports CogVideoX-3 only.', diff --git a/docs/development/generation-impact-validation.md b/docs/development/generation-impact-validation.md index 6346ae572..710e9a4ca 100644 --- a/docs/development/generation-impact-validation.md +++ b/docs/development/generation-impact-validation.md @@ -21,6 +21,10 @@ Use `generation.impact` through `POST /api/creation/projects/{projectId}/queries - Show both `inputState` and `reuseState`, the reasons and original `baselineJobId`/`activeJobIds`. Retain `projectVersion`, `eventCursor` and object revisions for context; they do not reserve a future edit. Any workbench action continues through existing commands with current versions, locks and authorization. - Reports cover all project generation configurations. `relation` is relative to the requested roots; `timelineConsumers` covers only those roots and their downstream configurations. Consumers are discriminated as `clip` with `clipId`, or `text_overlay` with `overlayId`. Fixed asset usage and source associations are review evidence, not automatic replacement instructions. Recoverable failures and unresolved cancellations retain their original `activeJobIds`. +`projectVersion` and `eventCursor` identify one authoritative project snapshot only. The model catalog is read under its own lock, and effective input rules also use independently read capability observations. These reads do not form one atomic project-and-model snapshot: configuration or observation changes during the query can affect the comparison without changing the reported project version. The report describes observed reuse evidence, not reserved inputs. A subsequent generation submission still resolves and validates its actual inputs through the existing acceptance path. + +Timeline asset associations include historical results and unadopted candidates when the timeline actually retains those assets. `association` describes how a usage relates to a generation spec, not whether its asset is currently adopted. Reuse comparison continues to use the successful Job behind `currentResultId`; including a candidate's timeline usage does not adopt it or add a live generation dependency. + ### Recorded request and response The [request](fixtures/generation-impact-request.json) and [response](fixtures/generation-impact-response.json) were captured from `test_reopenable_dependency_case_uses_real_commands_and_files` after editing B's prompt. These UUIDs belong to an isolated test project; substitute IDs from your own project to execute a query. The HTTP sample includes the envelope; the CLI parameter file contains just `rootSpecIds` and optional `maxNodes`. @@ -48,6 +52,8 @@ HTTP and Agent queries read the generation service's existing capability observa Direct application callers should pass their owning generation service's `availability` and shared `assets` when constructing `CreationCanvas`. Without an injected capability service, the standalone reader has only local configuration rules, not another process's transient observations. +Impact error copy is maintained in [impact_messages.py](../../packages/core/src/opendirector/domain/creation/impact_messages.py). Application guards reference the catalog while retaining their existing error codes. The HTTP boundary imports the dedicated `impact_scope_exceeded` translation and continues to use its shared translations for generic `invalid_input` and `missing_object` codes. This keeps unrelated errors' wording and HTTP status handling unchanged. + If a clip is explicitly connected through an ordinary material node containing a related result, the report retains that node's `sourceItemId` alongside its exact asset usage. Its `association` remains `asset`: the source identity records the document connection without creating a live generation dependency. Clips without a source connection retain a null `sourceItemId`. ## Reproducible validation @@ -100,3 +106,9 @@ One independent review identified seven important gaps: shared capability observ The material-node regression initially failed because `sourceItemId` was null; the generation-node case passed. The correction retains the existing connected source identity independently of whether that source follows a generation spec. The regression verifies the retained B1 asset after B2 adoption, both source roles, a clip without a connection, the unchanged A → B → C dependency graph and an unchanged project snapshot. After this correction, `tests/test_generation_impact.py`, `tests/test_generation_impact_queries.py` and `tests/test_creation_contracts.py` passed together: 141 cases, with the same dependency deprecation warning. The frontend impact/client tests passed 34 cases; generated contracts and all four import boundaries passed. These focused checks cover the follow-up; the complete CPU/frontend counts above belong to the earlier recorded revision. + +### Contract and message review follow-up, 2026-11-23 + +The follow-up to `79e25cc4` clarifies independent project/model/capability reads and the inclusion of actual historical/candidate timeline usages in contract descriptions and bilingual CLI guidance. Schema changes are descriptions only. It also moves impact error copy into a catalog while preserving stable codes, generic boundary translations and status handling. Graph validation and the deferred workbench integration are unchanged. + +The candidate-usage regression and expanded missing-object language assertions passed before the message extraction. After the changes, the impact, shared-query, creation-contract and localization modules passed together: 150 cases, with the existing dependency deprecation warning. Frontend impact/client tests passed 34 cases. Contract generation, all four import boundaries, i18n (3,352 keys, zero problems), type checking and the production build passed; the existing chunk-size advisory remains. These focused checks cover this follow-up and do not replace the earlier recorded full-suite evidence. diff --git a/docs/development/i18n.md b/docs/development/i18n.md index 4a98a148c..b164e1fde 100644 --- a/docs/development/i18n.md +++ b/docs/development/i18n.md @@ -58,7 +58,7 @@ src/i18n/ 1. 词条文件已在 `zh-CN` 与 `en-US` 成对创建,并在两个 `index.ts` 注册。 2. 界面文案全部通过 `useI18n()`、`useT()` 或 `tNow()` 取得;数组、状态机和校验结果返回 `MessageDescriptor`,不在组件内拼句子。 -3. 后端新增错误码或状态时保持 `code` 稳定,并在 [localization.py](../../apps/api/src/opendirector_api/localization.py) 的 `ENGLISH_BY_CODE` / `ENGLISH_BY_STATUS` 补齐英文;中文文案在抛出点,前端显示层映射同步更新。 +3. 后端新增或修改错误、状态文案时,保持 `code` 稳定,把文案集中到功能词条表,抛出点引用词条,不内嵌中英文句子。专有错误码同时提供中英文,并接入 [localization.py](../../apps/api/src/opendirector_api/localization.py) 的显示层查找;复用通用错误码时保留其已有统一译文,前端显示层映射同步更新。 4. 新增工具目录、模型简介、生成失败原因、任务状态或历史预览标签时,扩展「当前剩余」列出的显示层查找表,不直接把中文写进数据目录。 5. 更新下方审校表;新功能没有独立文件时,确认现有文件已经覆盖新增词条。 6. 运行 `npm run check:i18n`,再实际切换中英文走一遍新增流程;自动检查不覆盖硬编码英文,也不能证明英文界面没有中文泄漏。 @@ -70,6 +70,8 @@ src/i18n/ 前端校验与领域错误直接进入界面时,也必须走词条;新增错误应同时提供中英文。 +例如 [impact_messages.py](../../packages/core/src/opendirector/domain/creation/impact_messages.py) 集中保存依赖影响查询的默认中文文案和专有错误码英文译文;`invalid_input`、`missing_object` 继续复用边界层的通用英文译文。历史代码中仍有抛出点文案,这是待整理的现状,不是新代码继续内嵌文案的依据。整理时保留稳定错误码、HTTP 状态及其他功能的翻译语义。 + ## 检查 ```bash diff --git a/docs/guides/cli.md b/docs/guides/cli.md index 62026a6f9..19c5da165 100644 --- a/docs/guides/cli.md +++ b/docs/guides/cli.md @@ -80,6 +80,14 @@ For A→B→C and independent D, editing only B's prompt makes B `stale`, C `pen The report includes `projectVersion`, `eventCursor`, spec revisions, `baselineJobId`, `activeJobIds`, stable reason codes and controlled field paths. `activeJobIds` includes recoverable failures and unresolved remote cancellations. Timeline consumers cover media clips (`kind=clip`, `clipId`) and text sources (`kind=text_overlay`, `overlayId`) for the requested roots and their downstream configurations, distinguishing fixed assets from source associations; they do not authorize replacement. State may change after a query. Re-read affected objects and check current versions and locks before any modification. Inspect the original Job for active or uncertain submissions instead of creating another attempt from this report. +`projectVersion` 和 `eventCursor` 仅标识工程快照。模型配置与能力观测独立读取,不与工程组成同一时点的原子快照;它们在查询期间变化时,比较依据可能变化而工程版本不变。报告不预留执行输入,正式提交生成仍会重新解析并校验实际输入。 + +`projectVersion` and `eventCursor` identify only the project snapshot. Model configuration and capability observations are read independently, without an atomic snapshot across all three. Changes during the query can affect the comparison without changing the project version. The report does not reserve execution inputs; generation submission still resolves and validates its actual inputs. + +时间线实际使用的历史结果和未采用候选也会列入使用点。`association` 表示素材或来源的关联依据,不表示采用状态;复用判断仍以 `currentResultId` 对应的成功 Job 为基线。列出候选素材使用点不会采用该候选,也不会新增生成依赖。 + +Timeline usages also include historical results and unadopted candidates when those assets are actually retained. `association` identifies the asset/source relationship, not adoption status. Reuse is still compared against the successful Job behind `currentResultId`; listing a candidate usage does not adopt it or create a generation dependency. + 每次最多 100 个不同根;检查工程全部生成配置,`maxNodes` 默认 2,000、最大 10,000,活动参考及展开依赖边最多 20,000;时间线使用点与原任务身份合计最多 20,000 条。超限返回 `impact_scope_exceeded`,不返回截断后看似完整的报告。缺少可重建的 guide、窗口或扩展 adapter 依据时保持未知。复用只针对已有素材,不保证重新生成确定性、创作质量、服务商健康或远端 latent/cache 命中。外部 ComfyUI 未登记的 graph/history/cache 仍需单独核对。 Queries accept up to 100 distinct roots and inspect all generation configurations in the project. `maxNodes` defaults to 2,000 with a maximum of 10,000; active references and expanded edges are limited to 20,000. Timeline consumers and retained Job IDs share a separate combined limit of 20,000 entries. Overflow returns `impact_scope_exceeded`, not a truncated report. Missing reconstructable guide, window or adapter-extension evidence remains unknown. Reuse concerns existing assets, not deterministic regeneration, creative quality, provider health or remote latent/cache hits. Unregistered external ComfyUI graphs, history and caches require separate checks. diff --git a/packages/core/src/opendirector/application/creation_impact.py b/packages/core/src/opendirector/application/creation_impact.py index 14842fa90..bf38d5d9c 100644 --- a/packages/core/src/opendirector/application/creation_impact.py +++ b/packages/core/src/opendirector/application/creation_impact.py @@ -10,6 +10,7 @@ GenerationImpactItem, GenerationImpactReport, ImpactDependency, ImpactReason, TimelineClipImpactConsumer, TimelineTextImpactConsumer, ) +from opendirector.domain.creation.impact_messages import IMPACT_ERROR_ZH from opendirector.domain.creation.models import ModelSnapshot from opendirector.domain.creation.project import ProjectSnapshot from opendirector.domain.creation.validation import ContractError @@ -33,8 +34,9 @@ def query(self, query: GenerationImpactQuery) -> GenerationImpactReport: configs = gateway().models(self.projects.local.repository) availability = self.availability or ModelAvailability(configs) models = {} - # One locked catalog read. Effective rules use only cached/local facts; - # never prepare/refresh a capability probe for an impact query. + # The project, catalog and capability observations have independent read + # boundaries. Report versions identify only the project snapshot; this + # query neither reserves model rules nor refreshes capability probes. needed = {spec.modelConfigId for spec in snapshot.generationSpecs} for public, private in configs.catalog_snapshot(): identity = UUID(public['id']) @@ -85,7 +87,7 @@ def build_generation_dependencies( documentId=value.documentVersion.id if value and value.documentVersion else None, inputConfirmed=value is not None)) if len(edges) > MAX_IMPACT_EDGES: - raise ContractError('impact_scope_exceeded', '依赖分析超出节点或参考数量上限。') + raise ContractError('impact_scope_exceeded', IMPACT_ERROR_ZH['impact_scope_exceeded']) return tuple(edges) @@ -116,7 +118,7 @@ def __init__(self, snapshot): or job.resumeAllowed or job.remoteCancellation in {'requested', 'unknown'}): self.active_job_count += 1 if self.active_job_count > GENERATION_IMPACT_EVIDENCE_LIMIT: - raise ContractError('impact_scope_exceeded', '依赖分析超出节点、参考或证据数量上限。') + raise ContractError('impact_scope_exceeded', IMPACT_ERROR_ZH['impact_scope_exceeded']) self.active_jobs.setdefault(job.inputSnapshot.spec.id, []).append(job.id) def resolution_view(self, spec): @@ -258,7 +260,7 @@ def _timeline_consumers(index, related): def append(consumer): if len(consumers) + index.active_job_count >= GENERATION_IMPACT_EVIDENCE_LIMIT: - raise ContractError('impact_scope_exceeded', '依赖分析超出节点、参考或证据数量上限。') + raise ContractError('impact_scope_exceeded', IMPACT_ERROR_ZH['impact_scope_exceeded']) consumers.append(consumer) for document in index.snapshot.editorDocuments: @@ -300,12 +302,12 @@ def analyze_generation_impact(snapshot: ProjectSnapshot, *, root_spec_ids: tuple if (type(max_nodes) is not int or not 1 <= max_nodes <= 10000 or len(snapshot.generationSpecs) > max_nodes or sum(ref.active for ref in snapshot.references) > MAX_IMPACT_EDGES): - raise ContractError('impact_scope_exceeded', '依赖分析超出节点或参考数量上限。') + raise ContractError('impact_scope_exceeded', IMPACT_ERROR_ZH['impact_scope_exceeded']) index = _SnapshotIndex(snapshot) if not root_spec_ids or len(root_spec_ids) > 100 or len(set(root_spec_ids)) != len(root_spec_ids): - raise ContractError('invalid_input', '请提供 1 至 100 个不同的生成配置。') + raise ContractError('invalid_input', IMPACT_ERROR_ZH['invalid_input']) if any(key not in index.specs for key in root_spec_ids): - raise ContractError('missing_object', '生成配置不在当前工程中。') + raise ContractError('missing_object', IMPACT_ERROR_ZH['missing_object']) availability = {} def available(key): diff --git a/packages/core/src/opendirector/domain/creation/impact.py b/packages/core/src/opendirector/domain/creation/impact.py index 8900516b0..ff14f1b57 100644 --- a/packages/core/src/opendirector/domain/creation/impact.py +++ b/packages/core/src/opendirector/domain/creation/impact.py @@ -33,9 +33,9 @@ class ImpactDependency(Contract): class TimelineImpactConsumerBase(Contract): editorDocumentId: UUID = Field(description='Current timeline document identity.') revision: Revision = Field(description='Timeline document revision read by this report.') - assetId: UUID = Field(description='Asset currently retained in this timeline usage; the query never replaces it.') + assetId: UUID = Field(description='Asset currently retained in this timeline usage, including historical results and unadopted candidates; the query never replaces it.') specIds: tuple[UUID, ...] = Field(description='Related generation specs from exact result or source identities.') - association: Literal['asset', 'source', 'asset_and_source'] = Field(description='Exact retained result asset, explicit input connection, or both; none implies automatic replacement.') + association: Literal['asset', 'source', 'asset_and_source'] = Field(description='Basis of association with related specs: exact retained result asset, explicit generation-source connection, or both. Not adoption status or permission to replace content.') sourceItemId: UUID | None = Field(default=None, description='Source item from the document input connection, when relevant.') @@ -47,7 +47,7 @@ class TimelineClipImpactConsumer(TimelineImpactConsumerBase): class TimelineTextImpactConsumer(TimelineImpactConsumerBase): kind: Literal['text_overlay'] = Field(default='text_overlay', description='Retained text overlay source usage.') overlayId: Identifier = Field(description='Retained timeline text overlay identity.') - association: Literal['asset'] = Field(description='Exact frozen source text asset; subsequent source edits do not replace overlay text.') + association: Literal['asset'] = Field(description='Exact frozen source text asset, including historical results and unadopted candidates; not adoption status. Subsequent source edits do not replace overlay text.') sourceItemId: None = Field(default=None, description='Text overlays retain source assets without a live source connection.') @@ -60,7 +60,7 @@ class GenerationImpactItem(Contract): currentResultId: UUID | None = Field(default=None, description='Currently adopted result, never an unadopted candidate.') baselineJobId: UUID | None = Field(default=None, description='Successful job owning the adopted result.') baselineInputFingerprint: Digest | None = Field(default=None, description='Verified adopted job input fingerprint.') - currentInputFingerprint: Digest | None = Field(default=None, description='Reconstructed current input fingerprint using the acceptance rules.') + currentInputFingerprint: Digest | None = Field(default=None, description='Reconstructed inputs from the project snapshot and independently read model rules/capability observations; not an atomic project-and-model snapshot or an execution reservation.') inputState: Literal['equal', 'changed', 'unresolved', 'no_baseline'] = Field(description='Current effective inputs compared with the adopted job.') reuseState: Literal['reusable', 'stale', 'pending_upstream', 'unavailable', 'unknown', 'no_result'] = Field(description='Result reuse evidence, independent of creative approval and remote cache availability.') relation: Literal['root', 'downstream', 'independent'] = Field(description='Relationship to requested roots, not an invalidation decision.') @@ -72,8 +72,8 @@ class GenerationImpactItem(Contract): class GenerationImpactReport(Contract): analysisVersion: Literal[1] = Field(default=1, description='Impact interpretation version.') - projectVersion: ObjectVersion = Field(description='Single authoritative project snapshot version used for this read, not authorization for later writes.') - eventCursor: int = Field(strict=True, ge=0, description='Event cursor from the same project snapshot.') + projectVersion: ObjectVersion = Field(description='Version of the authoritative project snapshot only. Model configuration and capability observations are read independently; this report does not authorize later writes or reserve execution inputs.') + eventCursor: int = Field(strict=True, ge=0, description='Event cursor from the same project snapshot as projectVersion; excludes model configuration and capability observation changes.') rootSpecIds: tuple[UUID, ...] = Field(min_length=1, max_length=100, description='Unique requested roots in this project.') items: tuple[GenerationImpactItem, ...] = Field(max_length=10000, description='All project generation configurations, including independent branches.') dependencies: tuple[ImpactDependency, ...] = Field(max_length=20000, description='Current effective follow bindings; scope overflow fails instead of truncating.') diff --git a/packages/core/src/opendirector/domain/creation/impact_messages.py b/packages/core/src/opendirector/domain/creation/impact_messages.py new file mode 100644 index 000000000..3f8f92c1b --- /dev/null +++ b/packages/core/src/opendirector/domain/creation/impact_messages.py @@ -0,0 +1,13 @@ +"""Impact-query display copy; error codes keep their existing business meaning.""" + +IMPACT_ERROR_ZH = { + 'impact_scope_exceeded': '依赖分析超出节点、参考或证据数量上限。', + 'invalid_input': '请提供 1 至 100 个不同的生成配置。', + 'missing_object': '生成配置不在当前工程中。', +} + +# Generic invalid_input and missing_object codes retain the shared boundary +# translations. Only the feature-specific code adds an English catalog entry. +IMPACT_ERROR_EN = { + 'impact_scope_exceeded': 'Generation impact exceeds the node, reference or retained-evidence limit. Increase maxNodes only for a node-budget error; other limits require a smaller project scope.', +} diff --git a/src/contracts/creation.schema.json b/src/contracts/creation.schema.json index a739cd81a..61237bcb3 100644 --- a/src/contracts/creation.schema.json +++ b/src/contracts/creation.schema.json @@ -5706,7 +5706,7 @@ } ], "default": null, - "description": "Reconstructed current input fingerprint using the acceptance rules.", + "description": "Reconstructed inputs from the project snapshot and independently read model rules/capability observations; not an atomic project-and-model snapshot or an execution reservation.", "title": "Currentinputfingerprint" }, "inputState": { @@ -5846,10 +5846,10 @@ }, "projectVersion": { "$ref": "#/$defs/ObjectVersion", - "description": "Single authoritative project snapshot version used for this read, not authorization for later writes." + "description": "Version of the authoritative project snapshot only. Model configuration and capability observations are read independently; this report does not authorize later writes or reserve execution inputs." }, "eventCursor": { - "description": "Event cursor from the same project snapshot.", + "description": "Event cursor from the same project snapshot as projectVersion; excludes model configuration and capability observation changes.", "minimum": 0, "title": "Eventcursor", "type": "integer" @@ -13620,7 +13620,7 @@ "type": "integer" }, "assetId": { - "description": "Asset currently retained in this timeline usage; the query never replaces it.", + "description": "Asset currently retained in this timeline usage, including historical results and unadopted candidates; the query never replaces it.", "format": "uuid", "title": "Assetid", "type": "string" @@ -13635,7 +13635,7 @@ "type": "array" }, "association": { - "description": "Exact retained result asset, explicit input connection, or both; none implies automatic replacement.", + "description": "Basis of association with related specs: exact retained result asset, explicit generation-source connection, or both. Not adoption status or permission to replace content.", "enum": [ "asset", "source", @@ -13858,7 +13858,7 @@ "type": "integer" }, "assetId": { - "description": "Asset currently retained in this timeline usage; the query never replaces it.", + "description": "Asset currently retained in this timeline usage, including historical results and unadopted candidates; the query never replaces it.", "format": "uuid", "title": "Assetid", "type": "string" @@ -13873,7 +13873,7 @@ "type": "array" }, "association": { - "description": "Exact retained result asset, explicit input connection, or both; none implies automatic replacement.", + "description": "Basis of association with related specs: exact retained result asset, explicit generation-source connection, or both. Not adoption status or permission to replace content.", "enum": [ "asset", "source", @@ -14435,7 +14435,7 @@ "type": "integer" }, "assetId": { - "description": "Asset currently retained in this timeline usage; the query never replaces it.", + "description": "Asset currently retained in this timeline usage, including historical results and unadopted candidates; the query never replaces it.", "format": "uuid", "title": "Assetid", "type": "string" @@ -14451,7 +14451,7 @@ }, "association": { "const": "asset", - "description": "Exact frozen source text asset; subsequent source edits do not replace overlay text.", + "description": "Exact frozen source text asset, including historical results and unadopted candidates; not adoption status. Subsequent source edits do not replace overlay text.", "title": "Association", "type": "string" }, @@ -22530,7 +22530,7 @@ } ], "default": null, - "description": "Reconstructed current input fingerprint using the acceptance rules.", + "description": "Reconstructed inputs from the project snapshot and independently read model rules/capability observations; not an atomic project-and-model snapshot or an execution reservation.", "title": "Currentinputfingerprint" }, "inputState": { @@ -22678,10 +22678,10 @@ }, "projectVersion": { "$ref": "#/$defs/ObjectVersion", - "description": "Single authoritative project snapshot version used for this read, not authorization for later writes." + "description": "Version of the authoritative project snapshot only. Model configuration and capability observations are read independently; this report does not authorize later writes or reserve execution inputs." }, "eventCursor": { - "description": "Event cursor from the same project snapshot.", + "description": "Event cursor from the same project snapshot as projectVersion; excludes model configuration and capability observation changes.", "minimum": 0, "title": "Eventcursor", "type": "integer" @@ -30762,7 +30762,7 @@ "type": "integer" }, "assetId": { - "description": "Asset currently retained in this timeline usage; the query never replaces it.", + "description": "Asset currently retained in this timeline usage, including historical results and unadopted candidates; the query never replaces it.", "format": "uuid", "title": "Assetid", "type": "string" @@ -30777,7 +30777,7 @@ "type": "array" }, "association": { - "description": "Exact retained result asset, explicit input connection, or both; none implies automatic replacement.", + "description": "Basis of association with related specs: exact retained result asset, explicit generation-source connection, or both. Not adoption status or permission to replace content.", "enum": [ "asset", "source", @@ -31006,7 +31006,7 @@ "type": "integer" }, "assetId": { - "description": "Asset currently retained in this timeline usage; the query never replaces it.", + "description": "Asset currently retained in this timeline usage, including historical results and unadopted candidates; the query never replaces it.", "format": "uuid", "title": "Assetid", "type": "string" @@ -31021,7 +31021,7 @@ "type": "array" }, "association": { - "description": "Exact retained result asset, explicit input connection, or both; none implies automatic replacement.", + "description": "Basis of association with related specs: exact retained result asset, explicit generation-source connection, or both. Not adoption status or permission to replace content.", "enum": [ "asset", "source", @@ -31599,7 +31599,7 @@ "type": "integer" }, "assetId": { - "description": "Asset currently retained in this timeline usage; the query never replaces it.", + "description": "Asset currently retained in this timeline usage, including historical results and unadopted candidates; the query never replaces it.", "format": "uuid", "title": "Assetid", "type": "string" @@ -31615,7 +31615,7 @@ }, "association": { "const": "asset", - "description": "Exact frozen source text asset; subsequent source edits do not replace overlay text.", + "description": "Exact frozen source text asset, including historical results and unadopted candidates; not adoption status. Subsequent source edits do not replace overlay text.", "title": "Association", "type": "string" }, diff --git a/tests/test_generation_impact.py b/tests/test_generation_impact.py index 0350ee9cc..69f38953c 100644 --- a/tests/test_generation_impact.py +++ b/tests/test_generation_impact.py @@ -333,6 +333,23 @@ def test_timeline_consumers_are_reported_without_mutation(source_role): assert state.model_dump_json() == before +def test_timeline_candidate_usage_preserves_the_adopted_reuse_baseline(): + state = new_result(graph(), 1, adopt=False) + data = state.model_dump() + data['editorDocuments'] = [entity(800, kind='timeline', data=dict( + fps=24, width=128, height=128, tracks=[dict(id='v', kind='visual', title='Shots', clips=[dict( + id='candidate', resource=dict(asset=asset_ref(state.assets[-1]), title='Candidate'), + inPoint=0, outPoint=1)])]))] + state = ProjectSnapshot.model_validate(data) + before = state.model_dump_json() + value = report(state) + consumer, = value.timelineConsumers + assert (consumer.assetId, consumer.specIds, consumer.association) == (uid(1000), (uid(101),), 'asset') + assert (value.items[1].currentResultId, value.items[1].baselineJobId) == (uid(501), uid(401)) + assert all(item.reuseState == 'reusable' for item in value.items) + assert state.model_dump_json() == before + + def test_snapshot_normalization_matches_generation_acceptance(tmp_path): from generation_helpers import new_project, command from test_creation_generation_service import Provider diff --git a/tests/test_generation_impact_queries.py b/tests/test_generation_impact_queries.py index 5b16a0c60..7bd2184c8 100644 --- a/tests/test_generation_impact_queries.py +++ b/tests/test_generation_impact_queries.py @@ -172,6 +172,9 @@ def test_impact_errors_and_codes_are_locale_safe(saved, locale): for roots in ([uuid4()], [pid]): # foreign and wrong-kind identity response = api.post(f'/api/creation/projects/{pid}/queries', json=impact_query(pid, roots).model_dump(mode='json')) assert response.status_code == 404 and response.json()['code'] == 'missing_object' + message = response.json()['detail'] + assert ('当前工程' in message) if locale == 'zh-CN' else ( + 'no longer exists' in message and not any('\u4e00' <= c <= '\u9fff' for c in message)) valid = impact_query(pid, [specs[1]]).model_dump(mode='json') english = api.post(f'/api/creation/projects/{pid}/queries', json=valid, headers={'Accept-Language': 'en-US'}).json() chinese = api.post(f'/api/creation/projects/{pid}/queries', json=valid, headers={'Accept-Language': 'zh-CN'}).json()