@capagents/forgeqe 2.7.1 → 2.7.3

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.
Files changed (124) hide show
  1. package/HOW_TO_USE.md +82 -18
  2. package/THIRD_PARTY_NOTICES.md +62 -22
  3. package/bin/forgeqe.js +1 -1
  4. package/dist/docs-site/docs/architecture/index.html +1 -1
  5. package/dist/docs-site/docs/containers/index.html +1 -1
  6. package/dist/docs-site/docs/index.html +71 -2
  7. package/dist/docs-site/docs/search.js +1 -1
  8. package/dist/forgeqe.js +1775 -1520
  9. package/dist/web/THIRD_PARTY_NOTICES.md +578 -51
  10. package/dist/web/assets/Agent-DU51Em-3.js +4 -0
  11. package/dist/web/assets/ApiTests-D6YhbfPF.js +10 -0
  12. package/dist/web/assets/Chat-CQsQvyDs.js +3 -0
  13. package/dist/web/assets/Data-Djj0u25X.js +3 -0
  14. package/dist/web/assets/Evidence-R2GZ5yW9.js +1 -0
  15. package/dist/web/assets/Features-C1qvr-oy.js +1 -0
  16. package/dist/web/assets/Jobs-BOr2nkQa.js +5 -0
  17. package/dist/web/assets/KindPage-CB2gMzhI.js +6 -0
  18. package/dist/web/assets/Migration-71lvv1zU.js +2 -0
  19. package/dist/web/assets/Product-BAQtMlzO.js +7 -0
  20. package/dist/web/assets/Product-DLioOiRN.css +1 -0
  21. package/dist/web/assets/Quality-DeUvoOND.js +1 -0
  22. package/dist/web/assets/Record-CPjgxHRX.js +2 -0
  23. package/dist/web/assets/Regression-D8V0CNAw.js +5 -0
  24. package/dist/web/assets/Reports-Bhv6gqFl.js +2 -0
  25. package/dist/web/assets/Response-CXyWQxrt.js +4 -0
  26. package/dist/web/assets/Runs-Ba8X4nId.js +2 -0
  27. package/dist/web/assets/Shell-BoXDubsc.js +3 -0
  28. package/dist/web/assets/TestCases-DEciDMh1.js +1 -0
  29. package/dist/web/assets/TestData-DY6MVYdx.js +2 -0
  30. package/dist/web/assets/Tosca-BzNnPm0_.js +2 -0
  31. package/dist/web/assets/WhatsNew-7O1MlqCy.js +1 -0
  32. package/dist/web/assets/dataParts-0a9Sjn2u.js +3 -0
  33. package/dist/web/assets/index-C9TchKsF.css +2 -0
  34. package/dist/web/assets/index-DcmN4YB2.js +43 -0
  35. package/dist/web/assets/logos-BnPN8M-S.js +1 -0
  36. package/dist/web/assets/parts-mP2z3tbH.js +1 -0
  37. package/dist/web/assets/productParts-B2wO-b1i.js +1 -0
  38. package/dist/web/assets/qualityParts-ByR8_rNE.js +1 -0
  39. package/dist/web/assets/segmented-BZcnZadS.js +1 -0
  40. package/dist/web/assets/{thread-CHhZJi-Y.js → thread-DLf1W085.js} +2 -2
  41. package/dist/web/assets/usePageChat-lpZh_ziF.js +1 -0
  42. package/dist/web/index.html +3 -3
  43. package/docs/ARCHITECTURE.md +1 -1
  44. package/docs/CONTAINERS.md +1 -1
  45. package/docs/EVIDENCE.md +9 -4
  46. package/docs/GRAPHIFY.md +178 -0
  47. package/docs/PRODUCT_KNOWLEDGE.md +25 -4
  48. package/docs/PRODUCT_VIEWS.md +5 -2
  49. package/docs/prompts/graphify-evidence.md +167 -0
  50. package/docs/user-guide.html +71 -2
  51. package/evals/evidence/domain/base/orders-api/src/report.ts +4 -0
  52. package/evals/evidence/domain/base/orders-api/src/routes/admin.ts +2 -1
  53. package/evals/evidence/domain/cases/bad-function-removed/after/src/workflow.ts +6 -0
  54. package/evals/evidence/domain/cases/bad-function-removed/case.json +14 -0
  55. package/evals/evidence/domain/cases/bad-signature-changed/after/src/workflow.ts +6 -0
  56. package/evals/evidence/domain/cases/bad-signature-changed/case.json +14 -0
  57. package/evals/evidence/domain/cases/bad-state-set-directly/after/src/routes/admin.ts +2 -1
  58. package/evals/evidence/domain/cases/bad-untested-change/after/src/routes/admin.ts +2 -1
  59. package/evals/evidence/domain/cases/bad-untested-helper/after/src/report.ts +4 -0
  60. package/evals/evidence/domain/cases/bad-untested-helper/case.json +14 -0
  61. package/evals/evidence/domain/cases/good-optional-parameter/after/src/workflow.ts +6 -0
  62. package/evals/evidence/domain/cases/good-optional-parameter/case.json +12 -0
  63. package/evals/evidence/domain/cases/good-tested-helper/after/src/clients/payments.ts +8 -0
  64. package/evals/evidence/domain/cases/good-tested-helper/case.json +12 -0
  65. package/forgeqe.example.yaml +14 -1
  66. package/package.json +17 -14
  67. package/prompts/README.md +1 -0
  68. package/prompts/product-investigate.md +1 -1
  69. package/prompts/tosca.md +64 -0
  70. package/py/forgeqe_desktop/models.py +14 -5
  71. package/py/forgeqe_engine/__init__.py +1 -1
  72. package/py/forgeqe_knowledge/graphify_bridge.py +156 -0
  73. package/py/forgeqe_tosca/__init__.py +85 -0
  74. package/py/forgeqe_tosca/__main__.py +50 -0
  75. package/py/forgeqe_tosca/ntir.py +484 -0
  76. package/py/forgeqe_tosca/render.py +128 -0
  77. package/py/forgeqe_tosca/tsu.py +187 -0
  78. package/py/forgeqe_tosca/vendor/toscatsu/LICENSE +26 -0
  79. package/py/forgeqe_tosca/vendor/toscatsu/UPSTREAM +7 -0
  80. package/py/forgeqe_tosca/vendor/toscatsu/gen_tsu.py +735 -0
  81. package/py/forgeqe_tosca/vendor/toscatsu/parse_tsu.py +1979 -0
  82. package/py/forgeqe_tosca/vendor/toscatsu/spec_to_manifest.py +878 -0
  83. package/py/forgeqe_tosca/vendored.py +50 -0
  84. package/skills/tosca-knowledge/SKILL.md +56 -0
  85. package/skills/tosca-knowledge/references/actions-and-values.md +63 -0
  86. package/skills/tosca-knowledge/references/locators.md +29 -0
  87. package/skills/tosca-knowledge/references/mapping-cypress.md +21 -0
  88. package/skills/tosca-knowledge/references/mapping-playwright.md +31 -0
  89. package/skills/tosca-knowledge/references/mapping-selenium-webdriverio.md +26 -0
  90. package/skills/tosca-knowledge/references/ntir.md +46 -0
  91. package/dist/web/assets/Agent-Ol1sf0Me.js +0 -4
  92. package/dist/web/assets/ApiTests-BfN5VysH.js +0 -10
  93. package/dist/web/assets/Chat-Bk2ECB9h.js +0 -3
  94. package/dist/web/assets/Data-DSZ9xkqr.js +0 -3
  95. package/dist/web/assets/Evidence-BVjGRwcr.js +0 -1
  96. package/dist/web/assets/Features-DQEzR0Mz.js +0 -1
  97. package/dist/web/assets/Jobs-chEiiqmE.js +0 -5
  98. package/dist/web/assets/KindPage-D-Jah0cx.js +0 -6
  99. package/dist/web/assets/Migration-DMIBgW27.js +0 -2
  100. package/dist/web/assets/Product-B3buEWja.js +0 -1
  101. package/dist/web/assets/Quality-DuELzB5I.js +0 -1
  102. package/dist/web/assets/Record-DLTuuxTP.js +0 -2
  103. package/dist/web/assets/Regression-Bjz4Xfbo.js +0 -5
  104. package/dist/web/assets/Reports-p8Qp2KwM.js +0 -2
  105. package/dist/web/assets/Response-DGJAmOI0.js +0 -4
  106. package/dist/web/assets/Runs-CnPPwEq7.js +0 -2
  107. package/dist/web/assets/Shell-Molb7AUz.js +0 -3
  108. package/dist/web/assets/TestCases-CUZ-kHja.js +0 -1
  109. package/dist/web/assets/TestData-B3P1fBRO.js +0 -2
  110. package/dist/web/assets/WhatsNew-CdiZ0Eob.js +0 -1
  111. package/dist/web/assets/arrow-down-D5oPK0MM.js +0 -1
  112. package/dist/web/assets/arrow-right-2yt0QgFJ.js +0 -1
  113. package/dist/web/assets/circle-DIklM9wF.js +0 -1
  114. package/dist/web/assets/circle-dashed-BZvX5dyl.js +0 -1
  115. package/dist/web/assets/circle-dot-Cd20PWQi.js +0 -1
  116. package/dist/web/assets/dataParts-D0dUqael.js +0 -3
  117. package/dist/web/assets/index-BC72t3H1.js +0 -43
  118. package/dist/web/assets/index-BiJ_Nvm1.css +0 -2
  119. package/dist/web/assets/keyboard-Dab5j5YB.js +0 -1
  120. package/dist/web/assets/pencil-DeEsXRZX.js +0 -1
  121. package/dist/web/assets/productParts-Ciuentrl.js +0 -1
  122. package/dist/web/assets/qualityParts-CZCG8hDs.js +0 -1
  123. package/dist/web/assets/segmented-BMOboT4H.js +0 -1
  124. package/dist/web/assets/usePageChat-eO0J5JlP.js +0 -1
@@ -0,0 +1,735 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ gen_tsu.py — Playwright/manifest → Tosca .tsu (Tosca-importable).
4
+
5
+ Inverse of parse_tsu.py. Three working modes:
6
+
7
+ # Update an existing test case + its module(s):
8
+ python3 gen_tsu.py --manifest steps.json --base existing.tsu --out new.tsu
9
+
10
+ # New TC referencing existing modules (skeleton supplies envelope):
11
+ python3 gen_tsu.py --manifest steps.json --skeleton project_skeleton.tsu --out new.tsu
12
+
13
+ # Add new TC alongside the existing one (extend mode):
14
+ python3 gen_tsu.py --manifest steps.json --base existing.tsu --extend --out new.tsu
15
+
16
+ # From .spec.ts (Phase B — uses tree-sitter to AST-parse the spec):
17
+ python3 gen_tsu.py --spec test.spec.ts --pages playwright-test/pages \
18
+ --base existing.tsu --out new.tsu
19
+
20
+ Concepts:
21
+ Envelope = TCProject, TCFolder, TCComponentFolder, XModule catalog,
22
+ XModuleAttribute, XParam, ReuseableTestStepBlock, ParameterLayer,
23
+ Parameter, TestStepLibrary, OwnedFile, FileContent.
24
+ TC subtree = TestCase + its TestStepFolders, TestStepFolderReferences,
25
+ XTestSteps, XTestStepValues, TestCaseControlFlowItems,
26
+ TestCaseControlFlowFolders, ParameterLayerReferences,
27
+ ParameterReferences.
28
+
29
+ The emitter rebuilds the TC subtree from the manifest. It preserves
30
+ envelope entities verbatim — XModule.TCProperties blobs, encrypted
31
+ passwords, server-side metadata are pass-through.
32
+
33
+ When the manifest references a module/attribute name not in base/skeleton,
34
+ the emitter mints a fresh XModule + XModuleAttribute + XParam tree. When
35
+ the locator differs, it updates the matching XParam values.
36
+
37
+ Validation:
38
+ python3 gen_tsu.py --manifest complexTest1_steps.json \
39
+ --base complexTest1.tsu --out complexTest1_round.tsu
40
+ python3 parse_tsu.py complexTest1_round.tsu --steps-json
41
+ diff <(jq -S . complexTest1_steps.json) \
42
+ <(jq -S . complexTest1_round_steps.json)
43
+ """
44
+
45
+ import argparse, gzip, json, sys, re, uuid, hashlib, copy
46
+ from pathlib import Path
47
+ from collections import defaultdict, OrderedDict
48
+
49
+
50
+ # ──────────────────────────────────────────────────────────────────────────────
51
+ # Tosca constants — kept aligned with parse_tsu.py
52
+ # ──────────────────────────────────────────────────────────────────────────────
53
+ ACTION_MODE_BY_KEY = {'input':'1', 'set':'37', 'verify':'69', 'waitFor':'101',
54
+ 'bufferRead':'165', 'optionalSet':'517'}
55
+
56
+ # Default Attributes Tosca expects on each ObjectClass (when minting fresh).
57
+ # Values are the empty/zero defaults observed across multiple .tsu samples.
58
+ DEFAULTS = {
59
+ 'TestCase': {
60
+ 'CheckoutWorkspace': '', 'SynchronizationPolicy': '2', 'Description': '',
61
+ 'CheckOutState': '0', 'Revision': '0', 'IncludeForSynchronization': '1',
62
+ 'Pausable': '1', 'TestCaseWorkState': '2', 'IsBusinessTestCase': '0',
63
+ 'DerivedFromName': '', 'TestConfigurationParameters': '',
64
+ },
65
+ 'TestStepFolder': {
66
+ 'Condition': '', 'Path': '', 'BreakInstantiation': '0',
67
+ 'Repetition': '', 'DisabledDescription': '', 'Pausable': '2',
68
+ },
69
+ 'TestStepFolderReference': {
70
+ 'Condition': '', 'Path': '', 'BreakInstantiation': '0',
71
+ 'Repetition': '', 'DisabledDescription': '', 'Pausable': '0',
72
+ },
73
+ 'XTestStep': {
74
+ 'Condition': '', 'Path': '', 'BreakInstantiation': '0',
75
+ 'Repetition': '', 'DisabledDescription': '', 'Pausable': '2',
76
+ 'ReorderAllowed': '0',
77
+ },
78
+ 'XTestStepValue': {
79
+ 'ExplicitName': '', 'DataType': '0', 'ActionMode': '37',
80
+ 'Operator': '0', 'Value': '', 'ActionProperty': '',
81
+ 'DisabledDescription': '', 'Condition': '', 'Path': '',
82
+ },
83
+ 'TestCaseControlFlowItem': {
84
+ 'Condition': '', 'Path': '', 'BreakInstantiation': '0',
85
+ 'Repetition': '', 'DisabledDescription': '', 'Pausable': '0',
86
+ 'StatementType': '1', 'MaximumRepetitions': '',
87
+ },
88
+ 'TestCaseControlFlowFolder': {
89
+ 'Condition': '', 'Path': '', 'BreakInstantiation': '0',
90
+ 'Repetition': '', 'DisabledDescription': '', 'Pausable': '0',
91
+ 'StatementType': '0',
92
+ },
93
+ 'ParameterLayerReference': {},
94
+ 'ParameterReference': {'Value': ''},
95
+ 'XModule': {
96
+ 'CheckoutWorkspace': '', 'SynchronizationPolicy': '2', 'Description': '',
97
+ 'CheckOutState': '1', 'Revision': '0', 'IncludeForSynchronization': '1',
98
+ 'InterfaceType': '0', 'ImplementationType': '', 'TechnicalId': '',
99
+ 'IsAbstract': '0', 'ValueSelectionGroup': '', 'BusinessType': '',
100
+ 'SpecialIcon': '', 'TCProperties': '',
101
+ },
102
+ 'XModuleAttribute': {
103
+ 'ValueSelectionGroup': '', 'Description': '', 'BusinessType': '',
104
+ 'SpecialIcon': '', 'Cardinality': '1-1', 'DefaultDataType': '0',
105
+ 'DefaultActionMode': '37', 'InterfaceType': '2147483647',
106
+ 'DefaultValue': '', 'Visible': '1',
107
+ },
108
+ 'XParam': {'Visible': '1', 'Readonly': '0', 'SupressCopy': '0', 'ParamType': '8'},
109
+ }
110
+
111
+ # Default Assocs structure per class (lists, even when empty)
112
+ ASSOC_KEYS = {
113
+ 'TestCase': ['ConfigurationLinks','Properties','ParentFolder','AttachedFiles','Items'],
114
+ 'TestStepFolder': ['ConfigurationLinks','TestCase','ParentFolder','ExecutionContainerLogs','Items'],
115
+ 'TestStepFolderReference': ['ConfigurationLinks','ParentFolder','ExecutionContainerLogs',
116
+ 'ReusedItem','ParameterLayerReference'],
117
+ 'XTestStep': ['ConfigurationLinks','ParentFolder','ExecutionContainerLogs',
118
+ 'TestStepValues','Module','ExecutionLogs'],
119
+ 'XTestStepValue': ['ConfigurationLinks','TestStep','SubValues','ParentValue',
120
+ 'ModuleAttribute','ExecutionLogs'],
121
+ 'TestCaseControlFlowItem': ['ConfigurationLinks','ParentFolder','ExecutionContainerLogs',
122
+ 'ControlFlowFolders'],
123
+ 'TestCaseControlFlowFolder': ['ConfigurationLinks','ExecutionContainerLogs','Items',
124
+ 'ParentControlFlowItem'],
125
+ 'ParameterLayerReference': ['ConfigurationLinks','TestStepFolderReference',
126
+ 'AllParameterReferences','ParameterLayer'],
127
+ 'ParameterReference': ['ConfigurationLinks','ParameterLayerReference','Parameter'],
128
+ 'XModule': ['ConfigurationLinks','Properties','ParentFolder','AttachedFiles',
129
+ 'Specializations','Attributes','ReferencingAttributes',
130
+ 'UsedAsDefaultSpecializationIn','TestSteps'],
131
+ 'XModuleAttribute': ['ConfigurationLinks','Properties','Module','Attributes',
132
+ 'UIChildren','TestStepValues','ParentAttribute','ParentAttributeFor'],
133
+ 'XParam': ['ConfigurationLinks','ExtendableObject'],
134
+ }
135
+
136
+
137
+ # ──────────────────────────────────────────────────────────────────────────────
138
+ # Surrogate minting — deterministic UUIDs (hash-derived) for stability
139
+ # ──────────────────────────────────────────────────────────────────────────────
140
+ class SurrogateMinter:
141
+ """Mints stable UUIDs from (entity_class, identifying_path) so re-runs on
142
+ equivalent input produce equivalent output. UUIDs are formatted to look
143
+ like Tosca's surrogates (8-4-4-4-12 lowercase hex)."""
144
+
145
+ def __init__(self, salt: str):
146
+ self.salt = salt
147
+ self.counter = 0
148
+
149
+ def mint(self, *parts) -> str:
150
+ self.counter += 1
151
+ material = self.salt + '|' + '|'.join(str(p) for p in parts) + f'|{self.counter}'
152
+ h = hashlib.sha1(material.encode('utf-8')).hexdigest()
153
+ return f"{h[0:8]}-{h[8:12]}-{h[12:16]}-{h[16:20]}-{h[20:32]}"
154
+
155
+
156
+ # ──────────────────────────────────────────────────────────────────────────────
157
+ # Envelope analysis — what's inside the TestCase subtree vs preserved
158
+ # ──────────────────────────────────────────────────────────────────────────────
159
+ def find_test_case(ents) -> dict:
160
+ """Return the (single) TestCase entity. Errors out if 0 or >1."""
161
+ tcs = [e for e in ents.values() if e['ObjectClass'] == 'TestCase']
162
+ if not tcs:
163
+ sys.exit('error: base/skeleton .tsu has no TestCase entity (cannot anchor)')
164
+ if len(tcs) > 1:
165
+ sys.exit(f'error: base/skeleton has {len(tcs)} TestCases — use --extend to add alongside')
166
+ return tcs[0]
167
+
168
+
169
+ def collect_tc_subtree(ents, tc_sur: str) -> set:
170
+ """Walk down from a TestCase, collecting all entity surrogates that belong
171
+ to it (NOT envelope, NOT RTB internals).
172
+
173
+ Edges followed: Items, TestStepValues, SubValues, ControlFlowFolders,
174
+ ParameterLayerReference, AllParameterReferences. We stop at TestStepFolderReference's
175
+ ReusedItem (that's a pointer into the RTB library)."""
176
+
177
+ follow = {'Items', 'TestStepValues', 'SubValues', 'ControlFlowFolders',
178
+ 'ParameterLayerReference', 'AllParameterReferences'}
179
+ seen = set()
180
+ stack = [tc_sur]
181
+ while stack:
182
+ sur = stack.pop()
183
+ if sur in seen: continue
184
+ seen.add(sur)
185
+ e = ents.get(sur)
186
+ if not e: continue
187
+ for k in follow:
188
+ for s in e.get('Assocs', {}).get(k, []):
189
+ if s not in seen:
190
+ stack.append(s)
191
+ return seen
192
+
193
+
194
+ # ──────────────────────────────────────────────────────────────────────────────
195
+ # Module catalog — index XModule + XModuleAttribute by name
196
+ # ──────────────────────────────────────────────────────────────────────────────
197
+ def build_module_catalog(ents):
198
+ """Build {module_name: {sur, attrs: {attr_name: attr_sur}}} index over the envelope."""
199
+ cat = {}
200
+
201
+ # Find each XModule and its attributes
202
+ attr_by_module = defaultdict(list)
203
+ for e in ents.values():
204
+ if e['ObjectClass'] == 'XModuleAttribute':
205
+ for ms in e.get('Assocs', {}).get('Module', []):
206
+ attr_by_module[ms].append(e)
207
+
208
+ # Walk parent_attribute chains so that nested attrs index to their top module
209
+ parent_of = {}
210
+ for e in ents.values():
211
+ if e['ObjectClass'] == 'XModuleAttribute':
212
+ ps = e.get('Assocs', {}).get('ParentAttribute', [])
213
+ if ps: parent_of[e['Surrogate']] = ps[0]
214
+
215
+ for e in ents.values():
216
+ if e['ObjectClass'] != 'XModule': continue
217
+ mod_sur = e['Surrogate']
218
+ mod_name = e['Attributes'].get('Name', '')
219
+ attrs = {}
220
+ # Direct attrs
221
+ for a in attr_by_module.get(mod_sur, []):
222
+ attrs[a['Attributes'].get('Name', '')] = a['Surrogate']
223
+ # Indirect (children whose parent chain leads here)
224
+ for a in ents.values():
225
+ if a['ObjectClass'] != 'XModuleAttribute': continue
226
+ cur = a['Surrogate']
227
+ seen = set()
228
+ while cur in parent_of and cur not in seen:
229
+ seen.add(cur)
230
+ cur = parent_of[cur]
231
+ # cur is now the top-most attr — does it belong to this module?
232
+ for ms in ents.get(cur, {}).get('Assocs', {}).get('Module', []):
233
+ if ms == mod_sur:
234
+ name = a['Attributes'].get('Name', '')
235
+ if name and name not in attrs:
236
+ attrs[name] = a['Surrogate']
237
+ break
238
+ cat[mod_name] = {'sur': mod_sur, 'attrs': attrs}
239
+ return cat
240
+
241
+
242
+ def build_rtb_catalog(ents):
243
+ """Index ReuseableTestStepBlock by Name → {sur, layer_sur, params: {name: sur}}."""
244
+ cat = {}
245
+ for e in ents.values():
246
+ if e['ObjectClass'] != 'ReuseableTestStepBlock': continue
247
+ layer_surs = e.get('Assocs', {}).get('ParameterLayer', [])
248
+ layer_sur = layer_surs[0] if layer_surs else None
249
+ params = {}
250
+ if layer_sur and layer_sur in ents:
251
+ for p_sur in ents[layer_sur].get('Assocs', {}).get('Parameters', []):
252
+ p = ents.get(p_sur)
253
+ if p:
254
+ params[p['Attributes'].get('Name', '')] = p_sur
255
+ cat[e['Attributes'].get('Name', '')] = {
256
+ 'sur': e['Surrogate'], 'layer_sur': layer_sur, 'params': params,
257
+ }
258
+ return cat
259
+
260
+
261
+ # ──────────────────────────────────────────────────────────────────────────────
262
+ # Locator → XParam set (for new XModuleAttribute creation)
263
+ # ──────────────────────────────────────────────────────────────────────────────
264
+ # Maps manifest locator.raw keys → XParam Name. Most are 1:1.
265
+ LOCATOR_RAW_TO_XPARAM = {
266
+ 'Tag': 'Tag', 'Id': 'Id', 'ClassName': 'ClassName', 'Name': 'Name',
267
+ 'AriaLabel': 'AriaLabel', 'Type': 'Type', 'Title': 'Title',
268
+ 'Href': 'Href', 'Src': 'Src', 'XPath': 'XPath', 'AbsoluteXPath': 'AbsoluteXPath',
269
+ 'RelativeId': 'RelativeId', 'PlaceHolder': 'PlaceHolder', 'Value': 'Value',
270
+ 'AlternateText': 'AlternateText',
271
+ }
272
+
273
+
274
+ def locator_raw_to_xparams(raw: dict) -> list:
275
+ """Convert a manifest locator.raw dict to a list of (xparam_name, value) pairs.
276
+ Skips meta keys (_self_healing, _parent_chain) — those are derived."""
277
+ out = []
278
+ for k, v in (raw or {}).items():
279
+ if k.startswith('_') or v is None or v == '':
280
+ continue
281
+ if k in LOCATOR_RAW_TO_XPARAM:
282
+ out.append((LOCATOR_RAW_TO_XPARAM[k], str(v)))
283
+ elif k.startswith('attributes_'):
284
+ out.append((k, str(v)))
285
+ else:
286
+ # passthrough — uncommon XParam name, preserve verbatim
287
+ out.append((k, str(v)))
288
+ return out
289
+
290
+
291
+ # ──────────────────────────────────────────────────────────────────────────────
292
+ # Entity factory
293
+ # ──────────────────────────────────────────────────────────────────────────────
294
+ def mk_entity(cls: str, surrogate: str, attrs_overrides=None, assocs_overrides=None) -> dict:
295
+ """Create an entity with class defaults filled in."""
296
+ attrs = {**DEFAULTS.get(cls, {}), **(attrs_overrides or {})}
297
+ assocs = {k: [] for k in ASSOC_KEYS.get(cls, [])}
298
+ if assocs_overrides:
299
+ for k, v in assocs_overrides.items():
300
+ assocs[k] = v
301
+ return {
302
+ 'ObjectClass': cls,
303
+ 'Surrogate': surrogate,
304
+ 'Attributes': attrs,
305
+ 'Assocs': assocs,
306
+ }
307
+
308
+
309
+ # ──────────────────────────────────────────────────────────────────────────────
310
+ # Builder — walks manifest.steps stream, emits entity tree
311
+ # ──────────────────────────────────────────────────────────────────────────────
312
+ class TCBuilder:
313
+ def __init__(self, tc_sur: str, ents: dict, mod_catalog: dict, rtb_catalog: dict,
314
+ minter: SurrogateMinter, base_buffer_module_name='TBox Set Buffer'):
315
+ self.tc_sur = tc_sur
316
+ self.ents = ents # envelope entities (read-only here)
317
+ self.new_ents = {} # entities we mint
318
+ self.mod_cat = mod_catalog
319
+ self.rtb_cat = rtb_catalog
320
+ self.minter = minter
321
+ self.buffer_module = base_buffer_module_name
322
+ # Stack frames: (parent_sur, items_list_to_append_to)
323
+ # The TestCase frame's items_list is the TC's Assocs.Items list.
324
+ self.stack = []
325
+ self.tc_items_assoc = [] # gets attached to the TC at finalize
326
+ self.stack.append((tc_sur, self.tc_items_assoc))
327
+ self.path = [] # for stable surrogates: stack of names
328
+ # block_depth > 0 means we're inside a block_start..block_end frame and
329
+ # all step/folder/control-flow nodes should be SUPPRESSED (the RTB owns
330
+ # those entities — they're already in the envelope; the manifest only
331
+ # unfurls them for human readability).
332
+ self.block_depth = 0
333
+
334
+ @property
335
+ def cur_parent(self) -> str:
336
+ return self.stack[-1][0]
337
+
338
+ @property
339
+ def cur_items(self) -> list:
340
+ return self.stack[-1][1]
341
+
342
+ def _push(self, sur: str, items_list: list, name=''):
343
+ self.stack.append((sur, items_list))
344
+ self.path.append(name)
345
+
346
+ def _pop(self):
347
+ self.stack.pop()
348
+ if self.path: self.path.pop()
349
+
350
+ def _path_key(self, *extra) -> str:
351
+ return '/'.join(self.path + list(extra))
352
+
353
+ # ── manifest stream handlers ──────────────────────────────────────────
354
+ def handle(self, node: dict):
355
+ t = node.get('type')
356
+ # Suppress all node types except block_start/block_end (and their nested
357
+ # blocks) when we're inside an RTB body. The RTB owns those entities.
358
+ if self.block_depth > 0 and t not in ('block_start', 'block_end'):
359
+ return
360
+ h = getattr(self, f'on_{t}', None)
361
+ if h is None:
362
+ print(f'warning: unknown manifest node type {t!r}; skipping', file=sys.stderr)
363
+ return
364
+ h(node)
365
+
366
+ def on_folder(self, node):
367
+ name = node.get('name', '')
368
+ sur = self.minter.mint('TSF', self._path_key(name))
369
+ ent = mk_entity('TestStepFolder',
370
+ sur,
371
+ attrs_overrides={'Name': name},
372
+ assocs_overrides={
373
+ 'TestCase': [self.tc_sur] if len(self.stack) == 1 else [],
374
+ 'ParentFolder': [self.cur_parent],
375
+ 'Items': [],
376
+ })
377
+ self.new_ents[sur] = ent
378
+ self.cur_items.append(sur)
379
+ self._push(sur, ent['Assocs']['Items'], name)
380
+
381
+ def on_folder_end(self, node):
382
+ self._pop()
383
+
384
+ def on_block_start(self, node):
385
+ block_name = node.get('name', '')
386
+ rtb = self.rtb_cat.get(block_name)
387
+ if not rtb:
388
+ print(f'warning: block_start references unknown ReuseableTestStepBlock {block_name!r}; '
389
+ f'creating reference anyway with no ReusedItem', file=sys.stderr)
390
+ # TestStepFolderReference
391
+ ref_sur = self.minter.mint('TSFR', self._path_key(block_name))
392
+ # ParameterLayerReference
393
+ plr_sur = self.minter.mint('PLR', self._path_key(block_name))
394
+ # ParameterReference children
395
+ param_refs_surs = []
396
+ params_in = node.get('parameters', {}) or {}
397
+ if rtb:
398
+ for pname, pval in params_in.items():
399
+ pname_sur = rtb['params'].get(pname)
400
+ if not pname_sur: continue
401
+ pr_sur = self.minter.mint('PR', self._path_key(block_name, pname))
402
+ pr = mk_entity('ParameterReference', pr_sur,
403
+ attrs_overrides={'Value': str(pval)},
404
+ assocs_overrides={
405
+ 'ParameterLayerReference': [plr_sur],
406
+ 'Parameter': [pname_sur],
407
+ })
408
+ self.new_ents[pr_sur] = pr
409
+ param_refs_surs.append(pr_sur)
410
+ plr = mk_entity('ParameterLayerReference', plr_sur,
411
+ attrs_overrides={'Name': 'Business Parameters'},
412
+ assocs_overrides={
413
+ 'TestStepFolderReference': [ref_sur],
414
+ 'AllParameterReferences': param_refs_surs,
415
+ 'ParameterLayer': [rtb['layer_sur']] if rtb and rtb['layer_sur'] else [],
416
+ })
417
+ self.new_ents[plr_sur] = plr
418
+ ref = mk_entity('TestStepFolderReference', ref_sur,
419
+ attrs_overrides={'Name': ''},
420
+ assocs_overrides={
421
+ 'ParentFolder': [self.cur_parent],
422
+ 'ReusedItem': [rtb['sur']] if rtb else [],
423
+ 'ParameterLayerReference': [plr_sur],
424
+ })
425
+ self.new_ents[ref_sur] = ref
426
+ self.cur_items.append(ref_sur)
427
+ # Push a frame so block_end pops cleanly, and bump block_depth so any
428
+ # nested step/folder/control-flow nodes (the RTB body unfurled by the
429
+ # parser) get suppressed — those entities live in the envelope.
430
+ self._push(ref_sur, [], block_name)
431
+ self.block_depth += 1
432
+
433
+ def on_block_end(self, node):
434
+ self._pop()
435
+ self.block_depth -= 1
436
+
437
+ def on_step(self, node):
438
+ step_name = node.get('name', '')
439
+ module_name = node.get('module', '')
440
+ actions = node.get('actions') or []
441
+
442
+ # Resolve XModule for this step
443
+ mod_entry = self.mod_cat.get(module_name)
444
+ if not mod_entry:
445
+ mod_entry = self._mint_module(module_name)
446
+ module_sur = mod_entry['sur']
447
+
448
+ # XTestStep
449
+ xts_sur = self.minter.mint('XTS', self._path_key(step_name))
450
+ sv_surs = [] # children TestStepValues
451
+ xts = mk_entity('XTestStep', xts_sur,
452
+ attrs_overrides={'Name': step_name},
453
+ assocs_overrides={
454
+ 'ParentFolder': [self.cur_parent],
455
+ 'TestStepValues': sv_surs,
456
+ 'Module': [module_sur],
457
+ })
458
+ self.new_ents[xts_sur] = xts
459
+
460
+ # Each action becomes an XTestStepValue
461
+ for i, act in enumerate(actions):
462
+ sv_sur = self._emit_action(xts_sur, mod_entry, act, i, step_name)
463
+ sv_surs.append(sv_sur)
464
+
465
+ self.cur_items.append(xts_sur)
466
+
467
+ def _emit_action(self, xts_sur, mod_entry, act, idx, step_name) -> str:
468
+ attr_name = act.get('element', '') or '<Buffername>'
469
+ explicit = act.get('explicit_name') or ''
470
+ mode_key = act.get('mode', 'set')
471
+ prop = act.get('property', '') or ''
472
+ value = act.get('value', '')
473
+
474
+ # Resolve XModuleAttribute
475
+ attr_sur = mod_entry['attrs'].get(attr_name)
476
+ if not attr_sur:
477
+ # Mint a new attribute if locator info present
478
+ loc_raw = (act.get('locator') or {}).get('raw') or {}
479
+ attr_sur = self._mint_attribute(mod_entry, attr_name, loc_raw)
480
+
481
+ # ExplicitName: only set when the manifest explicitly carries it
482
+ # (TBox Set Buffer steps where attr=<Buffername>, explicit=<bufferKey>).
483
+ # Otherwise leave empty — Tosca derives the display name from the
484
+ # ModuleAttribute's Name.
485
+ sv_path_id = explicit or attr_name
486
+ sv_sur = self.minter.mint('SV', self._path_key(step_name, str(idx), sv_path_id))
487
+ sv = mk_entity('XTestStepValue', sv_sur,
488
+ attrs_overrides={
489
+ 'ActionMode': ACTION_MODE_BY_KEY.get(mode_key, '37'),
490
+ 'ActionProperty': prop,
491
+ 'Value': str(value) if value is not None else '',
492
+ 'ExplicitName': explicit,
493
+ },
494
+ assocs_overrides={
495
+ 'TestStep': [xts_sur],
496
+ 'ModuleAttribute': [attr_sur] if attr_sur else [],
497
+ })
498
+ self.new_ents[sv_sur] = sv
499
+ return sv_sur
500
+
501
+ def _mint_module(self, name: str) -> dict:
502
+ sur = self.minter.mint('XModule', name)
503
+ ent = mk_entity('XModule', sur,
504
+ attrs_overrides={'Name': name},
505
+ assocs_overrides={'Attributes': []})
506
+ self.new_ents[sur] = ent
507
+ entry = {'sur': sur, 'attrs': {}}
508
+ self.mod_cat[name] = entry
509
+ return entry
510
+
511
+ def _mint_attribute(self, mod_entry: dict, attr_name: str, loc_raw: dict) -> str:
512
+ attr_sur = self.minter.mint('XMA', mod_entry['sur'], attr_name)
513
+ attr = mk_entity('XModuleAttribute', attr_sur,
514
+ attrs_overrides={'Name': attr_name},
515
+ assocs_overrides={
516
+ 'Module': [mod_entry['sur']],
517
+ 'Properties': [],
518
+ })
519
+ self.new_ents[attr_sur] = attr
520
+ # Add the parent module's Attributes list
521
+ if mod_entry['sur'] in self.ents:
522
+ mod_ent = self.ents[mod_entry['sur']]
523
+ mod_ent['Assocs'].setdefault('Attributes', []).append(attr_sur)
524
+ elif mod_entry['sur'] in self.new_ents:
525
+ self.new_ents[mod_entry['sur']]['Assocs']['Attributes'].append(attr_sur)
526
+ # XParams from locator
527
+ for xp_name, xp_value in locator_raw_to_xparams(loc_raw):
528
+ xp_sur = self.minter.mint('XP', attr_sur, xp_name)
529
+ xp = mk_entity('XParam', xp_sur,
530
+ attrs_overrides={'Name': xp_name, 'Value': xp_value},
531
+ assocs_overrides={'ExtendableObject': [attr_sur]})
532
+ self.new_ents[xp_sur] = xp
533
+ attr['Assocs']['Properties'].append(xp_sur)
534
+ mod_entry['attrs'][attr_name] = attr_sur
535
+ return attr_sur
536
+
537
+ # ── control flow ──────────────────────────────────────────────────────
538
+ def on_if(self, node):
539
+ name = node.get('name', '') or ''
540
+ cfi_sur = self.minter.mint('CFI', self._path_key('if', name))
541
+ cfi = mk_entity('TestCaseControlFlowItem', cfi_sur,
542
+ attrs_overrides={'Name': name, 'StatementType': '1'},
543
+ assocs_overrides={
544
+ 'ParentFolder': [self.cur_parent],
545
+ 'ControlFlowFolders': [],
546
+ })
547
+ self.new_ents[cfi_sur] = cfi
548
+ self.cur_items.append(cfi_sur)
549
+ # Synthesize a Condition folder with one Eval step
550
+ cond_expr = node.get('condition', '') or ''
551
+ cond_sur = self.minter.mint('CFF-Cond', self._path_key('if', name))
552
+ cond = mk_entity('TestCaseControlFlowFolder', cond_sur,
553
+ attrs_overrides={'Name': 'Condition', 'StatementType': '0'},
554
+ assocs_overrides={
555
+ 'ParentControlFlowItem': [cfi_sur],
556
+ 'Items': [],
557
+ })
558
+ self.new_ents[cond_sur] = cond
559
+ cfi['Assocs']['ControlFlowFolders'].append(cond_sur)
560
+ # Note: we don't synthesize the TBox Evaluation Tool step inside Condition
561
+ # for v1 — the manifest may not always carry it. Tosca import may flag
562
+ # this; if it does, extend.
563
+ # Push a frame keyed by 'if' so that then/else/loop folders can be added.
564
+ self._push(cfi_sur, cfi['Assocs']['ControlFlowFolders'], 'if:' + name)
565
+
566
+ def on_then_start(self, node):
567
+ self._push_branch('Then')
568
+
569
+ def on_then_end(self, node):
570
+ self._pop()
571
+
572
+ def on_else_start(self, node):
573
+ self._push_branch('Else')
574
+
575
+ def on_else_end(self, node):
576
+ self._pop()
577
+
578
+ def on_loop_start(self, node):
579
+ self._push_branch('Loop')
580
+
581
+ def on_loop_end(self, node):
582
+ self._pop()
583
+
584
+ def _push_branch(self, kind: str):
585
+ cfi_sur = self.cur_parent # frame from on_if
586
+ sur = self.minter.mint(f'CFF-{kind}', self._path_key(kind))
587
+ cff = mk_entity('TestCaseControlFlowFolder', sur,
588
+ attrs_overrides={'Name': kind, 'StatementType': '0'},
589
+ assocs_overrides={
590
+ 'ParentControlFlowItem': [cfi_sur],
591
+ 'Items': [],
592
+ })
593
+ self.new_ents[sur] = cff
594
+ # Append to the CFI's ControlFlowFolders list (cur_items here points at it)
595
+ self.cur_items.append(sur)
596
+ self._push(sur, cff['Assocs']['Items'], kind)
597
+
598
+ def on_if_end(self, node):
599
+ self._pop()
600
+
601
+
602
+ # ──────────────────────────────────────────────────────────────────────────────
603
+ # Top-level orchestration
604
+ # ──────────────────────────────────────────────────────────────────────────────
605
+ def emit(manifest: dict, base_path: Path, out_path: Path,
606
+ is_skeleton: bool, extend: bool):
607
+ raw = json.loads(gzip.open(base_path, 'rb').read())
608
+ ents = OrderedDict((e['Surrogate'], e) for e in raw['Entities'])
609
+
610
+ if is_skeleton:
611
+ # Skeleton mode — there must be no TestCase yet, OR one stub TestCase.
612
+ existing = [e for e in ents.values() if e['ObjectClass'] == 'TestCase']
613
+ if not existing:
614
+ sys.exit('error: --skeleton .tsu has no TestCase shell — '
615
+ 'export one stub test from Tosca to use as skeleton')
616
+ tc = existing[0]
617
+ elif extend:
618
+ sys.exit('error: --extend not yet implemented (next iteration)')
619
+ else:
620
+ tc = find_test_case(ents)
621
+
622
+ # Refresh TestCase Attributes from manifest
623
+ test_name = manifest.get('meta', {}).get('test_name') or tc['Attributes'].get('Name', '')
624
+ tc['Attributes']['Name'] = test_name
625
+
626
+ # Wipe the old subtree
627
+ old_subtree = collect_tc_subtree(ents, tc['Surrogate'])
628
+ old_subtree.discard(tc['Surrogate']) # keep the TC itself, just clear its body
629
+ for s in old_subtree:
630
+ ents.pop(s, None)
631
+
632
+ # Reset TC Items list so we rebuild from scratch
633
+ tc['Assocs']['Items'] = []
634
+
635
+ # Build catalogs
636
+ mod_cat = build_module_catalog(ents)
637
+ rtb_cat = build_rtb_catalog(ents)
638
+
639
+ # Mint deterministic surrogates seeded by the TC name (so re-runs are stable)
640
+ salt = hashlib.sha1(test_name.encode('utf-8')).hexdigest()[:16]
641
+ minter = SurrogateMinter(salt)
642
+
643
+ # Walk manifest
644
+ builder = TCBuilder(tc['Surrogate'], ents, mod_cat, rtb_cat, minter)
645
+ for node in manifest.get('steps', []):
646
+ builder.handle(node)
647
+
648
+ # Synthesize a "TBox Set Buffer" folder for test_data preconditions if the
649
+ # manifest doesn't already have explicit buffer-set steps (it usually does,
650
+ # but for fresh-from-spec manifests we'd need this).
651
+ # For v1, trust the manifest stream.
652
+
653
+ # Attach builder's items list to the TC
654
+ tc['Assocs']['Items'] = builder.tc_items_assoc
655
+
656
+ # Merge new entities
657
+ for s, e in builder.new_ents.items():
658
+ if s in ents:
659
+ print(f'warning: surrogate collision on {s}; keeping new', file=sys.stderr)
660
+ ents[s] = e
661
+
662
+ # Re-fix module Assocs.Attributes for any modules mutated in-place
663
+ # (mk_entity already initializes; _mint_attribute appends to envelope module's list)
664
+
665
+ out_data = {'Entities': list(ents.values())}
666
+ raw_bytes = json.dumps(out_data, ensure_ascii=False).encode('utf-8')
667
+ with gzip.open(out_path, 'wb', compresslevel=6) as f:
668
+ f.write(raw_bytes)
669
+ return len(ents), len(builder.new_ents), len(old_subtree)
670
+
671
+
672
+ # ──────────────────────────────────────────────────────────────────────────────
673
+ # CLI
674
+ # ──────────────────────────────────────────────────────────────────────────────
675
+ def main():
676
+ ap = argparse.ArgumentParser(description=__doc__,
677
+ formatter_class=argparse.RawDescriptionHelpFormatter)
678
+ ap.add_argument('--manifest', help='Path to _steps.json')
679
+ ap.add_argument('--spec', help='Path to .spec.ts (Phase B; not yet wired)')
680
+ ap.add_argument('--pages', help='Page-objects dir (with --spec)')
681
+ g = ap.add_mutually_exclusive_group(required=True)
682
+ g.add_argument('--base', help='Existing .tsu to update (full envelope + TC)')
683
+ g.add_argument('--skeleton', help='Skeleton .tsu (envelope + stub TC)')
684
+ ap.add_argument('--extend', action='store_true',
685
+ help='Add new TC alongside the existing one (use with --base)')
686
+ ap.add_argument('--out', required=True, help='Output .tsu path')
687
+ args = ap.parse_args()
688
+
689
+ if not args.manifest and not args.spec:
690
+ ap.error('must pass --manifest or --spec')
691
+
692
+ base = Path(args.base or args.skeleton)
693
+ out = Path(args.out)
694
+ if not base.exists():
695
+ sys.exit(f'error: {base} not found')
696
+
697
+ if args.spec:
698
+ # Lazy-import to avoid hard dependency on tree-sitter for manifest mode.
699
+ try:
700
+ from spec_to_manifest import build_manifest_from_spec
701
+ except ImportError as e:
702
+ sys.exit(f'error: --spec mode requires tree-sitter ({e}). '
703
+ f'install: pip3 install --user tree_sitter tree-sitter-typescript')
704
+ spec = Path(args.spec)
705
+ if not spec.exists():
706
+ sys.exit(f'error: {spec} not found')
707
+ pages = Path(args.pages) if args.pages else None
708
+ # If a base manifest exists alongside the base .tsu (the parse_tsu
709
+ # output), use it as a context source — provides project name, base_url,
710
+ # all_urls, etc. — so the regenerated .tsu picks them up unchanged.
711
+ base_manifest = None
712
+ sibling = base.with_name(base.stem + '_steps.json')
713
+ if sibling.exists():
714
+ try:
715
+ base_manifest = json.loads(sibling.read_text(encoding='utf-8'))
716
+ except Exception:
717
+ base_manifest = None
718
+ manifest = build_manifest_from_spec(spec, pages, base_manifest)
719
+ else:
720
+ manifest = json.loads(Path(args.manifest).read_text(encoding='utf-8'))
721
+
722
+ total, minted, deleted = emit(
723
+ manifest=manifest,
724
+ base_path=base,
725
+ out_path=out,
726
+ is_skeleton=bool(args.skeleton),
727
+ extend=args.extend,
728
+ )
729
+
730
+ print(f'wrote {out}')
731
+ print(f' {total} total entities, {minted} new, {deleted} replaced from base')
732
+
733
+
734
+ if __name__ == '__main__':
735
+ main()