agentic-development-framework 0.2.0__py3-none-any.whl → 0.4.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: agentic-development-framework
3
- Version: 0.2.0
3
+ Version: 0.4.0
4
4
  Summary: A local-first framework for agentic software development workflows.
5
5
  Project-URL: Homepage, https://github.com/Badsha-ugv/ide-agentic-development-framework
6
6
  Project-URL: Repository, https://github.com/Badsha-ugv/ide-agentic-development-framework
@@ -39,7 +39,7 @@ The project is being delivered incrementally. The current implementation provide
39
39
  installable package, strict configuration validation, structured logging, safe project
40
40
  initialization, immutable requirements versioning, SQLite workflow state, recovery checkpoints,
41
41
  lifecycle commands, structured stage execution contracts, artifact validation, approval history,
42
- and Codex/Antigravity project configuration.
42
+ Codex/Antigravity project configuration, and a browser-verified frontend-first delivery workflow.
43
43
 
44
44
  ## Requirements
45
45
 
@@ -74,6 +74,7 @@ adt --version
74
74
  adt init
75
75
  adt config validate path/to/config.yaml
76
76
  adt requirements ingest
77
+ adt requirements screenshots
77
78
  adt start
78
79
  adt status
79
80
  adt pause
@@ -137,6 +138,26 @@ clear unsupported-extraction status. Optional binary-format extractors are futur
137
138
 
138
139
  See `docs/REQUIREMENTS_MANAGEMENT.md` for the file contract and safety behavior.
139
140
 
141
+ Place PNG, JPG, JPEG, or WEBP design references anywhere below `requirements/screenshots/` and
142
+ run `adt requirements screenshots`. ADF recursively catalogs them, preserves immutable reference
143
+ revisions, records dimensions and contextual folder hints, and updates
144
+ `docs/ui-ux/screenshot-reference-analysis.md` without modifying originals. Requirements ingestion
145
+ also performs this synchronization.
146
+
147
+ ## Frontend-first visual workflow
148
+
149
+ The `ui_ux_design` stage now builds the complete production frontend—there is no disposable design
150
+ prototype. It accepts a Figma URL from requirements, recursively discovered screenshots, a generated
151
+ design direction, or a combination. Before implementation it verifies the chosen frontend stack,
152
+ package manager, runtime, dependencies, and production build. The result must be modern, accessible,
153
+ responsive, fully interactive, and visually faithful to supplied references without unapproved
154
+ deviations.
155
+
156
+ The following `design_review` stage reviews the actual frontend and always waits for explicit human
157
+ approval. Revisions update that production frontend. Backend implementation begins only afterward,
158
+ followed by frontend/backend API integration. See
159
+ [`docs/UI_UX_WORKFLOW.md`](docs/UI_UX_WORKFLOW.md).
160
+
140
161
  ## Runtime state and recovery
141
162
 
142
163
  Initialization creates `.agentic/database/agentic.db` as the transactional source of truth,
@@ -1,29 +1,30 @@
1
- agentic_framework/__init__.py,sha256=S1gT5jrk4C2azsQ87hh1jLDJOMm7h9XDrQPlAKJf-Z0,112
1
+ agentic_framework/__init__.py,sha256=UlBF83T1GV7xHAvkpjGWRWpNbaAS-43ahtY3PBmB1Ms,112
2
2
  agentic_framework/__main__.py,sha256=fHn8AFsz1H4xtmbMVsTaBxC9PNr96qqd8aocXjUsVuQ,140
3
- agentic_framework/cli.py,sha256=wypOrQWw8DAXiBUosuMNwoo0QizcrafYN26EPwwHcyU,15020
3
+ agentic_framework/cli.py,sha256=9n99mxysd0SdmPrlB9PJfYed56dGft6ovMBZxlJQiwA,15857
4
4
  agentic_framework/exceptions.py,sha256=C8bMuXkRaYr3sXXbsMOZcPrwiglDm8myZ4f6W7x7lrQ,610
5
5
  agentic_framework/logging.py,sha256=mHa65Qt-KdA6XsjcnM0RYbCyaxGrvGNt3FB9sexOXJU,2247
6
6
  agentic_framework/adapters/__init__.py,sha256=1vR3_hu_F6m0YSFBPTvme16p-98IZYv743xm9EalGy8,176
7
- agentic_framework/adapters/generator.py,sha256=DAlIIxrganfM7X5A4azEqXf7ME2O6qDjBuKgfz-hCfc,9799
7
+ agentic_framework/adapters/generator.py,sha256=k0IdLyui3GdIoJ7Z05HpiaqDIzeb2tOmj37S_IqHG2s,13865
8
8
  agentic_framework/core/__init__.py,sha256=-n3tAT8X8Smg8FcQghm9kMHh_3Ck_Z9LnFhA7tAVXZQ,32
9
9
  agentic_framework/core/command_registry.py,sha256=usRxLLonXIpHzd9dF811485wQDLPpoN14eUbOI3tvF0,771
10
10
  agentic_framework/core/config.py,sha256=sLs_-NbjwOXgT5OFtGKczKLpVEfmQoisuJeN1SK5t4g,4425
11
11
  agentic_framework/core/custom_commands.py,sha256=pk2vlFJaLef04KzGeXg2kmZMWpkywunq7H6V3MKAjhs,4114
12
- agentic_framework/core/initialization.py,sha256=aDZCUzTfwAtERkccRZwo1wxMcTrfLFOskKQXpyJP1Vw,8837
12
+ agentic_framework/core/initialization.py,sha256=_XxujmW77Z40nEnc1pR9VgsUEpOWNejY9xns8h7i2Gk,9999
13
13
  agentic_framework/core/project.py,sha256=MVVmxepUFlF4PL7tfOwk7uae0ddti-s8OJL1AbxS9Dg,2827
14
- agentic_framework/core/stages.py,sha256=aUtAY1FNoTmDGATIZKo0IIrpXLK6fHD0p8BYgTNXfNI,13550
15
- agentic_framework/core/workflow.py,sha256=yIjwk4tKLzTTxfhkaEIOGCANKgWFq2jMOX31W8T1pk4,13548
16
- agentic_framework/requirements_manager/__init__.py,sha256=Q1T1sIh9n2VxbBucCg_RNzZ6hYgYVJHWZdGe6ccC02M,234
14
+ agentic_framework/core/stages.py,sha256=0ZWgJJ7jprKLp4G4NTrVbHodTOEuLboYeQN3nko64is,20796
15
+ agentic_framework/core/workflow.py,sha256=uDZJwypvbEO9dyHyhl7cCmMD2Anf-knpoWAUWhbcfS4,22124
16
+ agentic_framework/requirements_manager/__init__.py,sha256=DP4QfMZBG3TVxZkkrzEY08sqF4OSI2YAHWsjoCGwc6M,584
17
17
  agentic_framework/requirements_manager/comparison.py,sha256=04Yxd-eK1EST1tbt-ps8wKlULHjhmS2OgwsLGWnXnR8,4807
18
18
  agentic_framework/requirements_manager/extraction.py,sha256=SSRbc6W4VDSS7jpnirCfFU2lVuyVCwPWCLoc50dhLvE,1362
19
- agentic_framework/requirements_manager/ingestion.py,sha256=iYRIXB8HQt15KHl05mjVXoN2nWpp-9_rx5wYfWAkMlI,14947
19
+ agentic_framework/requirements_manager/ingestion.py,sha256=NP8KScJOUkFzwZGGsqxo37LY0ABeDqfRgJKNMEkxk9M,15084
20
+ agentic_framework/requirements_manager/screenshots.py,sha256=xcKwo-ylI_MIsTdaPm9Jgy_erptaTnXPpQLQaOUYyLA,16833
20
21
  agentic_framework/requirements_manager/traceability.py,sha256=azvdk3rc8Uq_gknNn3H9KMg7cUP0q13ltG56f8gq6LE,2254
21
22
  agentic_framework/state/__init__.py,sha256=w4no5X4gzvJr935HcZvszZscATGSkEepsMBbBKzQQu8,135
22
23
  agentic_framework/state/database.py,sha256=8-8U86jezQuC_YiShLC2dyQ0U3uO2A41rpwKCWnW_XE,18196
23
24
  agentic_framework/templates/__init__.py,sha256=D1B-_zlAKldwEbDY_kEvAfltg6OLZOuLyt4b5Ujgtdw,42
24
- agentic_framework/templates/skills/agentic-commands/SKILL.md,sha256=ssfqqV_rT5_-izPvou-Ko2hv12wyxHMFXI6Ll214IWg,3577
25
- agentic_development_framework-0.2.0.dist-info/METADATA,sha256=CJGEnatPmOB3dlcoy9upkN0sYYf_rY2v55qUjwPTESo,9007
26
- agentic_development_framework-0.2.0.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
27
- agentic_development_framework-0.2.0.dist-info/entry_points.txt,sha256=yLrtkLPdApbQjlyVZYNpmRtgc0prbjpJGwF3G9td_zk,50
28
- agentic_development_framework-0.2.0.dist-info/licenses/LICENSE,sha256=6BzOzZ1c-kyBOz_uNhWQKM1xPmPEQzSNwubTqgniGM0,1100
29
- agentic_development_framework-0.2.0.dist-info/RECORD,,
25
+ agentic_framework/templates/skills/agentic-commands/SKILL.md,sha256=C0HlrvxjxG273kusqg4f53MEpevafGjSoKWWT8C0tlE,9012
26
+ agentic_development_framework-0.4.0.dist-info/METADATA,sha256=_hQNZFWp-r4pLM52ZEUbWAf4pLgE72_L0eRLicCV4iM,10332
27
+ agentic_development_framework-0.4.0.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
28
+ agentic_development_framework-0.4.0.dist-info/entry_points.txt,sha256=yLrtkLPdApbQjlyVZYNpmRtgc0prbjpJGwF3G9td_zk,50
29
+ agentic_development_framework-0.4.0.dist-info/licenses/LICENSE,sha256=6BzOzZ1c-kyBOz_uNhWQKM1xPmPEQzSNwubTqgniGM0,1100
30
+ agentic_development_framework-0.4.0.dist-info/RECORD,,
@@ -1,6 +1,6 @@
1
1
  """Agentic Development Framework public package metadata."""
2
2
 
3
- __version__ = "0.2.0"
3
+ __version__ = "0.4.0"
4
4
 
5
5
  __all__ = ["__version__"]
6
6
 
@@ -31,6 +31,15 @@ read the shared command skill and
31
31
  `.agentic/execution-contracts.yaml`; do not merely run a lifecycle command and report its output.
32
32
  The IDE agent performs reasoning and artifact creation while `adt` persists execution, artifacts,
33
33
  validation, approvals, and recovery. Never bypass approval gates or overwrite unrelated changes.
34
+ In an existing application, detect and follow its actual architecture, tools, conventions, Git
35
+ state, and active ADF artifacts; report discovered defects and conflicts instead of silently
36
+ ignoring them. For the frontend stage, inspect actual Figma/screenshot references, verify the
37
+ environment, and build the complete production frontend with accessible, responsive, meaningful
38
+ interactions. Supplied
39
+ references govern presentation and must have no unapproved visual deviation. Do not create a
40
+ disposable prototype. Require explicit frontend approval before backend planning or implementation.
41
+ Build the backend separately, then connect it through the frontend adapter boundary during the API
42
+ integration stage. A custom `/adf` request may refine current-stage work but cannot skip this order.
34
43
  """
35
44
 
36
45
  _CODEX_NOTE = """# Codex adapter
@@ -78,24 +87,79 @@ def _workflow() -> str:
78
87
  "checkpoint_policy": "on_completion",
79
88
  }
80
89
  )
81
- return _yaml({"schema_version": 2, "name": "default", "stages": stages})
90
+ return _yaml({"schema_version": 4, "name": "default", "stages": stages})
82
91
 
83
92
 
84
93
  def _registry() -> str:
85
94
  agents = []
86
95
  for agent_id, name in _AGENTS:
96
+ responsibilities = [f"Perform {name.lower()} work within approved scope"]
97
+ required_inputs: list[str] = []
98
+ expected_outputs = ["standardized agent result"]
99
+ verification = ["run relevant checks"]
100
+ if agent_id == "ui_ux_designer":
101
+ responsibilities = [
102
+ "Analyze visual references and define a production-ready design system",
103
+ "Analyze Figma, screenshots, and approved requirements without inventing evidence",
104
+ "Support exact visual comparison and intentional revision decisions",
105
+ ]
106
+ required_inputs = [
107
+ "approved requirements and architecture",
108
+ "screenshot manifest and actual images",
109
+ "optional authenticated Figma design context",
110
+ ]
111
+ expected_outputs = [
112
+ "design system and page inventory",
113
+ "visual reference analysis",
114
+ ]
115
+ verification = [
116
+ "inspect desktop, tablet, and mobile rendering",
117
+ "test meaningful behavior for every visible control",
118
+ "preserve revision and visual-reference traceability",
119
+ ]
120
+ elif agent_id == "frontend_developer":
121
+ responsibilities = [
122
+ "Verify the frontend stack and environment before implementation",
123
+ "Build the complete production frontend before backend implementation",
124
+ "Match approved references exactly and deliver modern, accessible interactions",
125
+ ]
126
+ required_inputs = ["approved requirements, architecture, and visual references"]
127
+ expected_outputs = ["production frontend and browser verification evidence"]
128
+ verification = [
129
+ "prove environment setup and production build before completion",
130
+ "compare actual frontend rendering with every approved reference",
131
+ "test pages, states, controls, accessibility, console, and responsive layouts",
132
+ ]
133
+ elif agent_id == "backend_developer":
134
+ responsibilities = [
135
+ "Implement backend services from approved API and architecture contracts",
136
+ "Preserve the approved frontend and its adapter boundary",
137
+ "Implement persistence, validation, security, migrations, and failure behavior",
138
+ ]
139
+ required_inputs = ["approved backend plan, architecture, and frontend adapter needs"]
140
+ expected_outputs = ["tested backend implementation and traceability manifest"]
141
+ verification = ["run backend unit, integration, migration, and security checks"]
142
+ elif agent_id == "integration_engineer":
143
+ responsibilities = [
144
+ "Replace frontend mocks through the documented adapter boundary",
145
+ "Verify API, authentication, validation, and failure-state behavior end to end",
146
+ "Prevent silent visual drift during frontend/backend integration",
147
+ ]
148
+ required_inputs = ["approved frontend, verified backend, and API integration plan"]
149
+ expected_outputs = ["API integration report with reproducible evidence"]
150
+ verification = ["run backend, frontend, API, and browser integration checks"]
87
151
  agents.append(
88
152
  {
89
153
  "id": agent_id,
90
154
  "name": name,
91
155
  "role": name,
92
- "responsibilities": [f"Perform {name.lower()} work within approved scope"],
156
+ "responsibilities": responsibilities,
93
157
  "scope": "assigned tasks only",
94
- "required_inputs": [],
95
- "expected_outputs": ["standardized agent result"],
158
+ "required_inputs": required_inputs,
159
+ "expected_outputs": expected_outputs,
96
160
  "allowed_tools": ["repository read/write tools", "project test commands"],
97
161
  "restricted_operations": ["secrets", "force push", "unapproved deployment"],
98
- "verification_requirements": ["run relevant checks"],
162
+ "verification_requirements": verification,
99
163
  "handoff_format": "agent result contract",
100
164
  "failure_and_escalation": "record blocker and escalate to orchestrator",
101
165
  }
agentic_framework/cli.py CHANGED
@@ -19,7 +19,7 @@ from agentic_framework.exceptions import (
19
19
  RequirementsError,
20
20
  StateError,
21
21
  )
22
- from agentic_framework.requirements_manager import RequirementsManager
22
+ from agentic_framework.requirements_manager import RequirementsManager, ScreenshotManager
23
23
 
24
24
  app = typer.Typer(
25
25
  name="adt",
@@ -427,3 +427,24 @@ def ingest_requirements(
427
427
  relative_report = result.impact_report.relative_to(result.version_path.parents[1])
428
428
  typer.echo(f"Impact report: {relative_report}")
429
429
 
430
+
431
+ @requirements_app.command("screenshots")
432
+ def sync_screenshots(
433
+ path: Annotated[
434
+ Path,
435
+ typer.Option("--path", help="Project directory containing requirements/screenshots."),
436
+ ] = Path("."),
437
+ ) -> None:
438
+ """Discover screenshot references and publish an immutable manifest revision."""
439
+
440
+ try:
441
+ result = ScreenshotManager(path).sync()
442
+ except RequirementsError as exc:
443
+ typer.echo(f"Error: {exc}", err=True)
444
+ raise typer.Exit(code=2) from exc
445
+ action = "Unchanged" if result.duplicate else "Published"
446
+ typer.echo(f"{action} screenshot revision {result.revision}.")
447
+ typer.echo(f"Screenshot files: {result.file_count}")
448
+ typer.echo("Manifest: requirements/screenshots/manifest.json")
449
+ typer.echo("Analysis: docs/ui-ux/screenshot-reference-analysis.md")
450
+
@@ -34,18 +34,30 @@ _DIRECTORIES = (
34
34
  ".github/instructions",
35
35
  ".github/workflows",
36
36
  "requirements/inbox",
37
+ "requirements/screenshots/desktop/homepage",
38
+ "requirements/screenshots/desktop/dashboard",
39
+ "requirements/screenshots/desktop/other",
40
+ "requirements/screenshots/mobile/homepage",
41
+ "requirements/screenshots/mobile/dashboard",
42
+ "requirements/screenshots/mobile/other",
43
+ "requirements/screenshots/admin-dashboard",
44
+ "requirements/screenshots/vendor-dashboard",
45
+ "requirements/screenshots/customer-dashboard",
46
+ "requirements/screenshots/references",
37
47
  "requirements/versions",
38
48
  "requirements/reports",
39
49
  "docs/discovery",
40
50
  "docs/requirements",
41
51
  "docs/architecture",
42
52
  "docs/design",
53
+ "docs/ui-ux",
54
+ "docs/frontend",
55
+ "docs/backend",
43
56
  "docs/decisions",
44
57
  "docs/planning",
45
58
  "docs/technical",
46
59
  "docs/revisions",
47
60
  "docs/reports",
48
- "design-prototype",
49
61
  "tests",
50
62
  )
51
63
 
@@ -64,6 +76,10 @@ This project uses the Agentic Development Framework (ADF).
64
76
  and run `adt stage complete`. The CLI persists state; the IDE agent performs the work.
65
77
  - Never treat successful `adt continue` output as completion or stage advancement.
66
78
  - Do not claim a task or phase is complete until its required checks pass.
79
+ - Build the complete production frontend before backend work: verify its environment, inspect actual
80
+ Figma/screenshots, browser-test all pages and viewports, and wait for explicit frontend approval.
81
+ - Keep frontend and backend separate until the API integration stage. Never create a disposable
82
+ design prototype or silently simplify an approved visual reference.
67
83
  """
68
84
 
69
85
  _REQUIREMENTS_README = """# Project requirements
@@ -72,6 +88,10 @@ Place source requirement files in `inbox/`, then run `adt requirements ingest`.
72
88
  source byte-for-byte into an immutable directory under `versions/`, detects duplicates using
73
89
  SHA-256 hashes, and compares each new version with its predecessor. Files in `inbox/` are never
74
90
  silently overwritten or removed.
91
+
92
+ Place PNG, JPG, JPEG, or WEBP visual references anywhere under `screenshots/`. ADF discovers them
93
+ recursively, preserves immutable revisions, and updates the screenshot manifest with
94
+ `adt requirements screenshots`. Folder names provide context but never replace visual inspection.
75
95
  """
76
96
 
77
97
  _GITIGNORE = """# Agentic Development Framework local runtime data
@@ -21,6 +21,7 @@ class StageContract:
21
21
  expected_outputs: tuple[str, ...]
22
22
  validation_criteria: tuple[str, ...]
23
23
  completion_conditions: tuple[str, ...]
24
+ supported_design_inputs: tuple[str, ...] = ()
24
25
  approval_required: bool = False
25
26
  failure_behavior: str = "Record the error, preserve work, and do not advance."
26
27
  max_attempts: int = 3
@@ -47,6 +48,7 @@ def _contract(
47
48
  "Every required output is registered with its current SHA-256 digest.",
48
49
  "Validation succeeds without unresolved execution errors.",
49
50
  ),
51
+ design_inputs: tuple[str, ...] = (),
50
52
  approval: bool = False,
51
53
  ) -> StageContract:
52
54
  return StageContract(
@@ -61,6 +63,7 @@ def _contract(
61
63
  expected_outputs=outputs,
62
64
  validation_criteria=validation,
63
65
  completion_conditions=completion,
66
+ supported_design_inputs=design_inputs,
64
67
  approval_required=approval,
65
68
  )
66
69
 
@@ -204,63 +207,186 @@ CONTRACTS = (
204
207
  ),
205
208
  _contract(
206
209
  "ui_ux_design",
207
- "UI/UX design",
208
- "Create a reviewable experience design before production frontend work.",
210
+ "Frontend environment & complete UI implementation",
211
+ "Configure and build the complete production frontend before backend implementation.",
209
212
  prerequisites=("architecture_review",),
210
- inputs=("docs/requirements/*.md", "docs/architecture/*.md"),
211
- agent="ui_ux_designer",
213
+ inputs=(
214
+ "docs/requirements/*.md",
215
+ "docs/architecture/*.md",
216
+ "requirements/screenshots/manifest.json",
217
+ "requirements/screenshots/**",
218
+ "existing project design assets and frontend source",
219
+ "optional Figma file or frame URL recorded in requirements",
220
+ ),
221
+ agent="frontend_developer",
222
+ responsibilities=(
223
+ "Inventory every required page, user role, journey, state, and responsive layout.",
224
+ "Verify the selected frontend stack, package manager, runtime, and environment first.",
225
+ "Build the actual maintainable production frontend; never create a disposable "
226
+ "prototype.",
227
+ "Reproduce approved Figma or screenshot references without unapproved visual "
228
+ "deviation.",
229
+ "Create an excellent modern interface when no external visual reference is supplied.",
230
+ ),
212
231
  instructions=(
213
- "Use a configured Figma integration only when a Figma file is supplied.",
214
- "Otherwise create an interactive local HTML/CSS/JavaScript prototype.",
232
+ "Run adt requirements screenshots before analysis and inspect every discovered image.",
233
+ "Record the selected Figma, screenshot, and generated-frontend methods in "
234
+ "docs/frontend/design-inputs.json; methods may be combined.",
235
+ "For Figma, use an available authenticated MCP integration, retrieve design context "
236
+ "and screenshots, and block honestly when access or authentication fails.",
237
+ "Inspect the architecture and existing repository, select its required frontend stack, "
238
+ "install dependencies with its package manager, and prove the environment and build "
239
+ "work.",
240
+ "Keep frontend and backend separate. Use typed mock data or an adapter boundary in "
241
+ "this stage; do not implement the backend or couple components directly to unfinished "
242
+ "APIs.",
243
+ "For supplied references, match layout, dimensions, spacing, typography, colors, "
244
+ "assets, responsive behavior, states, and interactions exactly except for documented "
245
+ "approved revisions.",
246
+ "When no external reference exists, establish a cohesive modern design system with "
247
+ "strong information hierarchy, typography, spacing, color, depth, and restrained "
248
+ "purposeful motion.",
249
+ "Build complete role-aware production pages with realistic data, reusable components, "
250
+ "design tokens, responsive layouts, and loading, empty, success, validation, and error "
251
+ "states.",
252
+ "Make every control meaningful and accessible: semantic structure, keyboard operation, "
253
+ "visible focus, sufficient contrast, reduced-motion support, and clear feedback are "
254
+ "mandatory.",
255
+ "Optimize rendering, assets, navigation, and perceived performance; avoid generic "
256
+ "template-like screens, placeholder content, decorative controls, and inconsistent "
257
+ "one-off styling.",
258
+ "Run the actual frontend in a browser at desktop, tablet, and mobile sizes, exercise "
259
+ "all interactions and states, compare it with every reference, capture evidence, fix "
260
+ "defects, and repeat.",
261
+ ),
262
+ outputs=(
263
+ "docs/frontend/technology-and-environment.md",
264
+ "docs/frontend/design-inputs.json",
265
+ "docs/frontend/page-inventory.md",
266
+ "docs/frontend/design-system.md",
267
+ "docs/frontend/implementation-manifest.json",
268
+ "docs/ui-ux/screenshot-reference-analysis.md",
269
+ "docs/frontend/browser-verification.json",
270
+ "docs/frontend/reference-comparison.md",
271
+ "docs/frontend/revision-history.md",
272
+ "docs/frontend/verification-screenshots/**",
273
+ ),
274
+ validation=(
275
+ "Frontend environment and production build verification pass for the documented stack.",
276
+ "Design-input evidence selects supported methods and never claims unavailable Figma "
277
+ "context.",
278
+ "The implementation manifest identifies existing production source files registered "
279
+ "for review.",
280
+ "Page inventory covers approved roles, requirements, states, and responsive variants.",
281
+ "Every visible control has meaningful, accessible, browser-tested behavior.",
282
+ "Browser evidence passes every page at desktop, tablet, and mobile with no console "
283
+ "errors, links to captured screenshots, and records no unapproved reference "
284
+ "deviations.",
285
+ ),
286
+ completion=(
287
+ "Every required document, production frontend source file, and verification screenshot "
288
+ "is registered with its current SHA-256 digest.",
289
+ "Structured design-input, implementation, and browser evidence passes validation.",
290
+ "The complete production frontend is ready for explicit visual and functional review.",
215
291
  ),
216
- outputs=("docs/design/ui-ux-specification.md", "design-prototype/index.html"),
292
+ design_inputs=("figma_mcp", "generated_frontend", "screenshots"),
217
293
  ),
218
294
  _contract(
219
295
  "design_review",
220
- "Design review",
221
- "Validate the prototype and request explicit approval before implementation.",
296
+ "Production frontend review",
297
+ "Present the complete browser-verified production frontend for explicit human approval.",
222
298
  prerequisites=("ui_ux_design",),
223
- inputs=("docs/design/*.md", "design-prototype/**"),
299
+ inputs=(
300
+ "docs/frontend/**",
301
+ "docs/ui-ux/screenshot-reference-analysis.md",
302
+ "frontend source",
303
+ ),
224
304
  agent="main_orchestrator",
225
- instructions=("Review accessibility, flows, requirements coverage, and feedback.",),
226
- outputs=("docs/design/ui-ux-specification.md", "design-prototype/index.html"),
305
+ instructions=(
306
+ "Present the page inventory, local preview instructions, design system, responsive and "
307
+ "interaction evidence, outstanding issues, and revision history.",
308
+ "Require explicit human approval; never infer it from generated files or silence.",
309
+ "For revision feedback, update affected production screens consistently, document the "
310
+ "intentional design change, preserve unrelated decisions, and rerun frontend "
311
+ "verification.",
312
+ ),
313
+ outputs=(
314
+ "docs/frontend/technology-and-environment.md",
315
+ "docs/frontend/design-inputs.json",
316
+ "docs/frontend/page-inventory.md",
317
+ "docs/frontend/design-system.md",
318
+ "docs/frontend/implementation-manifest.json",
319
+ "docs/frontend/browser-verification.json",
320
+ "docs/frontend/reference-comparison.md",
321
+ "docs/frontend/revision-history.md",
322
+ "docs/frontend/verification-screenshots/**",
323
+ ),
324
+ validation=(
325
+ "All production frontend source and review evidence remains current and registered.",
326
+ "Outstanding issues and assumptions are disclosed for human review.",
327
+ "No backend implementation begins before explicit frontend approval is recorded.",
328
+ ),
227
329
  approval=True,
228
330
  ),
229
331
  _contract(
230
332
  "development_planning",
231
- "Development planning",
232
- "Create an executable, dependency-aware delivery plan.",
333
+ "Backend & API integration planning",
334
+ "Plan backend implementation and later API integration around the approved frontend.",
233
335
  prerequisites=("design_review",),
234
- inputs=("docs/requirements/*.md", "docs/architecture/*.md", "docs/design/*.md"),
235
- responsibilities=("Separate frontend, backend, integration, and verification work.",),
236
- instructions=("Define milestones, tasks, dependencies, tests, and delivery criteria.",),
336
+ inputs=("docs/requirements/*.md", "docs/architecture/*.md", "docs/frontend/**"),
337
+ responsibilities=(
338
+ "Separate backend construction from frontend/API integration and verification.",
339
+ ),
340
+ instructions=(
341
+ "Derive API contracts from approved requirements, architecture, and frontend adapter "
342
+ "needs.",
343
+ "Define backend milestones, tasks, migrations, security, tests, integration, and "
344
+ "delivery criteria.",
345
+ "Do not redesign or rebuild the approved frontend during backend planning.",
346
+ ),
237
347
  outputs=(
238
- "docs/planning/milestones.md",
239
- "docs/planning/task-breakdown.md",
240
- "docs/planning/testing-plan.md",
241
- "docs/planning/integration-plan.md",
348
+ "docs/planning/backend-implementation-plan.md",
349
+ "docs/planning/api-integration-plan.md",
350
+ "docs/planning/backend-testing-plan.md",
242
351
  ),
243
352
  ),
244
353
  _contract(
245
354
  "implementation",
246
- "Implementation",
247
- "Implement approved tasks traceably against requirements and architecture.",
355
+ "Backend implementation",
356
+ "Implement and verify the backend independently against approved contracts.",
248
357
  prerequisites=("development_planning",),
249
- inputs=("docs/planning/*.md",),
358
+ inputs=(
359
+ "docs/planning/*.md",
360
+ "docs/frontend/implementation-manifest.json",
361
+ "docs/frontend/page-inventory.md",
362
+ ),
250
363
  agent="main_orchestrator",
251
364
  instructions=(
252
- "Delegate sequential work, run focused tests, and record changed artifacts.",
365
+ "Implement data, domain, service, API, security, and persistence behavior from the "
366
+ "plan.",
367
+ "Run focused backend tests and record requirement and API-contract traceability.",
368
+ "Do not redesign the approved frontend or bypass its documented adapter boundary.",
369
+ ),
370
+ outputs=(
371
+ ".agentic/reports/backend-implementation.md",
372
+ "docs/backend/implementation-manifest.json",
253
373
  ),
254
- outputs=(".agentic/reports/implementation.md",),
255
374
  ),
256
375
  _contract(
257
376
  "integration",
258
- "Integration",
259
- "Integrate application components and verify their contracts.",
377
+ "Frontend/backend API integration",
378
+ "Connect the approved frontend to the verified backend and test end-to-end behavior.",
260
379
  prerequisites=("implementation",),
261
380
  agent="integration_engineer",
262
- instructions=("Run integration checks and document failures and resolutions.",),
263
- outputs=("docs/reports/integration.md",),
381
+ instructions=(
382
+ "Replace frontend mocks through its adapter boundary without changing approved "
383
+ "presentation.",
384
+ "Verify API contracts, authentication, validation, loading, empty, success, and error "
385
+ "behavior.",
386
+ "Run integration and browser checks and document failures, fixes, and remaining "
387
+ "constraints.",
388
+ ),
389
+ outputs=("docs/reports/api-integration.md",),
264
390
  ),
265
391
  _contract(
266
392
  "qa_and_testing",
@@ -331,7 +457,7 @@ def contract_document() -> dict[str, Any]:
331
457
  """Return the complete versioned stage contract document."""
332
458
 
333
459
  return {
334
- "schema_version": 2,
460
+ "schema_version": 4,
335
461
  "execution_model": "ide_agent",
336
462
  "stages": [contract.as_dict() for contract in CONTRACTS],
337
463
  }
@@ -2,6 +2,7 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
+ import json
5
6
  import shutil
6
7
  from dataclasses import dataclass, field
7
8
  from pathlib import Path
@@ -13,7 +14,8 @@ from agentic_framework.core.stages import (
13
14
  STAGES,
14
15
  StageContract,
15
16
  )
16
- from agentic_framework.exceptions import StateError
17
+ from agentic_framework.exceptions import RequirementsError, StateError
18
+ from agentic_framework.requirements_manager import ScreenshotManager
17
19
  from agentic_framework.state import RuntimeStore
18
20
 
19
21
 
@@ -111,6 +113,11 @@ class WorkflowService:
111
113
  if execution["status"] == "completed":
112
114
  raise StateError(f"stage is already complete: {stage}")
113
115
  contract = self.stage_contract(stage)
116
+ if stage in {"ui_ux_design", "design_review"}:
117
+ try:
118
+ ScreenshotManager(self.project_root).sync()
119
+ except RequirementsError as exc:
120
+ raise StateError(f"cannot prepare visual references: {exc}") from exc
114
121
  if execution["status"] == "failed" and execution["attempt_count"] >= contract.max_attempts:
115
122
  self.store.update_execution(
116
123
  stage,
@@ -209,8 +216,158 @@ class WorkflowService:
209
216
  raise StateError("required outputs are not registered: " + ", ".join(unregistered))
210
217
  if stale:
211
218
  raise StateError("registered outputs changed; register them again: " + ", ".join(stale))
219
+ if stage in {"ui_ux_design", "design_review"}:
220
+ self._validate_frontend_evidence(stage)
212
221
  return [path.relative_to(self.project_root).as_posix() for path in files]
213
222
 
223
+ def _read_evidence(self, relative: str) -> dict[str, Any]:
224
+ path = self.project_root / relative
225
+ try:
226
+ value = json.loads(path.read_text(encoding="utf-8"))
227
+ except (OSError, UnicodeError, json.JSONDecodeError) as exc:
228
+ raise StateError(f"invalid structured workflow evidence {relative}: {exc}") from exc
229
+ if not isinstance(value, dict):
230
+ raise StateError(f"structured workflow evidence must be an object: {relative}")
231
+ return value
232
+
233
+ def _safe_existing_file(self, relative_value: str, *, within: Path | None = None) -> Path:
234
+ relative = Path(relative_value)
235
+ resolved = (self.project_root / relative).resolve()
236
+ allowed = (within or self.project_root).resolve()
237
+ if (
238
+ relative.is_absolute()
239
+ or ".." in relative.parts
240
+ or not resolved.is_relative_to(allowed)
241
+ or not resolved.is_file()
242
+ or resolved.is_symlink()
243
+ ):
244
+ raise StateError(f"evidence references an unsafe or missing file: {relative_value}")
245
+ return resolved
246
+
247
+ def _validate_frontend_evidence(self, stage: str) -> None:
248
+ inputs = self._read_evidence("docs/frontend/design-inputs.json")
249
+ methods = inputs.get("methods")
250
+ supported = set(CONTRACT_BY_ID["ui_ux_design"].supported_design_inputs)
251
+ if (
252
+ not isinstance(methods, list)
253
+ or not methods
254
+ or any(not isinstance(method, str) or method not in supported for method in methods)
255
+ ):
256
+ raise StateError(
257
+ "design-input evidence must select one or more supported methods: "
258
+ + ", ".join(sorted(supported))
259
+ )
260
+ if "figma_mcp" in methods:
261
+ figma = inputs.get("figma")
262
+ if (
263
+ not isinstance(figma, dict)
264
+ or figma.get("status") != "inspected"
265
+ or not isinstance(figma.get("url"), str)
266
+ or not figma["url"].startswith("https://")
267
+ or not isinstance(figma.get("source_requirement"), str)
268
+ or not figma["source_requirement"].strip()
269
+ ):
270
+ raise StateError(
271
+ "Figma is selected but its requirement source, URL, and authenticated MCP "
272
+ "inspection are not recorded; "
273
+ "record the blocker instead of claiming completion"
274
+ )
275
+ if "screenshots" in methods:
276
+ manifest = self._read_evidence("requirements/screenshots/manifest.json")
277
+ screenshots = manifest.get("screenshots")
278
+ if not isinstance(screenshots, list) or not screenshots:
279
+ raise StateError(
280
+ "screenshot design input is selected but the screenshot manifest is empty"
281
+ )
282
+
283
+ implementation = self._read_evidence("docs/frontend/implementation-manifest.json")
284
+ frontend_root_value = implementation.get("frontend_root")
285
+ if not isinstance(frontend_root_value, str) or not frontend_root_value.strip():
286
+ raise StateError("frontend implementation manifest must identify frontend_root")
287
+ frontend_root_relative = Path(frontend_root_value)
288
+ frontend_root = (self.project_root / frontend_root_relative).resolve()
289
+ if (
290
+ frontend_root_relative.is_absolute()
291
+ or ".." in frontend_root_relative.parts
292
+ or not frontend_root.is_relative_to(self.project_root)
293
+ or not frontend_root.is_dir()
294
+ or frontend_root.is_symlink()
295
+ ):
296
+ raise StateError("frontend_root must be a safe existing project directory")
297
+ stack = implementation.get("stack")
298
+ if (
299
+ not isinstance(stack, dict)
300
+ or not stack
301
+ or any(not isinstance(value, str) or not value.strip() for value in stack.values())
302
+ ):
303
+ raise StateError("frontend implementation manifest must document the selected stack")
304
+ if implementation.get("environment_verified") is not True:
305
+ raise StateError("frontend environment verification has not passed")
306
+ if implementation.get("build_passed") is not True:
307
+ raise StateError("frontend production build has not passed")
308
+ for key in ("install_command", "build_command"):
309
+ value = implementation.get(key)
310
+ if not isinstance(value, str) or not value.strip():
311
+ raise StateError(f"frontend implementation manifest must record {key}")
312
+ source_files = implementation.get("source_files")
313
+ if not isinstance(source_files, list) or not source_files:
314
+ raise StateError("frontend implementation manifest must list production source_files")
315
+ registered = {item["path"] for item in self.store.artifacts(stage)}
316
+ for source in source_files:
317
+ if not isinstance(source, str):
318
+ raise StateError("frontend source file paths must be strings")
319
+ resolved = self._safe_existing_file(source, within=frontend_root)
320
+ relative = resolved.relative_to(self.project_root).as_posix()
321
+ if relative not in registered:
322
+ raise StateError(
323
+ f"frontend source file is not registered for {stage}: {relative}"
324
+ )
325
+
326
+ evidence = self._read_evidence("docs/frontend/browser-verification.json")
327
+ pages = evidence.get("pages")
328
+ if evidence.get("passed") is not True or not isinstance(pages, list) or not pages:
329
+ raise StateError("browser verification must pass and include every frontend page")
330
+ console_errors = evidence.get("console_errors")
331
+ if not isinstance(console_errors, list) or console_errors:
332
+ raise StateError("frontend browser verification must record zero console errors")
333
+ required_viewports = {"desktop", "tablet", "mobile"}
334
+ for page in pages:
335
+ if not isinstance(page, dict) or not isinstance(page.get("id"), str):
336
+ raise StateError("each browser-verified page must have a stable id")
337
+ viewports = page.get("viewports")
338
+ if (
339
+ not isinstance(viewports, list)
340
+ or any(not isinstance(viewport, str) for viewport in viewports)
341
+ or not required_viewports <= set(viewports)
342
+ ):
343
+ raise StateError(
344
+ f"browser verification for {page['id']} must cover desktop, tablet, and mobile"
345
+ )
346
+ if page.get("interactions_passed") is not True:
347
+ raise StateError(f"interactive controls did not pass for page: {page['id']}")
348
+ if page.get("accessibility_passed") is not True:
349
+ raise StateError(f"accessibility checks did not pass for page: {page['id']}")
350
+ states = page.get("states_verified")
351
+ if not isinstance(states, list) or not states or any(
352
+ not isinstance(state, str) or not state.strip() for state in states
353
+ ):
354
+ raise StateError(f"verified UI states are missing for page: {page['id']}")
355
+ if page.get("reference_match") is not True:
356
+ raise StateError(f"frontend does not match its approved reference: {page['id']}")
357
+ deviations = page.get("unapproved_deviations")
358
+ if not isinstance(deviations, list) or deviations:
359
+ raise StateError(f"unapproved reference deviations remain for page: {page['id']}")
360
+ screenshots = page.get("screenshots")
361
+ if not isinstance(screenshots, list) or not screenshots:
362
+ raise StateError(f"rendered screenshots are missing for page: {page['id']}")
363
+ for screenshot in screenshots:
364
+ if not isinstance(screenshot, str):
365
+ raise StateError(f"invalid rendered screenshot path for page: {page['id']}")
366
+ self._safe_existing_file(
367
+ screenshot,
368
+ within=self.project_root / "docs/frontend/verification-screenshots",
369
+ )
370
+
214
371
  def complete_stage(self) -> dict[str, Any]:
215
372
  """Validate and complete the current stage, stopping at approval gates."""
216
373
 
@@ -4,5 +4,20 @@ from agentic_framework.requirements_manager.ingestion import (
4
4
  IngestionResult,
5
5
  RequirementsManager,
6
6
  )
7
+ from agentic_framework.requirements_manager.screenshots import (
8
+ SUPPORTED_SCREENSHOT_SUFFIXES,
9
+ ScreenshotManager,
10
+ ScreenshotReference,
11
+ ScreenshotSyncResult,
12
+ image_dimensions,
13
+ )
7
14
 
8
- __all__ = ["IngestionResult", "RequirementsManager"]
15
+ __all__ = [
16
+ "SUPPORTED_SCREENSHOT_SUFFIXES",
17
+ "IngestionResult",
18
+ "RequirementsManager",
19
+ "ScreenshotManager",
20
+ "ScreenshotReference",
21
+ "ScreenshotSyncResult",
22
+ "image_dimensions",
23
+ ]
@@ -23,6 +23,7 @@ from agentic_framework.requirements_manager.comparison import (
23
23
  render_impact_report,
24
24
  )
25
25
  from agentic_framework.requirements_manager.extraction import ExtractionResult, extract_text
26
+ from agentic_framework.requirements_manager.screenshots import ScreenshotManager
26
27
  from agentic_framework.requirements_manager.traceability import (
27
28
  RequirementRecord,
28
29
  extract_requirement_records,
@@ -333,6 +334,7 @@ class RequirementsManager:
333
334
  self._prepare_directories()
334
335
  with _ingestion_lock(self.requirements_root):
335
336
  items = self.inventory()
337
+ ScreenshotManager(self.project_root).sync()
336
338
  published = self._published_versions()
337
339
  latest = published[-1] if published else None
338
340
  if latest and self._manifest_signature(latest[1]) == self._signature(items):
@@ -0,0 +1,436 @@
1
+ """Immutable screenshot-reference discovery and metadata versioning."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import os
8
+ import shutil
9
+ import struct
10
+ import tempfile
11
+ from dataclasses import dataclass
12
+ from datetime import UTC, datetime
13
+ from pathlib import Path
14
+ from typing import Any
15
+
16
+ from agentic_framework.exceptions import RequirementsError
17
+
18
+ SUPPORTED_SCREENSHOT_SUFFIXES = frozenset({".png", ".jpg", ".jpeg", ".webp"})
19
+ _GENERATED_START = "<!-- ADF:SCREENSHOT-INVENTORY:START -->"
20
+ _GENERATED_END = "<!-- ADF:SCREENSHOT-INVENTORY:END -->"
21
+
22
+
23
+ @dataclass(frozen=True, slots=True)
24
+ class ScreenshotReference:
25
+ """Metadata for one unmodified screenshot reference."""
26
+
27
+ path: Path
28
+ relative_path: Path
29
+ sha256: str
30
+ size: int
31
+ width: int
32
+ height: int
33
+ format: str
34
+ context: tuple[str, ...]
35
+ device_hint: str
36
+ page_hint: str
37
+ role_hint: str | None
38
+
39
+ def as_dict(self) -> dict[str, Any]:
40
+ """Return stable JSON-compatible metadata."""
41
+
42
+ return {
43
+ "path": self.relative_path.as_posix(),
44
+ "sha256": self.sha256,
45
+ "size": self.size,
46
+ "width": self.width,
47
+ "height": self.height,
48
+ "format": self.format,
49
+ "context": list(self.context),
50
+ "device_hint": self.device_hint,
51
+ "page_hint": self.page_hint,
52
+ "role_hint": self.role_hint,
53
+ }
54
+
55
+
56
+ @dataclass(frozen=True, slots=True)
57
+ class ScreenshotSyncResult:
58
+ """Outcome of screenshot discovery and immutable catalog publication."""
59
+
60
+ revision: int
61
+ file_count: int
62
+ duplicate: bool
63
+ manifest_path: Path
64
+ analysis_path: Path
65
+ version_path: Path | None
66
+
67
+
68
+ def _sha256(path: Path) -> str:
69
+ digest = hashlib.sha256()
70
+ try:
71
+ with path.open("rb") as source:
72
+ for chunk in iter(lambda: source.read(1024 * 1024), b""):
73
+ digest.update(chunk)
74
+ except OSError as exc:
75
+ raise RequirementsError(f"cannot read screenshot reference {path}: {exc}") from exc
76
+ return digest.hexdigest()
77
+
78
+
79
+ def _png_dimensions(data: bytes) -> tuple[int, int] | None:
80
+ if len(data) >= 24 and data.startswith(b"\x89PNG\r\n\x1a\n") and data[12:16] == b"IHDR":
81
+ return struct.unpack(">II", data[16:24])
82
+ return None
83
+
84
+
85
+ def _jpeg_dimensions(data: bytes) -> tuple[int, int] | None:
86
+ if not data.startswith(b"\xff\xd8"):
87
+ return None
88
+ offset = 2
89
+ start_of_frame = {
90
+ 0xC0,
91
+ 0xC1,
92
+ 0xC2,
93
+ 0xC3,
94
+ 0xC5,
95
+ 0xC6,
96
+ 0xC7,
97
+ 0xC9,
98
+ 0xCA,
99
+ 0xCB,
100
+ 0xCD,
101
+ 0xCE,
102
+ 0xCF,
103
+ }
104
+ while offset + 4 <= len(data):
105
+ if data[offset] != 0xFF:
106
+ offset += 1
107
+ continue
108
+ while offset < len(data) and data[offset] == 0xFF:
109
+ offset += 1
110
+ if offset >= len(data):
111
+ break
112
+ marker = data[offset]
113
+ offset += 1
114
+ if marker in {0x01, *range(0xD0, 0xDA)}:
115
+ continue
116
+ if offset + 2 > len(data):
117
+ break
118
+ length = int.from_bytes(data[offset : offset + 2], "big")
119
+ if length < 2 or offset + length > len(data):
120
+ break
121
+ if marker in start_of_frame and length >= 7:
122
+ height = int.from_bytes(data[offset + 3 : offset + 5], "big")
123
+ width = int.from_bytes(data[offset + 5 : offset + 7], "big")
124
+ return width, height
125
+ offset += length
126
+ return None
127
+
128
+
129
+ def _little_uint24(value: bytes) -> int:
130
+ return int.from_bytes(value, "little")
131
+
132
+
133
+ def _webp_dimensions(data: bytes) -> tuple[int, int] | None:
134
+ if len(data) < 30 or data[:4] != b"RIFF" or data[8:12] != b"WEBP":
135
+ return None
136
+ kind = data[12:16]
137
+ if kind == b"VP8X":
138
+ return 1 + _little_uint24(data[24:27]), 1 + _little_uint24(data[27:30])
139
+ if kind == b"VP8 " and data[23:26] == b"\x9d\x01\x2a":
140
+ width = int.from_bytes(data[26:28], "little") & 0x3FFF
141
+ height = int.from_bytes(data[28:30], "little") & 0x3FFF
142
+ return width, height
143
+ if kind == b"VP8L" and len(data) >= 25 and data[20] == 0x2F:
144
+ bits = int.from_bytes(data[21:25], "little")
145
+ return 1 + (bits & 0x3FFF), 1 + ((bits >> 14) & 0x3FFF)
146
+ return None
147
+
148
+
149
+ def image_dimensions(path: Path) -> tuple[int, int]:
150
+ """Read dimensions from a supported image header without modifying the file."""
151
+
152
+ try:
153
+ data = path.read_bytes()
154
+ except OSError as exc:
155
+ raise RequirementsError(f"cannot read screenshot reference {path}: {exc}") from exc
156
+ suffix = path.suffix.lower()
157
+ dimensions = {
158
+ ".png": _png_dimensions,
159
+ ".jpg": _jpeg_dimensions,
160
+ ".jpeg": _jpeg_dimensions,
161
+ ".webp": _webp_dimensions,
162
+ }[suffix](data)
163
+ if dimensions is None or min(dimensions) <= 0:
164
+ raise RequirementsError(f"invalid or unsupported {suffix} screenshot image: {path}")
165
+ return dimensions
166
+
167
+
168
+ def _hints(relative: Path, width: int, height: int) -> tuple[str, str, str | None]:
169
+ context = [part.lower() for part in relative.parent.parts if part not in {".", ""}]
170
+ if "mobile" in context:
171
+ device = "mobile"
172
+ elif "desktop" in context:
173
+ device = "desktop"
174
+ elif "tablet" in context:
175
+ device = "tablet"
176
+ else:
177
+ ratio = width / height
178
+ device = "mobile" if ratio < 0.75 else "desktop" if ratio > 1.15 else "unknown"
179
+ roles = ("admin", "vendor", "customer")
180
+ role = next((name for name in roles if any(name in part for part in context)), None)
181
+ ignored = {"desktop", "mobile", "tablet", "references", "other"}
182
+ page = next((part for part in reversed(context) if part not in ignored), relative.stem)
183
+ return device, page, role
184
+
185
+
186
+ class ScreenshotManager:
187
+ """Discover screenshots recursively and preserve immutable reference revisions."""
188
+
189
+ def __init__(self, project_root: Path) -> None:
190
+ self.project_root = project_root.expanduser().resolve()
191
+ self.root = self.project_root / "requirements" / "screenshots"
192
+ self.versions = self.root / ".versions"
193
+ self.manifest_path = self.root / "manifest.json"
194
+ self.analysis_path = self.project_root / "docs" / "ui-ux" / (
195
+ "screenshot-reference-analysis.md"
196
+ )
197
+
198
+ def discover(self) -> tuple[ScreenshotReference, ...]:
199
+ """Recursively inventory supported screenshot files and contextual folder hints."""
200
+
201
+ self.root.mkdir(parents=True, exist_ok=True)
202
+ references: list[ScreenshotReference] = []
203
+ for path in sorted(self.root.rglob("*")):
204
+ relative = path.relative_to(self.root)
205
+ if relative.parts and relative.parts[0] == ".versions":
206
+ continue
207
+ if path.is_symlink():
208
+ raise RequirementsError(f"symbolic screenshot references are not accepted: {path}")
209
+ if not path.is_file() or path.suffix.lower() not in SUPPORTED_SCREENSHOT_SUFFIXES:
210
+ continue
211
+ width, height = image_dimensions(path)
212
+ device, page, role = _hints(relative, width, height)
213
+ references.append(
214
+ ScreenshotReference(
215
+ path=path,
216
+ relative_path=relative,
217
+ sha256=_sha256(path),
218
+ size=path.stat().st_size,
219
+ width=width,
220
+ height=height,
221
+ format=path.suffix.lower().removeprefix(".").replace("jpeg", "jpg"),
222
+ context=relative.parent.parts,
223
+ device_hint=device,
224
+ page_hint=page,
225
+ role_hint=role,
226
+ )
227
+ )
228
+ return tuple(references)
229
+
230
+ @staticmethod
231
+ def _signature(references: tuple[ScreenshotReference, ...]) -> dict[str, str]:
232
+ return {item.relative_path.as_posix(): item.sha256 for item in references}
233
+
234
+ def _read_manifest(self) -> dict[str, Any] | None:
235
+ if not self.manifest_path.is_file():
236
+ return None
237
+ try:
238
+ value = json.loads(self.manifest_path.read_text(encoding="utf-8"))
239
+ except (OSError, UnicodeError, json.JSONDecodeError) as exc:
240
+ raise RequirementsError(
241
+ f"cannot read screenshot manifest {self.manifest_path}: {exc}"
242
+ ) from exc
243
+ if not isinstance(value, dict) or not isinstance(value.get("screenshots"), list):
244
+ raise RequirementsError(f"invalid screenshot manifest: {self.manifest_path}")
245
+ return value
246
+
247
+ def _validate_versions(self) -> list[dict[str, Any]]:
248
+ manifests: list[dict[str, Any]] = []
249
+ if not self.versions.is_dir():
250
+ return manifests
251
+ for directory in sorted(self.versions.glob("version-*")):
252
+ manifest_path = directory / "manifest.json"
253
+ try:
254
+ manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
255
+ except (OSError, UnicodeError, json.JSONDecodeError) as exc:
256
+ raise RequirementsError(
257
+ f"cannot validate immutable screenshot revision {directory}: {exc}"
258
+ ) from exc
259
+ if not isinstance(manifest, dict) or manifest.get("immutable") is not True:
260
+ raise RequirementsError(f"invalid immutable screenshot revision: {directory}")
261
+ expected_revision = int(directory.name.removeprefix("version-"))
262
+ if manifest.get("revision") != expected_revision:
263
+ raise RequirementsError(f"invalid screenshot revision number: {directory}")
264
+ screenshots = manifest.get("screenshots")
265
+ if not isinstance(screenshots, list):
266
+ raise RequirementsError(f"invalid screenshot inventory: {directory}")
267
+ source_root = (directory / "source-files").resolve()
268
+ for item in screenshots:
269
+ if not isinstance(item, dict) or not isinstance(item.get("path"), str):
270
+ raise RequirementsError(f"invalid screenshot record: {directory}")
271
+ source = (source_root / item["path"]).resolve()
272
+ if (
273
+ not source.is_relative_to(source_root)
274
+ or not source.is_file()
275
+ or source.is_symlink()
276
+ or _sha256(source) != item.get("sha256")
277
+ ):
278
+ raise RequirementsError(
279
+ f"immutable screenshot reference was modified or removed: {source}"
280
+ )
281
+ manifests.append(manifest)
282
+ return manifests
283
+
284
+ @staticmethod
285
+ def _manifest_signature(manifest: dict[str, Any]) -> dict[str, str]:
286
+ return {item["path"]: item["sha256"] for item in manifest["screenshots"]}
287
+
288
+ @staticmethod
289
+ def _atomic_text(path: Path, content: str) -> None:
290
+ path.parent.mkdir(parents=True, exist_ok=True)
291
+ temporary = path.with_suffix(path.suffix + ".tmp")
292
+ temporary.write_text(content, encoding="utf-8")
293
+ os.replace(temporary, path)
294
+
295
+ def _analysis_inventory(
296
+ self, references: tuple[ScreenshotReference, ...], revision: int
297
+ ) -> str:
298
+ lines = [
299
+ _GENERATED_START,
300
+ "# Screenshot reference analysis",
301
+ "",
302
+ f"Manifest revision: **{revision}**",
303
+ "",
304
+ "## Screenshot inventory",
305
+ "",
306
+ ]
307
+ if not references:
308
+ lines.append("No screenshot references were discovered.")
309
+ else:
310
+ lines.extend(
311
+ [
312
+ "| Original path | Dimensions | Device hint | Page hint | Role hint |",
313
+ "| --- | ---: | --- | --- | --- |",
314
+ ]
315
+ )
316
+ for item in references:
317
+ role = item.role_hint or "unspecified"
318
+ lines.append(
319
+ f"| `requirements/screenshots/{item.relative_path.as_posix()}` | "
320
+ f"{item.width}×{item.height} | {item.device_hint} | "
321
+ f"{item.page_hint} | {role} |"
322
+ )
323
+ lines.extend(
324
+ [
325
+ "",
326
+ "> Folder-derived labels are contextual hints only. The frontend agent must "
327
+ "inspect "
328
+ "the actual images before recording conclusions.",
329
+ _GENERATED_END,
330
+ ]
331
+ )
332
+ return "\n".join(lines)
333
+
334
+ def _update_analysis(
335
+ self, references: tuple[ScreenshotReference, ...], revision: int
336
+ ) -> None:
337
+ generated = self._analysis_inventory(references, revision)
338
+ editable = """
339
+
340
+ ## Visual patterns and reusable components
341
+
342
+ To be completed by the frontend agent after visual inspection.
343
+
344
+ ## Missing pages and responsive states
345
+
346
+ To be completed against approved requirements and the page inventory.
347
+
348
+ ## Assumptions and inferred design decisions
349
+
350
+ Record evidence, confidence, and questions that materially affect usability.
351
+
352
+ ## Reference-to-frontend traceability
353
+
354
+ Map each reference to the production frontend pages and components that use it.
355
+ """
356
+ if self.analysis_path.is_file():
357
+ existing = self.analysis_path.read_text(encoding="utf-8")
358
+ if _GENERATED_END in existing:
359
+ editable = existing.split(_GENERATED_END, maxsplit=1)[1]
360
+ elif existing.strip():
361
+ editable = (
362
+ "\n\n## Preserved pre-existing analysis\n\n"
363
+ + existing.rstrip()
364
+ + "\n"
365
+ )
366
+ self._atomic_text(self.analysis_path, generated + editable.rstrip() + "\n")
367
+
368
+ def sync(self) -> ScreenshotSyncResult:
369
+ """Publish a new immutable screenshot revision when reference bytes change."""
370
+
371
+ references = self.discover()
372
+ versions = self._validate_versions()
373
+ current = self._read_manifest()
374
+ if versions and current is None:
375
+ raise RequirementsError(
376
+ "current screenshot manifest is missing while immutable revisions exist"
377
+ )
378
+ if current and versions:
379
+ latest = versions[-1]
380
+ if current.get("revision") != latest.get("revision") or self._manifest_signature(
381
+ current
382
+ ) != self._manifest_signature(latest):
383
+ raise RequirementsError(
384
+ "current screenshot manifest does not match the latest immutable revision"
385
+ )
386
+ if current and self._manifest_signature(current) == self._signature(references):
387
+ revision = int(current.get("revision", 1))
388
+ self._update_analysis(references, revision)
389
+ return ScreenshotSyncResult(
390
+ revision=revision,
391
+ file_count=len(references),
392
+ duplicate=True,
393
+ manifest_path=self.manifest_path,
394
+ analysis_path=self.analysis_path,
395
+ version_path=self.versions / f"version-{revision:03d}",
396
+ )
397
+
398
+ revision = int(current.get("revision", 0)) + 1 if current else 1
399
+ version_path = self.versions / f"version-{revision:03d}"
400
+ self.versions.mkdir(parents=True, exist_ok=True)
401
+ if version_path.exists():
402
+ raise RequirementsError(f"screenshot revision target already exists: {version_path}")
403
+ manifest: dict[str, Any] = {
404
+ "schema_version": 1,
405
+ "revision": revision,
406
+ "created_at": datetime.now(UTC).isoformat(),
407
+ "immutable": True,
408
+ "previous_revision": int(current["revision"]) if current else None,
409
+ "screenshots": [item.as_dict() for item in references],
410
+ }
411
+ with tempfile.TemporaryDirectory(prefix=".adf-screenshots-", dir=self.versions) as temp:
412
+ staging = Path(temp)
413
+ for item in references:
414
+ destination = staging / "source-files" / item.relative_path
415
+ destination.parent.mkdir(parents=True, exist_ok=True)
416
+ shutil.copyfile(item.path, destination)
417
+ if _sha256(destination) != item.sha256:
418
+ raise RequirementsError(
419
+ f"copied screenshot failed hash verification: {item.path}"
420
+ )
421
+ (staging / "manifest.json").write_text(
422
+ json.dumps(manifest, indent=2, sort_keys=True) + "\n", encoding="utf-8"
423
+ )
424
+ os.replace(staging, version_path)
425
+ self._atomic_text(
426
+ self.manifest_path, json.dumps(manifest, indent=2, sort_keys=True) + "\n"
427
+ )
428
+ self._update_analysis(references, revision)
429
+ return ScreenshotSyncResult(
430
+ revision=revision,
431
+ file_count=len(references),
432
+ duplicate=False,
433
+ manifest_path=self.manifest_path,
434
+ analysis_path=self.analysis_path,
435
+ version_path=version_path,
436
+ )
@@ -30,11 +30,86 @@ For `/start`, `/continue`, or `/adf-resume`, perform this loop from the project
30
30
  9. Run `adt stage complete`. This is the only normal command that may advance a non-review stage.
31
31
  10. If the stage enters `awaiting_approval`, show the registered deliverables and stop. Only the
32
32
  user may authorize `adt approve <stage>` or request `adt revise <stage> <feedback>`.
33
+ Never infer approval of the production frontend or begin backend implementation early.
33
34
  11. After revision feedback, update the deliverables, register the new bytes, rerun checks, and
34
35
  complete the same stage again. ADF preserves the previous reviewed artifact snapshot.
35
36
  12. Summarize artifacts, checks, persisted state, and any remaining blocker. Never claim a stage is
36
37
  complete unless `adt stage complete` or `adt approve` succeeded.
37
38
 
39
+ ## Existing-project discipline
40
+
41
+ For an existing or running application, inspect its real structure before proposing work: source
42
+ roots, frameworks, package managers, build and test commands, routes, modules, data models, API
43
+ boundaries, authentication, deployment configuration, conventions, and current Git changes. Adapt
44
+ the contract to that architecture; never impose a guessed folder layout. Preserve staged, unstaged,
45
+ and unrelated changes.
46
+
47
+ Compare requested behavior with the existing application and active ADF artifacts. Record discovered
48
+ bugs, broken commands, security concerns, inconsistent behavior, missing tests, and requirement
49
+ conflicts in the stage deliverable. Fix them only when the current approved scope authorizes the fix;
50
+ otherwise report them as actionable findings. Synchronize new work with completed and active tasks,
51
+ requirements IDs, decisions, and registered artifacts so parallel-looking requests do not conflict.
52
+
53
+ ## Production frontend execution
54
+
55
+ For `ui_ux_design`, the deliverable is the actual production frontend—not a wireframe, throwaway
56
+ HTML demo, or design prototype.
57
+
58
+ 1. Run `adt requirements screenshots` and open every relevant image. Search approved requirements for
59
+ Figma URLs. A manifest or filename is not visual inspection.
60
+ 2. Inspect the architecture and existing frontend. Record the frontend root, framework, language,
61
+ styling and component systems, package manager, runtime, install command, and build command.
62
+ 3. Install only compatible required dependencies. Prove the environment works before UI coding and
63
+ record the result in `docs/frontend/technology-and-environment.md`.
64
+ 4. Select one or more honest input modes in `docs/frontend/design-inputs.json`: `figma_mcp`,
65
+ `screenshots`, or `generated_frontend`. When Figma is selected, use authenticated design context
66
+ and record its requirement source and URL; persist a blocker if it cannot be inspected.
67
+ 5. Inventory all roles, routes, journeys, pages, responsive layouts, and relevant loading, empty,
68
+ success, validation, permission, offline, and error states before declaring coverage complete.
69
+ 6. For supplied references, reproduce layout, dimensions, spacing, typography, colors, assets,
70
+ hierarchy, responsive behavior, and interactions without unapproved deviation. Requirements govern
71
+ behavior; references govern presentation. Ask when they materially conflict.
72
+ 7. Without an external reference, create a distinctive, coherent design system before pages. Use
73
+ deliberate typography, spacing, color, hierarchy, reusable tokens/components, realistic content,
74
+ restrained purposeful motion, and strong information architecture. Avoid generic template output.
75
+ 8. Every visible control must do meaningful work. Implement semantic structure, keyboard access,
76
+ visible focus, contrast, reduced-motion support, clear feedback, and good perceived performance.
77
+ 9. Keep frontend and backend separate. Use typed mock data behind an adapter/service boundary; do not
78
+ build backend logic or couple UI components directly to unfinished endpoints in this stage.
79
+ 10. Run the real frontend in a browser. Exercise every page, state, navigation path, form, filter,
80
+ dialog, and other control at desktop, tablet, and mobile sizes. Check the console, capture rendered
81
+ evidence, compare each page to its reference, fix defects, and repeat.
82
+ 11. Register all required evidence and every source file listed in
83
+ `docs/frontend/implementation-manifest.json`. The manifest must record successful environment and
84
+ production-build checks. Do not claim exactness based only on code inspection.
85
+
86
+ For `design_review`, present the running production frontend, reference comparison, known constraints,
87
+ browser evidence, and revision history. Stop for explicit approval. Revision feedback changes the
88
+ production frontend itself, documents the intentional difference, preserves unrelated approved work,
89
+ reruns affected build/browser checks, and registers the new bytes. Backend work cannot begin early.
90
+
91
+ ## Backend and integration sequence
92
+
93
+ For `development_planning`, plan the backend and later integration from approved requirements,
94
+ architecture, frontend adapter needs, and page/state inventory. Define API contracts, validation,
95
+ identity and permissions, persistence, migrations, security, tests, dependencies, and failure behavior.
96
+
97
+ For `implementation`, build and test only the backend plan. Do not redesign the approved frontend or
98
+ bypass its adapter boundary. Record backend source, migrations, commands, tests, and API-contract
99
+ traceability in the required manifest and report.
100
+
101
+ For `integration`, replace frontend mocks through the adapter boundary. Verify request/response
102
+ contracts, authentication and authorization, validation, loading, empty, success, retry, timeout, and
103
+ error behavior end to end. Rerun backend, frontend, integration, and browser checks relevant to the
104
+ change. Visual changes require explicit revision rather than silent drift.
105
+
106
+ ## Evidence quality
107
+
108
+ Evidence must name the command or inspection performed and its observed result. A planned check,
109
+ placeholder, generated filename, or assertion without execution is not evidence. Report failures
110
+ honestly, preserve diagnostics without secrets, and leave the workflow at the current stage when any
111
+ completion condition remains unsatisfied.
112
+
38
113
  Other mappings:
39
114
 
40
115
  - `/status`, `/pause`, `/stop`, `/review`, `/requirements`, and `/tasks` map to the same `adt`