sdtk-spec-kit 0.9.2 → 0.11.0

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 (88) hide show
  1. package/README.md +1 -1
  2. package/assets/manifest/toolkit-bundle.manifest.json +370 -35
  3. package/assets/manifest/toolkit-bundle.sha256.txt +84 -17
  4. package/assets/toolkit/toolkit/AGENTS.md +2 -1
  5. package/assets/toolkit/toolkit/SDTK_TOOLKIT.md +11 -3
  6. package/assets/toolkit/toolkit/runtimes/claude/CLAUDE_TEMPLATE.md +7 -0
  7. package/assets/toolkit/toolkit/scripts/install-claude-skills.ps1 +46 -0
  8. package/assets/toolkit/toolkit/scripts/install-codex-skills.ps1 +19 -0
  9. package/assets/toolkit/toolkit/skills/sdtk-arch/SKILL.md +1 -1
  10. package/assets/toolkit/toolkit/skills/sdtk-ba/SKILL.md +1 -1
  11. package/assets/toolkit/toolkit/skills/sdtk-customer-qa-sheet/SKILL.md +117 -0
  12. package/assets/toolkit/toolkit/skills/sdtk-customer-qa-sheet/references/PROFILE_TEMPLATE.md +60 -0
  13. package/assets/toolkit/toolkit/skills/sdtk-customer-qa-sheet/scripts/oq_sync.py +349 -0
  14. package/assets/toolkit/toolkit/skills/sdtk-customer-qa-sheet/scripts/test_oq_sync.py +175 -0
  15. package/assets/toolkit/toolkit/skills/sdtk-db-design/SKILL.md +130 -0
  16. package/assets/toolkit/toolkit/skills/sdtk-db-design/references/REVIEW_PROCESS.md +82 -0
  17. package/assets/toolkit/toolkit/skills/sdtk-orchestrator/SKILL.md +2 -0
  18. package/assets/toolkit/toolkit/skills/sdtk-qa/SKILL.md +1 -1
  19. package/assets/toolkit/toolkit/skills/sdtk-screen-design-xlsx/SKILL.md +104 -0
  20. package/assets/toolkit/toolkit/skills/sdtk-screen-design-xlsx/references/REVIEW_AND_MISTAKES.md +63 -0
  21. package/assets/toolkit/toolkit/skills/sdtk-screen-design-xlsx/references/SCR01.json +46 -0
  22. package/assets/toolkit/toolkit/skills/sdtk-screen-design-xlsx/references/SCR01.png +0 -0
  23. package/assets/toolkit/toolkit/skills/sdtk-screen-design-xlsx/references/SPEC_SCHEMA.md +208 -0
  24. package/assets/toolkit/toolkit/skills/sdtk-screen-design-xlsx/references/example_spec.yaml +115 -0
  25. package/assets/toolkit/toolkit/skills/sdtk-screen-design-xlsx/scripts/build_design_xlsx.py +550 -0
  26. package/assets/toolkit/toolkit/skills/sdtk-screen-design-xlsx/scripts/design_spec.py +305 -0
  27. package/assets/toolkit/toolkit/skills/sdtk-screen-design-xlsx/scripts/export_preview.py +111 -0
  28. package/assets/toolkit/toolkit/skills/sdtk-screen-design-xlsx/scripts/export_spec_md.py +181 -0
  29. package/assets/toolkit/toolkit/skills/sdtk-screen-design-xlsx/scripts/make_template.py +113 -0
  30. package/assets/toolkit/toolkit/skills/sdtk-screen-design-xlsx/scripts/test_screen_design.py +198 -0
  31. package/assets/toolkit/toolkit/skills/sdtk-screen-design-xlsx/scripts/uia_dump.py +64 -0
  32. package/assets/toolkit/toolkit/skills/sdtk-screen-design-xlsx/scripts/validate_spec.py +260 -0
  33. package/assets/toolkit/toolkit/skills/sdtk-session-handoff/SKILL.md +76 -0
  34. package/assets/toolkit/toolkit/skills/sdtk-session-handoff/references/HANDOFF_TEMPLATE.md +63 -0
  35. package/assets/toolkit/toolkit/skills/sdtk-session-handoff/references/MOVING_A_PROJECT.md +18 -0
  36. package/assets/toolkit/toolkit/skills/sdtk-session-handoff/scripts/dirty_files.py +133 -0
  37. package/assets/toolkit/toolkit/skills/sdtk-session-handoff/scripts/test_dirty_files.py +94 -0
  38. package/assets/toolkit/toolkit/skills/sdtk-smoke-test-spec/SKILL.md +69 -0
  39. package/assets/toolkit/toolkit/skills/sdtk-smoke-test-spec/scripts/test_validate_smoke_test.py +58 -0
  40. package/assets/toolkit/toolkit/skills/sdtk-smoke-test-spec/scripts/validate_smoke_test.py +152 -0
  41. package/assets/toolkit/toolkit/skills/sdtk-test-case-xlsx/SKILL.md +297 -0
  42. package/assets/toolkit/toolkit/skills/sdtk-test-case-xlsx/prompts/agent_brief_template.md +59 -0
  43. package/assets/toolkit/toolkit/skills/sdtk-test-case-xlsx/scripts/check_coverage.py +50 -0
  44. package/assets/toolkit/toolkit/skills/sdtk-test-case-xlsx/scripts/extract_sources.py +224 -0
  45. package/assets/toolkit/toolkit/skills/sdtk-test-case-xlsx/scripts/merge_parts.py +78 -0
  46. package/assets/toolkit/toolkit/skills/sdtk-test-case-xlsx/scripts/render_testcase.py +421 -0
  47. package/assets/toolkit/toolkit/skills/sdtk-test-case-xlsx/scripts/template_set.py +57 -0
  48. package/assets/toolkit/toolkit/skills/sdtk-test-case-xlsx/scripts/test_write_results.py +89 -0
  49. package/assets/toolkit/toolkit/skills/sdtk-test-case-xlsx/scripts/write_results.py +126 -0
  50. package/assets/toolkit/toolkit/skills/sdtk-xlsx-safe-edit/SKILL.md +149 -0
  51. package/assets/toolkit/toolkit/skills/sdtk-xlsx-safe-edit/scripts/pictures.py +68 -0
  52. package/assets/toolkit/toolkit/skills/sdtk-xlsx-safe-edit/scripts/test_metadata.py +76 -0
  53. package/assets/toolkit/toolkit/skills/sdtk-xlsx-safe-edit/scripts/test_pictures.py +55 -0
  54. package/assets/toolkit/toolkit/skills/sdtk-xlsx-safe-edit/scripts/xlsafe.py +137 -0
  55. package/assets/toolkit/toolkit/skills/sdtk-xlsx-safe-edit/scripts/xlsx_xml_edit.py +217 -0
  56. package/assets/toolkit/toolkit/skills/skills.catalog.yaml +172 -0
  57. package/assets/toolkit/toolkit/skills-claude/arch/SKILL.md +1 -1
  58. package/assets/toolkit/toolkit/skills-claude/ba/SKILL.md +1 -1
  59. package/assets/toolkit/toolkit/skills-claude/customer-qa-sheet/SKILL.md +115 -0
  60. package/assets/toolkit/toolkit/skills-claude/db-design/SKILL.md +128 -0
  61. package/assets/toolkit/toolkit/skills-claude/orchestrator/SKILL.md +1 -1
  62. package/assets/toolkit/toolkit/skills-claude/qa/SKILL.md +1 -1
  63. package/assets/toolkit/toolkit/skills-claude/screen-design-xlsx/SKILL.md +101 -0
  64. package/assets/toolkit/toolkit/skills-claude/session-handoff/SKILL.md +74 -0
  65. package/assets/toolkit/toolkit/skills-claude/smoke-test-spec/SKILL.md +66 -0
  66. package/assets/toolkit/toolkit/skills-claude/test-case-xlsx/SKILL.md +294 -0
  67. package/assets/toolkit/toolkit/skills-claude/xlsx-safe-edit/SKILL.md +146 -0
  68. package/assets/toolkit/toolkit/templates/README.md +11 -1
  69. package/assets/toolkit/toolkit/templates/docs/database/DATABASE_SPEC_TEMPLATE.md +14 -0
  70. package/assets/toolkit/toolkit/templates/screen-design-xlsx/ja-default/TEMPLATE.md +247 -0
  71. package/assets/toolkit/toolkit/templates/screen-design-xlsx/ja-default/template.xlsx +0 -0
  72. package/assets/toolkit/toolkit/templates/smoke-test/PROFILE_TEMPLATE.md +36 -0
  73. package/assets/toolkit/toolkit/templates/smoke-test/vi-default/AUTHORING_RULES.md +32 -0
  74. package/assets/toolkit/toolkit/templates/smoke-test/vi-default/SMOKE_TEST_TEMPLATE.md +147 -0
  75. package/assets/toolkit/toolkit/templates/smoke-test/vi-default/TEMPLATE.md +25 -0
  76. package/assets/toolkit/toolkit/templates/test-case-xlsx/PROFILE_TEMPLATE.md +78 -0
  77. package/assets/toolkit/toolkit/templates/test-case-xlsx/ja-default/TEMPLATE.md +28 -0
  78. package/assets/toolkit/toolkit/templates/test-case-xlsx/ja-default/viewpoints/README.md +73 -0
  79. package/assets/toolkit/toolkit/templates/test-case-xlsx/ja-default/viewpoints/_template.xlsx +0 -0
  80. package/assets/toolkit/toolkit/templates/test-case-xlsx/ja-default/viewpoints/common/common.xlsx +0 -0
  81. package/assets/toolkit/toolkit/templates/test-case-xlsx/ja-default/viewpoints/platform/mobile_app.xlsx +0 -0
  82. package/assets/toolkit/toolkit/templates/test-case-xlsx/ja-default/viewpoints/platform/smartphone_web.xlsx +0 -0
  83. package/assets/toolkit/toolkit/templates/test-case-xlsx/ja-default/viewpoints/platform/web.xlsx +0 -0
  84. package/assets/toolkit/toolkit/templates/test-case-xlsx/ja-default/viewpoints/platform/windows_app.xlsx +0 -0
  85. package/assets/toolkit/toolkit/templates/test-case-xlsx/ja-default//343/203/206/343/202/271/343/203/210/344/273/225/346/247/230/346/233/270/344/275/234/346/210/220/343/203/253/343/203/274/343/203/253.md +514 -0
  86. package/assets/toolkit/toolkit/templates/test-case-xlsx/ja-default//343/203/206/343/202/271/343/203/210/344/273/225/346/247/230/346/233/270/351/233/233/345/236/213.xlsx +0 -0
  87. package/package.json +1 -1
  88. package/src/lib/scope.js +6 -4
@@ -0,0 +1,349 @@
1
+ #!/usr/bin/env python3
2
+ """Bridge between the open questions (OQ-xx) of SDTK specs and a customer's hand-maintained Q&A workbook.
3
+
4
+ oq_sync.py oqs --spec BA_SPEC.md list OQ rows of the spec(s) (id, status, question)
5
+ oq_sync.py sheet --profile qa_sheet_profile.md dump the sheet's rows (read-only)
6
+ oq_sync.py export --profile P --spec BA_SPEC.md [--out f] draft of rows for OPEN OQs not yet in the sheet
7
+ oq_sync.py answers --profile P [--snapshot s.json] [--save-snapshot s.json]
8
+ answered rows changed since the snapshot, keyed by OQ id
9
+ oq_sync.py write --profile P --rows approved.json [--apply]
10
+ write approved rows (XML route; dry-run without --apply)
11
+
12
+ The profile is the project's qa_sheet_profile.md; the script reads its first ```json block (keys below). Rows are
13
+ matched to OQs by id (an OQ column, or "[OQ-07]" in the question text) — never by position. The workbook is only
14
+ read with openpyxl; `write` goes through sdtk-xlsx-safe-edit's xlsx_xml_edit (other parts stay byte-identical).
15
+
16
+ Profile JSON keys: workbook, sheet, header_row, first_data_row, template_row (optional, default = last filled
17
+ row), columns {no, question, answer, oq (optional), plus any others used in approved rows}, no_format (e.g.
18
+ "00000" or "int"), oq_tag (default "[{id}]").
19
+ """
20
+ from __future__ import annotations
21
+
22
+ import argparse
23
+ import hashlib
24
+ import json
25
+ import os
26
+ import re
27
+ import shutil
28
+ import sys
29
+ import tempfile
30
+
31
+ HERE = os.path.dirname(os.path.abspath(__file__))
32
+ for _name in ("sdtk-xlsx-safe-edit", "xlsx-safe-edit"): # toolkit layout / Claude skills layout
33
+ _candidate = os.path.join(HERE, "..", "..", _name, "scripts")
34
+ if os.path.isdir(_candidate):
35
+ sys.path.insert(0, os.path.normpath(_candidate))
36
+ break
37
+
38
+ OQ_ID = re.compile(r"\bOQ-\d+\b")
39
+
40
+
41
+ class SyncError(RuntimeError):
42
+ pass
43
+
44
+
45
+ # ---------------------------------------------------------------------------------------------------- spec side
46
+ def _cells(line):
47
+ return [c.strip() for c in line.strip().strip("|").split("|")]
48
+
49
+
50
+ def read_oqs(spec_paths):
51
+ """OQ rows from every markdown table whose header has a Q-ID / ID column and a Question column."""
52
+ out = []
53
+ for path in spec_paths:
54
+ with open(path, encoding="utf-8") as f:
55
+ lines = f.read().splitlines()
56
+ header = None
57
+ for i, line in enumerate(lines):
58
+ if not line.lstrip().startswith("|"):
59
+ header = None
60
+ continue
61
+ cells = _cells(line)
62
+ if header is None:
63
+ low = [c.lower() for c in cells]
64
+ idc = next((j for j, c in enumerate(low) if c in ("q-id", "id", "oq", "oq id", "oq-id")), None)
65
+ qc = next((j for j, c in enumerate(low) if c.startswith("question")), None)
66
+ if idc is not None and qc is not None:
67
+ st = next((j for j, c in enumerate(low) if c.startswith("status")), None)
68
+ header = (idc, qc, st)
69
+ continue
70
+ if set("".join(cells)) <= set("-: "):
71
+ continue
72
+ idc, qc, st = header
73
+ if idc >= len(cells) or not OQ_ID.fullmatch(cells[idc]):
74
+ continue
75
+ out.append({"id": cells[idc], "question": cells[qc] if qc < len(cells) else "",
76
+ "status": (cells[st] if st is not None and st < len(cells) else "").upper(),
77
+ "source": f"{path}:{i + 1}"})
78
+ seen = {}
79
+ for oq in out:
80
+ if oq["id"] in seen:
81
+ raise SyncError(f"{oq['id']} appears twice: {seen[oq['id']]} and {oq['source']}")
82
+ seen[oq["id"]] = oq["source"]
83
+ return out
84
+
85
+
86
+ # ---------------------------------------------------------------------------------------------------- sheet side
87
+ def load_profile(path):
88
+ with open(path, encoding="utf-8") as f:
89
+ text = f.read()
90
+ m = re.search(r"```json\s*\n(.*?)\n```", text, re.S)
91
+ if not m:
92
+ raise SyncError(f"{path}: no ```json block (see the profile template)")
93
+ prof = json.loads(m.group(1))
94
+ for key in ("workbook", "sheet", "header_row", "first_data_row", "columns"):
95
+ if key not in prof:
96
+ raise SyncError(f"profile: missing key {key!r}")
97
+ for key in ("no", "question", "answer"):
98
+ if key not in prof["columns"]:
99
+ raise SyncError(f"profile: columns.{key} missing")
100
+ base = os.path.dirname(os.path.abspath(path))
101
+ if not os.path.isabs(prof["workbook"]):
102
+ candidates = [os.path.join(base, prof["workbook"]), os.path.abspath(prof["workbook"])]
103
+ prof["workbook"] = next((c for c in candidates if os.path.exists(c)), candidates[0])
104
+ prof.setdefault("oq_tag", "[{id}]")
105
+ prof.setdefault("no_format", "int")
106
+ return prof
107
+
108
+
109
+ def _text(v):
110
+ if v is None:
111
+ return ""
112
+ if isinstance(v, float) and v.is_integer():
113
+ v = int(v)
114
+ return str(v).strip()
115
+
116
+
117
+ def read_sheet(prof):
118
+ """Rows from first_data_row to the last row with any mapped column filled. Read-only."""
119
+ from openpyxl import load_workbook
120
+ tmp = tempfile.mkdtemp(prefix="oqsync-")
121
+ try:
122
+ copy = os.path.join(tmp, "read.xlsx")
123
+ shutil.copy2(prof["workbook"], copy) # never hold the person's file open
124
+ wb = load_workbook(copy, data_only=True) # not read_only: that mode trusts <dimension>
125
+ ws = wb[prof["sheet"]]
126
+ cols = prof["columns"]
127
+ rows = []
128
+ for r, row in enumerate(ws.iter_rows(min_row=prof["first_data_row"], values_only=True), prof["first_data_row"]):
129
+ get = lambda col: _text(row[_col_index(col)] if _col_index(col) < len(row) else None) # noqa: E731
130
+ rec = {k: get(c) for k, c in cols.items()}
131
+ rec["row"] = r
132
+ ids = set(OQ_ID.findall(rec.get("oq", "")))
133
+ ids |= set(OQ_ID.findall(rec.get("question", "")))
134
+ rec["oq_ids"] = sorted(ids)
135
+ rows.append(rec)
136
+ while rows and not any(rows[-1][k] for k in cols if k != "no"):
137
+ rows.pop()
138
+ return rows
139
+ finally:
140
+ shutil.rmtree(tmp, ignore_errors=True)
141
+
142
+
143
+ def _col_index(col):
144
+ n = 0
145
+ for ch in col:
146
+ n = n * 26 + ord(ch) - 64
147
+ return n - 1
148
+
149
+
150
+ def format_no(prof, n):
151
+ fmt = prof["no_format"]
152
+ return str(n).zfill(len(fmt)) if fmt.strip("0") == "" and fmt else n
153
+
154
+
155
+ def next_number(rows):
156
+ """First pre-numbered empty row, else last number + 1."""
157
+ for rec in rows:
158
+ if rec["no"] and not rec["question"]:
159
+ return int(re.sub(r"\D", "", rec["no"]) or 0), rec["row"]
160
+ nums = [int(re.sub(r"\D", "", r["no"])) for r in rows if re.sub(r"\D", "", r["no"])]
161
+ last_row = rows[-1]["row"] if rows else None
162
+ return (max(nums) + 1 if nums else 1), (last_row + 1 if last_row else None)
163
+
164
+
165
+ # ---------------------------------------------------------------------------------------------------- commands
166
+ def cmd_export(prof, spec_paths, out):
167
+ oqs = read_oqs(spec_paths)
168
+ rows = read_sheet(prof)
169
+ in_sheet = {i: r for r in rows for i in r["oq_ids"]}
170
+ number, row = next_number(rows)
171
+ lines = [f"# Q&A sheet draft — {os.path.basename(prof['workbook'])} / {prof['sheet']}", "",
172
+ "Draft only. Rewrite each question in the sheet's style and language (SKILL.md A.4), check related rows,",
173
+ "then get the person's approval before `write`.", "",
174
+ "\"Possibly related\" lists rows sharing words with the OQ — a hint for step A.3, not a verdict: rows",
175
+ "written before OQ ids were used carry no id, so search the sheet yourself too.", "",
176
+ "| OQ | Status in spec | In sheet | Possibly related (No, answered?) | Proposed No | Sheet row | Question (spec wording) |",
177
+ "|---|---|---|---|---|---|---|"]
178
+ proposed = []
179
+ for oq in oqs:
180
+ if oq["id"] in in_sheet:
181
+ r = in_sheet[oq["id"]]
182
+ state = f"No {r['no']} (row {r['row']}){' — answered' if r['answer'] else ''}"
183
+ lines.append(f"| {oq['id']} | {oq['status'] or '?'} | {state} | — | — | — | {oq['question']} |")
184
+ continue
185
+ if oq["status"] and oq["status"] != "OPEN":
186
+ lines.append(f"| {oq['id']} | {oq['status']} | no | — | — (not open) | — | {oq['question']} |")
187
+ continue
188
+ hints = related_rows(oq["question"], rows)
189
+ hint = ", ".join(f"No {r['no']} ({'answered' if r['answer'] else 'open'})" for r in hints[:3]) or "none"
190
+ no = format_no(prof, number)
191
+ lines.append(f"| {oq['id']} | {oq['status'] or '?'} | no | {hint} | {no} | {row} | {oq['question']} |")
192
+ proposed.append({"oq": oq["id"], "no": no, "row": row, "question": oq["question"], "source": oq["source"],
193
+ "related": [r["no"] for r in hints]})
194
+ number += 1
195
+ row = row + 1 if row else None
196
+ lines += ["", "Proposed rows (fill `values` per profile column, then save as the approved rows file):", "",
197
+ "```json", json.dumps([{"row": p["row"], "oq": p["oq"],
198
+ "values": {"no": p["no"], "question": prof["oq_tag"].format(id=p["oq"]) + " ",
199
+ **({"oq": p["oq"]} if "oq" in prof["columns"] else {})}}
200
+ for p in proposed], ensure_ascii=False, indent=2), "```"]
201
+ text = "\n".join(lines) + "\n"
202
+ if out:
203
+ with open(out, "w", encoding="utf-8") as f:
204
+ f.write(text)
205
+ return text, proposed
206
+
207
+
208
+ _STOP = {"what", "which", "when", "where", "there", "their", "this", "that", "with", "from", "have", "should",
209
+ "would", "could", "does", "will", "shall", "about", "into", "than", "then", "them", "they", "also", "only"}
210
+
211
+
212
+ def _tokens(text):
213
+ """Words of 4+ letters (minus a few function words) and CJK bigrams — enough to point at likely duplicates."""
214
+ text = text.lower()
215
+ words = {w for w in re.findall(r"[a-z0-9]{4,}", text) if w not in _STOP}
216
+ words |= {w[:-1] for w in words if w.endswith("s")}
217
+ cjk = re.findall(r"[\u3040-\u30ff\u3400-\u9fff]+", text)
218
+ return words | {run[i:i + 2] for run in cjk for i in range(len(run) - 1)}
219
+
220
+
221
+ def related_rows(question, rows, minimum=2):
222
+ """Rows of the sheet sharing at least `minimum` tokens with the question, best first. A hint, not a verdict."""
223
+ mine = _tokens(question)
224
+ scored = []
225
+ for rec in rows:
226
+ if not rec.get("question"):
227
+ continue
228
+ shared = len(mine & _tokens(" ".join(rec.get(k, "") for k in rec if k not in ("row", "oq_ids", "no"))))
229
+ if shared >= minimum:
230
+ scored.append((shared, rec["row"], rec))
231
+ return [rec for _, _, rec in sorted(scored, key=lambda t: (-t[0], t[1]))]
232
+
233
+
234
+ def _digest(rec):
235
+ return hashlib.sha256(rec["answer"].encode("utf-8")).hexdigest()[:16]
236
+
237
+
238
+ def cmd_answers(prof, snapshot, save):
239
+ rows = read_sheet(prof)
240
+ old = {}
241
+ if snapshot and os.path.exists(snapshot):
242
+ with open(snapshot, encoding="utf-8") as f:
243
+ old = json.load(f)
244
+ changed = []
245
+ for rec in rows:
246
+ if not rec["answer"]:
247
+ continue
248
+ key = rec["no"] or f"row{rec['row']}"
249
+ if old.get(key) == _digest(rec):
250
+ continue
251
+ changed.append({"no": rec["no"], "row": rec["row"], "oq_ids": rec["oq_ids"], "question": rec["question"],
252
+ "answer": rec["answer"], "unmatched": not rec["oq_ids"]})
253
+ if save:
254
+ with open(save, "w", encoding="utf-8") as f:
255
+ json.dump({(r["no"] or f"row{r['row']}"): _digest(r) for r in rows if r["answer"]}, f, indent=1, sort_keys=True)
256
+ return changed
257
+
258
+
259
+ def cmd_write(prof, rows_path, apply):
260
+ from xlsx_xml_edit import SheetXml, package_diff
261
+ with open(rows_path, encoding="utf-8") as f:
262
+ approved = json.load(f)
263
+ current = read_sheet(prof)
264
+ by_row = {r["row"]: r for r in current}
265
+ present = {i for r in current for i in r["oq_ids"]}
266
+ cols = prof["columns"]
267
+ plan = []
268
+ for item in approved:
269
+ r, values = item["row"], item["values"]
270
+ if item.get("oq") in present:
271
+ raise SyncError(f"{item['oq']} is already in the sheet — re-run export")
272
+ existing = by_row.get(r)
273
+ if existing and existing["question"]:
274
+ raise SyncError(f"row {r} already holds a question (No {existing['no']}) — never overwrite")
275
+ if item.get("oq") and item["oq"] not in values.get("question", "") + values.get("oq", ""):
276
+ raise SyncError(f"row {r}: OQ id {item['oq']} must be in the question text or the oq column")
277
+ unknown = set(values) - set(cols)
278
+ if unknown:
279
+ raise SyncError(f"row {r}: columns not in the profile: {sorted(unknown)}")
280
+ if values.get("answer"):
281
+ raise SyncError(f"row {r}: the answer column is the customer's — leave it empty")
282
+ plan.append((r, {cols[k]: v for k, v in values.items()}))
283
+ if not apply:
284
+ return {"dry_run": True, "rows": [{"row": r, "cells": v} for r, v in plan]}
285
+ src = prof["workbook"]
286
+ lock = os.path.join(os.path.dirname(src), "~$" + os.path.basename(src))
287
+ if os.path.exists(lock):
288
+ raise SyncError(f"lock file {lock} exists — the workbook may be open; ask the person to close it")
289
+ backup = src + ".bak"
290
+ shutil.copy2(src, backup)
291
+ last_filled = max((x["row"] for x in current if x["question"]), default=prof["first_data_row"])
292
+ template_row = prof.get("template_row") or last_filled
293
+ sheet = SheetXml(src, prof["sheet"])
294
+ old_last = max([int(n) for n in re.findall(r'<row r="(\d+)"', sheet.xml)] + [last_filled])
295
+ for r, cells in plan:
296
+ sheet.set_row(r, cells, template_row)
297
+ new_last = max(r for r, _ in plan)
298
+ if new_last > old_last:
299
+ sheet.extend_ranges(old_last, new_last) # DV / CF / dimension that end at the last row grow with it
300
+ fd, out = tempfile.mkstemp(suffix=".xlsx", dir=os.path.dirname(src))
301
+ os.close(fd)
302
+ sheet.save(out)
303
+ sheet.zf.close()
304
+ changed = package_diff(src, out)
305
+ if changed != [sheet.part]:
306
+ os.remove(out)
307
+ raise SyncError(f"unexpected parts changed: {changed} — nothing written")
308
+ os.replace(out, src)
309
+ after = {x["row"]: x for x in read_sheet(prof)}
310
+ for r, _ in plan:
311
+ if not after.get(r, {}).get("question"):
312
+ raise SyncError(f"row {r} reads back empty — restore {backup}")
313
+ return {"dry_run": False, "backup": backup, "rows": [r for r, _ in plan], "changed_parts": changed}
314
+
315
+
316
+ def main(argv=None):
317
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
318
+ sub = ap.add_subparsers(dest="cmd", required=True)
319
+ p = sub.add_parser("oqs"); p.add_argument("--spec", nargs="+", required=True)
320
+ p = sub.add_parser("sheet"); p.add_argument("--profile", required=True)
321
+ p = sub.add_parser("export"); p.add_argument("--profile", required=True)
322
+ p.add_argument("--spec", nargs="+", required=True); p.add_argument("--out")
323
+ p = sub.add_parser("answers"); p.add_argument("--profile", required=True)
324
+ p.add_argument("--snapshot"); p.add_argument("--save-snapshot")
325
+ p = sub.add_parser("write"); p.add_argument("--profile", required=True)
326
+ p.add_argument("--rows", required=True); p.add_argument("--apply", action="store_true")
327
+ a = ap.parse_args(argv)
328
+ try:
329
+ if a.cmd == "oqs":
330
+ res = read_oqs(a.spec)
331
+ elif a.cmd == "sheet":
332
+ res = read_sheet(load_profile(a.profile))
333
+ elif a.cmd == "export":
334
+ text, _ = cmd_export(load_profile(a.profile), a.spec, a.out)
335
+ print(text)
336
+ return 0
337
+ elif a.cmd == "answers":
338
+ res = cmd_answers(load_profile(a.profile), a.snapshot, a.save_snapshot)
339
+ else:
340
+ res = cmd_write(load_profile(a.profile), a.rows, a.apply)
341
+ except (SyncError, KeyError, FileNotFoundError) as e:
342
+ print(f"ERROR: {e}", file=sys.stderr)
343
+ return 2
344
+ print(json.dumps(res, ensure_ascii=False, indent=1))
345
+ return 0
346
+
347
+
348
+ if __name__ == "__main__":
349
+ sys.exit(main())
@@ -0,0 +1,175 @@
1
+ """Tests for oq_sync.py on a fictional Q&A workbook built here (openpyxl only creates the fixture)."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import os
6
+ import shutil
7
+ import sys
8
+ import tempfile
9
+ import unittest
10
+ import zipfile
11
+
12
+ HERE = os.path.dirname(os.path.abspath(__file__))
13
+ sys.path.insert(0, HERE)
14
+ import oq_sync # noqa: E402
15
+
16
+ try:
17
+ import openpyxl # noqa: F401
18
+ HAVE_OPENPYXL = True
19
+ except ImportError:
20
+ HAVE_OPENPYXL = False
21
+
22
+
23
+ def read_bytes(path):
24
+ with open(path, "rb") as f:
25
+ return f.read()
26
+
27
+ SPEC = """# BA SPEC: DEMO
28
+ ### 5.2 Open Questions
29
+
30
+ | No | Q-ID | Question | Type | Priority | Decision Owner (PM/User) | Status (OPEN/RESOLVED) | Notes/Options | Resolution |
31
+ | ---: | --- | --- | --- | --- | --- | --- | --- | --- |
32
+ | 1 | OQ-01 | Maximum attachments per order? | Business | High | User | OPEN | 5 / 10 | TBD |
33
+ | 2 | OQ-02 | Keep deleted orders for audit? | Business | Med | User | OPEN | | TBD |
34
+ | 3 | OQ-03 | Currency format | Business | Low | PM | RESOLVED | | JPY only |
35
+ | 4 | OQ-04 | Export encoding? | Business | Low | User | OPEN | | TBD |
36
+ """
37
+
38
+ PROFILE = """# Q&A sheet profile: demo
39
+ ```json
40
+ {"workbook": "qa.xlsx", "sheet": "QA", "header_row": 2, "first_data_row": 3, "no_format": "000",
41
+ "columns": {"no": "A", "category": "B", "question": "C", "answer": "D", "asked_by": "E"}}
42
+ ```
43
+ """
44
+
45
+
46
+ def make_workbook(path):
47
+ from openpyxl import Workbook
48
+ from openpyxl.worksheet.datavalidation import DataValidation
49
+ wb = Workbook()
50
+ ws = wb.active
51
+ ws.title = "QA"
52
+ ws["A1"] = "Q&A"
53
+ for col, head in zip("ABCDE", ("No", "Category", "Question", "Answer", "Asked by")):
54
+ ws[f"{col}2"] = head
55
+ ws.append(["001", "Spec", "[OQ-02] Keep deleted orders?", "Yes, 1 year.", "us"])
56
+ ws.append(["002", "Spec", "Login screen colour?", "", "us"])
57
+ ws.append(["003", "Spec", "", "", ""]) # pre-numbered empty row
58
+ dv = DataValidation(type="list", formula1='"Spec,Other"')
59
+ dv.add("B3:B5")
60
+ ws.add_data_validation(dv)
61
+ other = wb.create_sheet("Other")
62
+ other["A1"] = "owned by someone else"
63
+ wb.save(path)
64
+
65
+
66
+ @unittest.skipUnless(HAVE_OPENPYXL, "openpyxl not installed")
67
+ class OqSyncTests(unittest.TestCase):
68
+ def setUp(self):
69
+ self.tmp = tempfile.mkdtemp()
70
+ self.spec = os.path.join(self.tmp, "BA_SPEC_DEMO.md")
71
+ self.profile = os.path.join(self.tmp, "qa_sheet_profile.md")
72
+ self.book = os.path.join(self.tmp, "qa.xlsx")
73
+ for path, text in ((self.spec, SPEC), (self.profile, PROFILE)):
74
+ with open(path, "w", encoding="utf-8") as f:
75
+ f.write(text)
76
+ make_workbook(self.book)
77
+ self.prof = oq_sync.load_profile(self.profile)
78
+
79
+ def tearDown(self):
80
+ shutil.rmtree(self.tmp, ignore_errors=True)
81
+
82
+ def test_reads_oq_rows_with_status(self):
83
+ oqs = oq_sync.read_oqs([self.spec])
84
+ self.assertEqual([o["id"] for o in oqs], ["OQ-01", "OQ-02", "OQ-03", "OQ-04"])
85
+ self.assertEqual(oqs[2]["status"], "RESOLVED")
86
+
87
+ def test_duplicate_oq_id_is_an_error(self):
88
+ with open(self.spec, "a", encoding="utf-8") as f:
89
+ f.write("| 5 | OQ-01 | again | B | L | PM | OPEN | | |\n")
90
+ with self.assertRaises(oq_sync.SyncError):
91
+ oq_sync.read_oqs([self.spec])
92
+
93
+ def test_export_proposes_only_open_oqs_not_in_sheet_starting_at_the_prenumbered_row(self):
94
+ text, proposed = oq_sync.cmd_export(self.prof, [self.spec], None)
95
+ self.assertEqual([p["oq"] for p in proposed], ["OQ-01", "OQ-04"])
96
+ self.assertEqual((proposed[0]["no"], proposed[0]["row"]), ("003", 5))
97
+ self.assertEqual((proposed[1]["no"], proposed[1]["row"]), ("004", 6))
98
+ self.assertIn("No 001 (row 3) — answered", text) # OQ-02 found by its tag, not by position
99
+ self.assertIn("not open", text) # OQ-03 resolved
100
+
101
+ def test_export_points_at_untagged_rows_on_the_same_topic(self):
102
+ with open(self.spec, "a", encoding="utf-8") as f:
103
+ f.write("| 5 | OQ-05 | Which colour does the login screen use? | UI | Low | User | OPEN | | TBD |\n")
104
+ text, proposed = oq_sync.cmd_export(self.prof, [self.spec], None)
105
+ by_id = {p["oq"]: p for p in proposed}
106
+ self.assertEqual(by_id["OQ-05"]["related"], ["002"])
107
+ self.assertEqual(by_id["OQ-04"]["related"], [])
108
+ self.assertIn("No 002 (open)", text)
109
+
110
+ def test_answers_are_keyed_by_oq_and_filtered_by_snapshot(self):
111
+ snap = os.path.join(self.tmp, "snap.json")
112
+ first = oq_sync.cmd_answers(self.prof, snap, snap)
113
+ self.assertEqual([(a["no"], a["oq_ids"]) for a in first], [("001", ["OQ-02"])])
114
+ self.assertEqual(oq_sync.cmd_answers(self.prof, snap, None), [])
115
+
116
+ def test_answer_without_oq_is_reported_unmatched(self):
117
+ rows = oq_sync.read_sheet(self.prof)
118
+ rec = dict(rows[1], answer="Blue.")
119
+ self.assertTrue(not rec["oq_ids"])
120
+ snap = os.path.join(self.tmp, "s.json")
121
+ oq_sync.cmd_answers(self.prof, None, snap)
122
+ with open(snap, encoding="utf-8") as f:
123
+ self.assertEqual(json.load(f).keys(), {"001"})
124
+
125
+ def _rows(self, items):
126
+ path = os.path.join(self.tmp, "rows.json")
127
+ with open(path, "w", encoding="utf-8") as f:
128
+ json.dump(items, f)
129
+ return path
130
+
131
+ def test_write_dry_run_changes_nothing(self):
132
+ before = read_bytes(self.book)
133
+ res = oq_sync.cmd_write(self.prof, self._rows([{"row": 5, "oq": "OQ-01",
134
+ "values": {"no": "003", "question": "[OQ-01] Max attachments?"}}]), False)
135
+ self.assertTrue(res["dry_run"])
136
+ self.assertEqual(read_bytes(self.book), before)
137
+
138
+ def test_write_apply_changes_only_the_sheet_part_and_extends_validation(self):
139
+ with zipfile.ZipFile(self.book) as z:
140
+ other_before = z.read("xl/worksheets/sheet2.xml")
141
+ res = oq_sync.cmd_write(self.prof, self._rows([
142
+ {"row": 5, "oq": "OQ-01", "values": {"no": "003", "question": "[OQ-01] Max attachments?", "asked_by": "us"}},
143
+ {"row": 6, "oq": "OQ-04", "values": {"no": "004", "question": "[OQ-04] Export encoding?", "asked_by": "us"}},
144
+ ]), True)
145
+ self.assertEqual(res["changed_parts"], ["xl/worksheets/sheet1.xml"])
146
+ self.assertTrue(os.path.exists(res["backup"]))
147
+ rows = {r["row"]: r for r in oq_sync.read_sheet(self.prof)}
148
+ self.assertEqual(rows[6]["oq_ids"], ["OQ-04"])
149
+ self.assertEqual(rows[3]["answer"], "Yes, 1 year.")
150
+ with zipfile.ZipFile(self.book) as z:
151
+ self.assertEqual(z.read("xl/worksheets/sheet2.xml"), other_before)
152
+ self.assertIn('sqref="B3:B6"', z.read("xl/worksheets/sheet1.xml").decode("utf-8"))
153
+
154
+ def test_write_refuses_unsafe_rows(self):
155
+ cases = [
156
+ {"row": 4, "oq": "OQ-01", "values": {"no": "002", "question": "[OQ-01] x"}}, # row holds a question
157
+ {"row": 5, "oq": "OQ-02", "values": {"no": "003", "question": "[OQ-02] x"}}, # OQ already in sheet
158
+ {"row": 5, "oq": "OQ-01", "values": {"no": "003", "question": "[OQ-01] x", "answer": "y"}},
159
+ {"row": 5, "oq": "OQ-01", "values": {"no": "003", "question": "no id here"}},
160
+ {"row": 5, "oq": "OQ-01", "values": {"no": "003", "question": "[OQ-01] x", "zzz": "?"}},
161
+ ]
162
+ for item in cases:
163
+ with self.subTest(item=item), self.assertRaises(oq_sync.SyncError):
164
+ oq_sync.cmd_write(self.prof, self._rows([item]), True)
165
+
166
+ def test_write_refuses_when_the_workbook_is_open(self):
167
+ with open(os.path.join(self.tmp, "~$qa.xlsx"), "w"):
168
+ pass
169
+ with self.assertRaises(oq_sync.SyncError):
170
+ oq_sync.cmd_write(self.prof, self._rows([{"row": 5, "oq": "OQ-01",
171
+ "values": {"no": "003", "question": "[OQ-01] x"}}]), True)
172
+
173
+
174
+ if __name__ == "__main__":
175
+ unittest.main()
@@ -0,0 +1,130 @@
1
+ ---
2
+ name: sdtk-db-design
3
+ description: Use when designing, reviewing, trimming or migrating a database schema or durable app state (tables, columns, keys, indexes, enums, queues, recovery records) - a new table or column is proposed, a legacy database is replaced, or a schema change may reach machines holding real user data.
4
+ ---
5
+
6
+ # SDTK-SPEC Database Design, Review and Migration
7
+
8
+ A schema is a set of claims about what must be remembered. Keep the smallest schema that serves a present, evidenced requirement. Every durable field needs a named writer, reader, recovery purpose, and owner-approved meaning.
9
+
10
+ The product owner decides product semantics. Establish evidence, distinguish product policy from implementation mechanics, propose the smallest safe design, and obtain sign-off before changing the schema of record.
11
+
12
+ ## Critical Constraints
13
+
14
+ 1. **Every durable field names a writer, a reader, a recovery purpose and the requirement that fails without it.**
15
+ No such requirement → cut or defer it, and record what would reopen it.
16
+ 2. **Read the DDL and every write path** before stating what a column means or which states exist; never infer a
17
+ rule from a table's shape.
18
+ 3. **Once any build can hold data that exists nowhere else, a schema change never drops and recreates.** Upgrade
19
+ ladder, engine backup, one transaction per step, refuse to open a newer database with an older client.
20
+ 4. **The product owner decides product semantics** (ownership, retention, recovery, conflict policy, external
21
+ field meaning). Stop and ask for those; propose the smallest design for everything else.
22
+ 5. **The schema of record changes only after sign-off**; superseded design text is marked with date and reason,
23
+ never deleted.
24
+
25
+ <!-- neutral-only -->
26
+ > **Installed as a runtime skill** (for example under `.codex/skills/`): read `toolkit/skills/sdtk-<name>/` in the
27
+ > paths below as the installed skill folder of that name.
28
+ <!-- /neutral-only -->
29
+
30
+ ## Modes and outputs
31
+
32
+ `sdtk-arch` writes `docs/database/DATABASE_SPEC_[FEATURE_KEY].md` from the toolkit's DATABASE_SPEC template.
33
+ This skill decides **what goes into it** and how it may change:
34
+
35
+ | Mode | When | Output |
36
+ |---|---|---|
37
+ | **design** | a new table / column is proposed, or a feature has DB impact | the fact inventory (section 8 of the DATABASE_SPEC template) with a verdict per column, then the tables of the spec |
38
+ | **review / trim** | an existing schema, before a release or a refactor | the inventory of the current DDL **and all write paths**, a verdict per column (keep / derive / fold / defer / cut), the evidence |
39
+ | **migration** | a schema change, a legacy replacement, or any build that can meet real data | the legacy column map, the upgrade ladder, the migration policy and its stop point |
40
+
41
+ Every mode follows `toolkit/skills/sdtk-db-design/references/REVIEW_PROCESS.md` for the evidence it needs, and ends
42
+ with proposals for the owner — the schema of record changes only after sign-off.
43
+
44
+ Examples in this skill come from two kinds of systems; apply the rule, not the domain:
45
+ - a **web application** (orders, order lines, customers): "store inputs, not rendered output" → keep `amount` and
46
+ `currency`, not `amount_display`; "stable identity" → an order is keyed by its id, never by its order number
47
+ when that number can be re-issued; "one meaning, one name" → `status` of an order and `status` of a payment are
48
+ different value sets, named `order_status` / `payment_status`;
49
+ - a **local client that syncs with a server** (files, queues, recovery records): the durable-workflow rules below.
50
+
51
+ ## Core principles
52
+
53
+ 1. **Start from durable facts, not feature names.** For each table and column, name the requirement that fails without it. Otherwise cut or defer it.
54
+ 2. **Do not duplicate or cache durable truth without a failure reason.** Prefer filesystem state, upstream records, or values derivable from stored facts when they remain available at recovery time. The other store must hold the *same* fact: a read-only attribute on disk does not say whether this app set it or the user did, so ownership of a change is still a fact worth one column.
55
+ 3. **Keep an object's attributes on its own row.** Avoid one-to-one side tables unless lifecycle, access, or retention genuinely differs.
56
+ 4. **Persist only what must survive restart or crash.** Keep process-only coordination in memory; persist the minimal recovery fact.
57
+ 5. **Preserve external semantics.** Copy externally owned IDs, timestamps, bitmasks, names, defaults, and error meanings verbatim. Do not invent a local enum over an upstream contract.
58
+ 6. **Make identity stable.** Do not use mutable names, paths, parents, or nullable values as an object's identity key. Treat a path as location, not identity.
59
+ 7. **Derive states from real writers.** Every enum value must have a writer; every writer must have a documented value. A queue that deletes successful rows does not have a durable `Done` state.
60
+ 8. **Give indexes one explicit job.** Each index enforces a named invariant or accelerates a named query. Match collation to the platform's identity rules, such as case-insensitive Windows paths.
61
+ 9. **Preserve real user data from the first shared-system build.** "Dev only" ends when any build can contain a user's only copy of queued work, edits, or settings.
62
+ 10. **One meaning, one name; different meanings, different names.** Unify columns that hold the same domain and value set. Never merge columns whose same numbers mean different things in each table.
63
+ 11. **Store inputs, not rendered output.** Do not persist a display string that is fully derivable from other columns; store only what the UI cannot rebuild (an error reason, a conflict copy's name).
64
+ 12. **Keep some data outside the database.** Secrets stay in an encrypted store unless the database is encrypted at rest. Anything needed after the database file is deleted (an uninstaller's cleanup path) lives elsewhere too.
65
+ 13. **No schema for unspecified features.** When a feature's spec has not been delivered, defer its tables and columns and record the trigger that reopens them.
66
+
67
+ ## Durable workflows, queues, and synchronization
68
+
69
+ Use these rules whenever a database coordinates local files, background work, or an external service.
70
+
71
+ - Treat a queue row as **durable intent**, not merely a log. Complete it only after the external system has confirmed the requested effect.
72
+ - When state, queue, and protection records must agree, update them in **one transaction**. Check affected-row counts: a successful SQLite commit can still contain an UPDATE or DELETE that matched zero rows.
73
+ - Do not assume "no exception" means success. Repositories that log and return zero require callers to verify their result.
74
+ - A missing local row is not evidence that an item is new. Guard the "empty DB + populated workspace" shape; suspend or require recovery rather than mass-uploading existing content.
75
+ - Preserve the authoritative baseline needed for conflict detection. Do not overwrite a server baseline with local timestamps, malformed external values, or a refresh that races with a locally modified item.
76
+ - For a crash-recoverable multi-step operation, write a durable manifest or intent before the first irreversible external/local step; make each step idempotent; verify independently before cleanup; remove the manifest last.
77
+ - Do not adopt an external object by name alone. Name collisions cannot prove ownership.
78
+ - A retry ID is safe as an idempotency key only when it identifies one immutable operation and payload. A queue ID reused after a payload rewrite must not be sent as such a key.
79
+ - Identify client/server atomicity gaps explicitly. A server success before the local commit cannot be made exactly-once by client-side preflight alone; require an upstream idempotency contract if exact-once is a requirement.
80
+
81
+ ## Migration and write safety
82
+
83
+ - Once real user data can exist, schema mismatch must not mean drop-and-recreate. Use an explicit upgrade ladder, one atomic transaction per step, and a backup made through the database engine before risky changes.
84
+ - Commit DDL and the schema-version bump together. Test that a version change has a corresponding upgrade step, and refuse to open a newer database with an older client.
85
+ - A rebuild-on-change policy is acceptable only while its written precondition is true: no machine can hold data worth preserving. Record when that policy expires.
86
+ - Preserve legacy behavior by mapping required facts column by column, not by copying legacy table shapes. Every unmapped field needs an explicit reason it is obsolete.
87
+
88
+ ## Process
89
+
90
+ 1. Pick the mode (table above) and gather the evidence REVIEW_PROCESS.md names for it.
91
+ 2. Inventory and challenge every field (core principles, durable-workflow rules).
92
+ 3. For migrations: answer "can real data exist?" first, then the ladder (migration rules).
93
+ 4. Stop for the owner on the questions under "Stop and clarify"; present proposals with evidence.
94
+ 5. After sign-off: update the DATABASE_SPEC (section 8 included), then code and tests.
95
+
96
+ ### Review workflow
97
+
98
+ For a new schema, a material change, a legacy replacement, or release to machines with data, read `toolkit/skills/sdtk-db-design/references/REVIEW_PROCESS.md` and produce the relevant evidence before implementation.
99
+
100
+ At minimum, inspect the DDL **and all write paths**. Schema shape alone does not establish a field's meaning, state transitions, or recovery guarantees.
101
+
102
+ ## Stop and clarify
103
+
104
+ Stop for owner or backend confirmation when any of these is unknown:
105
+
106
+ - a user-visible ownership, retention, recovery, or conflict policy;
107
+ - the semantic meaning/default of an external field or response;
108
+ - whether a migration may encounter real data;
109
+ - whether a backend accepts a client idempotency key and its exact replay/concurrency contract.
110
+
111
+ Do not stop merely because an internal transaction boundary, naming convention, or retry implementation is undecided; propose the smallest design consistent with the approved product policy.
112
+
113
+ ## Red flags - stop and re-check
114
+
115
+ - "Add the table now so we don't have to migrate later."
116
+ - A local enum invented over values that come from another system.
117
+ - A status value no code path writes, or a written value with no status name.
118
+ - A design rule inferred from a table's shape ("it has no parent column, so...") without grepping who writes the table.
119
+ - A column justified only by "might help debugging/UI" with no requirement or screen named.
120
+ - "It's only on dev machines" - check whether any build points at a shared server.
121
+ - Design doc, ERD, definition sheet and code disagreeing about a name or value.
122
+
123
+ ## Common mistakes
124
+
125
+ | Mistake | Fix |
126
+ |---|---|
127
+ | Proposing tables from requirement titles | Map each requirement to the facts it must remember across restarts |
128
+ | Renaming columns in docs and code in many small rounds | Agree names with stakeholders first, then change code once |
129
+ | Deleting superseded design text | Mark it superseded with date and reason; keep it under the current version |
130
+ | Showing internal notes or implementation status in customer copies | Strip to PK, defaults and enum values |